test_mesh.py 14.1 KB
Newer Older
1
2
3
4
5
6
7
8
#!/usr/bin/env python
#
# test_mesh.py -
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#


9
10
11
12
import os.path  as     op
import numpy    as     np
from   unittest import mock
import                 pytest
13

Paul McCarthy's avatar
Paul McCarthy committed
14
15
import fsl.transform.affine as affine
import fsl.data.mesh        as fslmesh
16

Paul McCarthy's avatar
Paul McCarthy committed
17
18
from . import tempdir

19

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# vertices of a cube
CUBE_VERTICES = np.array([
    [-1, -1, -1],
    [-1, -1,  1],
    [-1,  1, -1],
    [-1,  1,  1],
    [ 1, -1, -1],
    [ 1, -1,  1],
    [ 1,  1, -1],
    [ 1,  1,  1],
])

# triangles
# cw  == clockwise, when facing outwards
#        from the centre of the mesh
CUBE_TRIANGLES_CW = np.array([
    [0, 4, 6], [0, 6, 2],
    [1, 3, 5], [3, 7, 5],
    [0, 1, 4], [1, 5, 4],
    [2, 6, 7], [2, 7, 3],
    [0, 2, 1], [1, 2, 3],
    [4, 5, 7], [4, 7, 6],
])

# ccw == counter-clockwise
CUBE_TRIANGLES_CCW = np.array(CUBE_TRIANGLES_CW)
CUBE_TRIANGLES_CCW[:, [1, 2]] = CUBE_TRIANGLES_CCW[:, [2, 1]]

Paul McCarthy's avatar
Paul McCarthy committed
48
49
50
51
52
53
54
55
CUBE_CCW_FACE_NORMALS = np.array([
    [ 0,  0, -1], [ 0,  0, -1],
    [ 0,  0,  1], [ 0,  0,  1],
    [ 0, -1,  0], [ 0, -1,  0],
    [ 0,  1,  0], [ 0,  1,  0],
    [-1,  0,  0], [-1,  0,  0],
    [ 1,  0,  0], [ 1,  0,  0],
])
56

Paul McCarthy's avatar
Paul McCarthy committed
57
58
59
60
CUBE_CCW_VERTEX_NORMALS = np.zeros((8, 3))
for i in range(8):
    faces = np.where(CUBE_TRIANGLES_CCW == i)[0]
    CUBE_CCW_VERTEX_NORMALS[i] = CUBE_CCW_FACE_NORMALS[faces].sum(axis=0)
Paul McCarthy's avatar
Paul McCarthy committed
61
CUBE_CCW_VERTEX_NORMALS = affine.normalise(CUBE_CCW_VERTEX_NORMALS)
62
63


Paul McCarthy's avatar
Paul McCarthy committed
64
def test_mesh_create():
65

Paul McCarthy's avatar
Paul McCarthy committed
66
67
    verts = np.array(CUBE_VERTICES)
    tris  = np.array(CUBE_TRIANGLES_CCW)
68

Paul McCarthy's avatar
Paul McCarthy committed
69
    mesh = fslmesh.Mesh(tris, vertices=verts)
70

Paul McCarthy's avatar
Paul McCarthy committed
71
72
    print(str(mesh))

Paul McCarthy's avatar
Paul McCarthy committed
73
74
    assert mesh.name       == 'mesh'
    assert mesh.dataSource is None
Paul McCarthy's avatar
Paul McCarthy committed
75
    assert mesh.nvertices  == 8
Paul McCarthy's avatar
Paul McCarthy committed
76
77
    assert np.all(np.isclose(mesh.vertices, verts))
    assert np.all(np.isclose(mesh.indices,  tris))
78

Paul McCarthy's avatar
Paul McCarthy committed
79
    blo, bhi = mesh.bounds
80

Paul McCarthy's avatar
Paul McCarthy committed
81
82
    assert np.all(np.isclose(blo, verts.min(axis=0)))
    assert np.all(np.isclose(bhi, verts.max(axis=0)))
83
84


Paul McCarthy's avatar
Paul McCarthy committed
85
def test_mesh_addVertices():
86

Paul McCarthy's avatar
Paul McCarthy committed
87
88
89
90
    tris   = np.array(CUBE_TRIANGLES_CCW)
    verts  = np.array(CUBE_VERTICES)
    verts2 = np.array(CUBE_VERTICES) * 2
    verts3 = np.array(CUBE_VERTICES) * 3
91

Paul McCarthy's avatar
Paul McCarthy committed
92
    mesh = fslmesh.Mesh(tris, vertices=verts)
93

Paul McCarthy's avatar
Paul McCarthy committed
94
    assert mesh.selectedVertices() == 'default'
Paul McCarthy's avatar
Paul McCarthy committed
95
    assert mesh.vertexSets() == ['default']
Paul McCarthy's avatar
Paul McCarthy committed
96
    assert np.all(np.isclose(mesh.vertices, verts))
97

Paul McCarthy's avatar
Paul McCarthy committed
98
    assert np.all(np.isclose(mesh.addVertices(verts2, 'twotimes'), verts2))
99

Paul McCarthy's avatar
Paul McCarthy committed
100
    assert mesh.selectedVertices() == 'twotimes'
Paul McCarthy's avatar
Paul McCarthy committed
101
    assert mesh.vertexSets() == ['default', 'twotimes']
Paul McCarthy's avatar
Paul McCarthy committed
102
    assert np.all(np.isclose(mesh.vertices, verts2))
103

Paul McCarthy's avatar
Paul McCarthy committed
104
    assert np.all(np.isclose(mesh.addVertices(verts3, 'threetimes', select=False), verts3))
105

Paul McCarthy's avatar
Paul McCarthy committed
106
    assert mesh.selectedVertices() == 'twotimes'
Paul McCarthy's avatar
Paul McCarthy committed
107
    assert mesh.vertexSets() == ['default', 'twotimes', 'threetimes']
Paul McCarthy's avatar
Paul McCarthy committed
108
    assert np.all(np.isclose(mesh.vertices, verts2))
109

Paul McCarthy's avatar
Paul McCarthy committed
110
    mesh.vertices = 'threetimes'
111

Paul McCarthy's avatar
Paul McCarthy committed
112
113
    assert mesh.selectedVertices() == 'threetimes'
    assert np.all(np.isclose(mesh.vertices, verts3))
114

Paul McCarthy's avatar
Paul McCarthy committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    with pytest.raises(ValueError):
        mesh.addVertices(verts[:-1, :], 'badverts')


def test_loadVertices():

    tris  = np.array(CUBE_TRIANGLES_CCW)
    verts = np.array(CUBE_VERTICES)

    mesh = fslmesh.Mesh(tris, vertices=verts)

    with tempdir():

        verts2 = verts * 2

        np.savetxt('verts2.txt', verts2)

        assert np.all(np.isclose(mesh.loadVertices('verts2.txt'), verts2))

        assert mesh.selectedVertices() == op.abspath('verts2.txt')

        np.savetxt('badverts.txt', verts2[:-1, :])

        with pytest.raises(ValueError):
            mesh.loadVertices('badverts.txt')

141

Paul McCarthy's avatar
Paul McCarthy committed
142
def test_mesh_addVertexData():
143

Paul McCarthy's avatar
Paul McCarthy committed
144
145
    mesh = fslmesh.Mesh(np.array(CUBE_TRIANGLES_CCW),
                        vertices=np.array(CUBE_VERTICES))
146

Paul McCarthy's avatar
Paul McCarthy committed
147
    nverts = CUBE_VERTICES.shape[0]
148

Paul McCarthy's avatar
Paul McCarthy committed
149
150
151
    data3D   = np.random.randint(1, 100,  nverts)
    data3_1D = np.random.randint(1, 100, (nverts, 1))
    data4D   = np.random.randint(1, 100, (nverts, 20))
Paul McCarthy's avatar
Paul McCarthy committed
152
    dataBad  = np.random.randint(1, 100, (nverts - 1, 20))
153

Paul McCarthy's avatar
Paul McCarthy committed
154
155
156
157
158
159
160
161
    assert np.all(np.isclose(mesh.addVertexData('3d',   data3D),   data3D.reshape(-1, 1)))
    assert list(mesh.vertexDataSets()) == ['3d']

    assert np.all(np.isclose(mesh.addVertexData('3_1d', data3_1D), data3_1D))
    assert list(mesh.vertexDataSets()) == ['3d', '3_1d']

    assert np.all(np.isclose(mesh.addVertexData('4d',   data4D),   data4D))
    assert list(mesh.vertexDataSets()) == ['3d', '3_1d', '4d']
162

Paul McCarthy's avatar
Paul McCarthy committed
163
164
165
    assert mesh.getVertexData('3d')  .shape == (nverts, 1)
    assert mesh.getVertexData('3_1d').shape == (nverts, 1)
    assert mesh.getVertexData('4d')  .shape == (nverts, 20)
166

Paul McCarthy's avatar
Paul McCarthy committed
167
168
169
    assert np.all(np.isclose(data3D.reshape(-1, 1), mesh.getVertexData('3d')))
    assert np.all(np.isclose(data3_1D,              mesh.getVertexData('3_1d')))
    assert np.all(np.isclose(data4D,                mesh.getVertexData('4d')))
170

Paul McCarthy's avatar
Paul McCarthy committed
171
    mesh.clearVertexData()
172

Paul McCarthy's avatar
Paul McCarthy committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    with pytest.raises(KeyError):   mesh.getVertexData('3d')
    with pytest.raises(KeyError):   mesh.getVertexData('3_1d')
    with pytest.raises(KeyError):   mesh.getVertexData('4d')
    with pytest.raises(ValueError): mesh.addVertexData('bad', dataBad)


def test_loadVertexData():

    verts = np.array(CUBE_VERTICES)
    tris  = np.array(CUBE_TRIANGLES_CCW)
    vdata = np.random.randint(1, 100, verts.shape[0]).reshape(-1, 1)
    mesh  = fslmesh.Mesh(tris, vertices=verts)

    with tempdir():
Paul McCarthy's avatar
Paul McCarthy committed
187
188
        np.savetxt('vdata.txt',    vdata)
        np.savetxt('badvdata.txt', vdata[:-1])
Paul McCarthy's avatar
Paul McCarthy committed
189
190
191
192
193
194
195

        key = op.abspath('vdata.txt')

        assert np.all(np.isclose(mesh.loadVertexData(key), vdata))
        assert np.all(np.isclose(mesh.getVertexData( key), vdata))
        assert np.all(np.isclose(mesh.loadVertexData(key, 'vdkey'), vdata))
        assert np.all(np.isclose(mesh.getVertexData(      'vdkey'), vdata))
196

Paul McCarthy's avatar
Paul McCarthy committed
197
198
199
        with pytest.raises(ValueError):
            mesh.loadVertexData('badvdata.txt')

200
201
202
203

def test_normals():

    # vertices of a cube
204
205
206
    verts         = np.array(CUBE_VERTICES)
    triangles_cw  = np.array(CUBE_TRIANGLES_CW)
    triangles_ccw = np.array(CUBE_TRIANGLES_CCW)
Paul McCarthy's avatar
Paul McCarthy committed
207
208
209
210
211
212
213
    fnormals      = np.array(CUBE_CCW_FACE_NORMALS)
    vnormals      = np.array(CUBE_CCW_VERTEX_NORMALS)

    cw_nofix  = fslmesh.Mesh(np.array(triangles_cw))
    cw_fix    = fslmesh.Mesh(np.array(triangles_cw))
    ccw_nofix = fslmesh.Mesh(np.array(triangles_ccw))
    ccw_fix   = fslmesh.Mesh(np.array(triangles_ccw))
214

Paul McCarthy's avatar
Paul McCarthy committed
215
216
217
218
    cw_nofix .addVertices(np.array(verts))
    cw_fix   .addVertices(np.array(verts), fixWinding=True)
    ccw_nofix.addVertices(np.array(verts))
    ccw_fix  .addVertices(np.array(verts), fixWinding=True)
219
220
221
222
223
224
225
226

    # ccw triangles should give correct
    # normals without unwinding
    assert np.all(np.isclose(cw_nofix .normals,  -fnormals))
    assert np.all(np.isclose(cw_nofix .vnormals, -vnormals))
    assert np.all(np.isclose(cw_fix   .normals,   fnormals))
    assert np.all(np.isclose(cw_fix   .vnormals,  vnormals))
    assert np.all(np.isclose(ccw_nofix.normals,   fnormals))
Paul McCarthy's avatar
Paul McCarthy committed
227
    assert np.all(np.isclose(ccw_nofix.vnormals,  vnormals))
228
229
    assert np.all(np.isclose(ccw_fix  .normals,   fnormals))
    assert np.all(np.isclose(ccw_fix  .vnormals,  vnormals))
230

Paul McCarthy's avatar
Paul McCarthy committed
231
232
233
234
235
236
    # Test standalone calcFaceNormals/
    # calcVertexNormals functions
    assert np.all(np.isclose(
        -fnormals, fslmesh.calcFaceNormals(verts, triangles_cw)))
    assert np.all(np.isclose(
        fnormals, fslmesh.calcFaceNormals(verts, triangles_ccw)))
237
238
239
240
241
242
243

    # Make sure result is (1, 3) for input of (1, 3)
    onetri = np.atleast_2d(triangles_ccw[0, :])
    result = fslmesh.calcFaceNormals(verts, onetri)
    assert result.shape == (1, 3)
    assert np.all(np.isclose(fnormals[0, :], result))

Paul McCarthy's avatar
Paul McCarthy committed
244
245
246
247
248
249
250
251
252
253
254
    assert np.all(np.isclose(
        -vnormals, fslmesh.calcVertexNormals(verts, triangles_cw, -fnormals)))
    assert np.all(np.isclose(
        vnormals, fslmesh.calcVertexNormals(verts, triangles_ccw, fnormals)))


def test_needsFixing():

    verts    = np.array(CUBE_VERTICES)
    tris_cw  = np.array(CUBE_TRIANGLES_CW)
    tris_ccw = np.array(CUBE_TRIANGLES_CCW)
Paul McCarthy's avatar
Paul McCarthy committed
255
    fnormals = np.array(CUBE_CCW_FACE_NORMALS)
Paul McCarthy's avatar
Paul McCarthy committed
256
257
    blo      = verts.min(axis=0)
    bhi      = verts.max(axis=0)
258
    mesh     = fslmesh.Mesh(tris_cw, vertices=verts, fixWinding=True)
Paul McCarthy's avatar
Paul McCarthy committed
259
260
261

    assert not fslmesh.needsFixing(verts, tris_ccw, fnormals, blo, bhi)
    assert     fslmesh.needsFixing(verts, tris_cw, -fnormals, blo, bhi)
262
    assert     np.all(np.isclose(mesh.indices, tris_ccw))
263

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
    # regression: needsFixing used to use the first triangle
    # of the nearest vertex to the camera. But this will fail
    # if that triangle is facing away from the camera.
    verts = np.array([
        [ -1,    -1,   -1], # vertex 0 will be nearest the camera
        [  0.5,  -0.5,  0],
        [  1,    -1,    0],
        [  1,     1,    1],
        [  0,    -1,    1]])
    tris = np.array([
        [0, 4, 1], # first triangle will be facing away from the camera
        [0, 1, 2],
        [1, 3, 2],
        [0, 2, 4],
        [2, 3, 4],
        [1, 4, 3]])
    mesh     = fslmesh.Mesh(tris, vertices=verts, fixWinding=True)
    fnormals = fslmesh.calcFaceNormals(verts, tris)
    blo      = verts.min(axis=0)
    bhi      = verts.max(axis=0)
    assert not fslmesh.needsFixing(verts, tris, fnormals, blo, bhi)

286
287
288

def test_trimesh_no_trimesh():

289
290
291
292
293
294
295
    # Make sure trimesh and rtree
    # are imported before messing
    # with sys.modules, otherwise
    # weird things can happen.
    import trimesh
    import rtree

296
297
298
299
    mods = ['trimesh', 'rtree']

    for mod in mods:
        with mock.patch.dict('sys.modules', **{mod : None}):
Paul McCarthy's avatar
Paul McCarthy committed
300

Paul McCarthy's avatar
Paul McCarthy committed
301
302
303
            verts = np.array(CUBE_VERTICES)
            tris  = np.array(CUBE_TRIANGLES_CCW)
            mesh  = fslmesh.Mesh(tris, vertices=verts)
Paul McCarthy's avatar
Paul McCarthy committed
304

Paul McCarthy's avatar
Paul McCarthy committed
305
            assert mesh.trimesh is None
Paul McCarthy's avatar
Paul McCarthy committed
306
307
            locs, tris = mesh.rayIntersection([[0, 0, 0]], [[0, 0, 1]])
            assert locs.size == 0
308
            assert tris.size == 0
309

Paul McCarthy's avatar
Paul McCarthy committed
310
311
            nverts, idxs, dists = mesh.nearestVertex([[0, 0, 0]])
            assert nverts.size == 0
312
313
314
315
316
317
318
            assert idxs.size  == 0
            assert dists.size == 0

            lines, faces = mesh.planeIntersection([0, 0, 1], [0, 0, 0])
            assert lines.size == 0
            assert faces.size == 0

319

320
@pytest.mark.meshtest
321
322
323
324
def test_trimesh():

    import trimesh

Paul McCarthy's avatar
Paul McCarthy committed
325
326
327
328
    verts = np.array(CUBE_VERTICES)
    tris  = np.array(CUBE_TRIANGLES_CCW)

    mesh = fslmesh.Mesh(tris, vertices=verts)
Paul McCarthy's avatar
Paul McCarthy committed
329
    assert isinstance(mesh.trimesh, trimesh.Trimesh)
330
331


332
@pytest.mark.meshtest
333
334
335
336
def test_rayIntersection():

    verts     = np.array(CUBE_VERTICES)
    triangles = np.array(CUBE_TRIANGLES_CCW)
Paul McCarthy's avatar
Paul McCarthy committed
337
    mesh      = fslmesh.Mesh(triangles, vertices=verts)
338
339
340
341
342
343
344

    for axis in range(3):
        rayOrigin       = [0, 0, 0]
        rayDir          = [0, 0, 0]
        rayOrigin[axis] = -2
        rayDir[   axis] =  1

Paul McCarthy's avatar
Paul McCarthy committed
345
        loc, tri = mesh.rayIntersection([rayOrigin], [rayDir])
346

Paul McCarthy's avatar
Paul McCarthy committed
347
348
349
350
        assert loc.shape == (1, 3)
        assert tri.shape == (1,)

        expected          = np.array([[0, 0, 0]])
351
352
        expected[0, axis] = -1

Paul McCarthy's avatar
Paul McCarthy committed
353
        assert np.all(np.isclose(loc, expected))
354

Paul McCarthy's avatar
Paul McCarthy committed
355
    loc, tri = mesh.rayIntersection([[-2, -2, -2]], [[-1, -1, -1]])
356
357
358

    assert loc.size == 0
    assert tri.size == 0
Paul McCarthy's avatar
Paul McCarthy committed
359
360


361
@pytest.mark.meshtest
Paul McCarthy's avatar
Paul McCarthy committed
362
363
364
365
def test_nearestVertex():

    verts     = np.array(CUBE_VERTICES)
    triangles = np.array(CUBE_TRIANGLES_CCW)
Paul McCarthy's avatar
Paul McCarthy committed
366
    mesh      = fslmesh.Mesh(triangles, vertices=verts)
Paul McCarthy's avatar
Paul McCarthy committed
367
368
369
370
371
372

    nverts, nidxs, ndists = mesh.nearestVertex(verts * 2)

    assert np.all(np.isclose(nverts, verts))
    assert np.all(np.isclose(nidxs,  np.arange(len(verts))))
    assert np.all(np.isclose(ndists, np.sqrt(3)))
373
374


375
@pytest.mark.meshtest
376
377
378
379
def test_planeIntersection():

    verts     = np.array(CUBE_VERTICES)
    triangles = np.array(CUBE_TRIANGLES_CCW)
Paul McCarthy's avatar
Paul McCarthy committed
380
    mesh      = fslmesh.Mesh(triangles, vertices=verts)
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444

    normal = [0, 0, 1]
    origin = [0, 0, 0]

    lines,  faces         = mesh.planeIntersection(normal, origin)
    lines2, faces2, dists = mesh.planeIntersection(normal,
                                                   origin,
                                                   distances=True)

    expLines = np.array([
        [[-1, -1,  0],
         [ 0, -1,  0]],
        [[ 1, -1,  0],
         [ 0, -1,  0]],

        [[ 1,  1,  0],
         [ 0,  1,  0]],

        [[-1,  1,  0],
         [ 0,  1,  0]],

        [[-1,  0,  0],
         [-1, -1,  0]],

        [[-1,  0,  0],
         [-1,  1,  0]],

        [[ 1,  0,  0],
         [ 1, -1,  0]],

        [[ 1,  0,  0],
         [ 1,  1,  0]]])

    expFaces = np.array([ 4,  5,  6,  7,  8,  9, 10, 11])
    expDists = np.array([
        [[0.5, 0,   0.5],
         [0,   0.5, 0.5]],

        [[0,   0.5, 0.5],
         [0.5, 0.5, 0]],

        [[0,   0.5, 0.5],
         [0.5, 0.5, 0]],

        [[0.5, 0.5, 0],
         [0.5, 0,   0.5]],

        [[0,   0.5, 0.5],
         [0.5, 0.5, 0]],

        [[0.5, 0,   0.5],
         [0,   0.5, 0.5]],

        [[0.5, 0.5, 0],
         [0.5, 0,   0.5]],

        [[0.5, 0,   0.5],
         [0,   0.5, 0.5]]])

    assert np.all(np.isclose(lines, lines2))
    assert np.all(np.isclose(faces, faces2))
    assert np.all(np.isclose(lines, expLines))
    assert np.all(np.isclose(faces, expFaces))
    assert np.all(np.isclose(dists, expDists))
Paul McCarthy's avatar
Paul McCarthy committed
445
446
447
448
449
450
451
452
453
454
455

    normal = [0, 0, 1]
    origin = [3, 3, 3]

    lines, faces, dists = mesh.planeIntersection(normal,
                                                 origin,
                                                 distances=True)

    assert lines.shape  == (0, 2, 3)
    assert faces.shape  == (0, )
    assert dists.shape  == (0, 2, 3)
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471


def test_mesh_different_winding_orders():

    verts1    =  CUBE_VERTICES
    verts2    = -CUBE_VERTICES
    tris      =  CUBE_TRIANGLES_CCW
    trisfixed =  CUBE_TRIANGLES_CW

    mnofix = fslmesh.Mesh(tris)
    mfix   = fslmesh.Mesh(tris)

    mnofix.addVertices(verts1, key='v1', fixWinding=False)
    mnofix.addVertices(verts2, key='v2', fixWinding=False)
    mfix  .addVertices(verts1, key='v1', fixWinding=True)
    mfix  .addVertices(verts2, key='v2', fixWinding=True)
Paul McCarthy's avatar
Paul McCarthy committed
472
    mfix  .addVertices(verts1, key='v3', fixWinding=True, select=False)
473
474
475
476
477
478
479
480
481
482

    mnofix.vertices = 'v1'
    assert np.all(mnofix.indices == tris)
    mnofix.vertices = 'v2'
    assert np.all(mnofix.indices == tris)

    mfix.vertices = 'v1'
    assert np.all(mfix.indices == tris)
    mfix.vertices = 'v2'
    assert np.all(mfix.indices == trisfixed)
Paul McCarthy's avatar
Paul McCarthy committed
483
484
    mfix.vertices = 'v3'
    assert np.all(mfix.indices == tris)