-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmarching.jl
More file actions
477 lines (405 loc) · 15.9 KB
/
marching.jl
File metadata and controls
477 lines (405 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
function assign_coordinates_at_point_in_plane!(
ixcoord,
ixvalues,
coordinates,
function_values,
node_index,
intersection_count
)
@views ixcoord[:, intersection_count] .= coordinates[:, node_index]
ixvalues[intersection_count] = function_values[node_index]
return nothing
end
function assign_coordinates_at_intersection!(
ixcoord,
ixvalues,
coordinates,
function_values,
planeq_values_start,
planeq_values_end,
node_index_start,
node_index_end,
intersection_count
)
t = planeq_values_start / (planeq_values_start - planeq_values_end)
@views @. ixcoord[:, intersection_count] = coordinates[:, node_index_start] + t * (coordinates[:, node_index_end] - coordinates[:, node_index_start])
ixvalues[intersection_count] = function_values[node_index_start] + t * (function_values[node_index_end] - function_values[node_index_start])
return nothing
end
"""
$(SIGNATURES)
Calculate intersections between tetrahedron with given piecewise linear
function data and plane
Adapted from [gltools](https://github.com/j-fu/gltools/blob/master/glm-3d.c#L341).
A non-empty intersection is either a triangle or a planar quadrilateral,
defined by either 3 or 4 intersection points between tetrahedron edges
and the plane.
Input:
- coordinates: 3xN array of grid point coordinates
- node_indices: 4 element array of node indices (pointing into coordinates and function_values)
- planeq_values: 4 element array of plane equation evaluated at the node coordinates
- function_values: N element array of function values
Mutates:
- ixcoord: 3x4 array of plane - tetedge intersection coordinates
- ixvalues: 4 element array of function values at plane - tetdedge intersections
Returns:
- amount_intersections,ixcoord,ixvalues
This method can be used both for the evaluation of plane sections and for
the evaluation of function isosurfaces.
"""
function calculate_plane_tetrahedron_intersection!(
ixcoord,
ixvalues,
coordinates,
node_indices,
planeq_values,
function_values;
tol = 0.0
)
# If all nodes lie on one side of the plane, no intersection
@fastmath if (
mapreduce(a -> a < -tol, *, planeq_values) ||
mapreduce(a -> a > tol, *, planeq_values)
)
return 0
end
amount_intersections = 0
@inbounds for n1 in 1:4
N1 = node_indices[n1]
if abs(planeq_values[n1]) < tol
amount_intersections += 1
assign_coordinates_at_point_in_plane!(ixcoord, ixvalues, coordinates, function_values, N1, amount_intersections)
else
for n2 in (n1 + 1):4
N2 = node_indices[n2]
if (abs(planeq_values[n2]) < tol) # We do not allow the 2nd node to be in the plane
continue
end
if planeq_values[n1] * planeq_values[n2] < tol^2
amount_intersections += 1
assign_coordinates_at_intersection!(ixcoord, ixvalues, coordinates, function_values, planeq_values[n1], planeq_values[n2], N1, N2, amount_intersections)
end
end
end
end
if amount_intersections > 4
@warn "computed $(amount_intersections) intersection points of a tetrahedron and a plane. Expected at most 4."
end
return amount_intersections
end
"""
We should be able to parametrize this
with a pushdata function which will remove one copy
step for GeometryBasics.mesh creation - perhaps a meshcollector struct we
can dispatch on.
flevel could be flevels
xyzcut could be a vector of plane data
perhaps we can also collect isolines.
Just an optional collector parameter, defaulting to something makie independent.
Better yet:
struct TetrahedronMarcher
...
end
tm=TetrahedronMarcher(planes,levels)
foreach tet
collect!(tm, tet_node_coord, node_function_values)
end
tm.colors=AbstractPlotting.interpolated_getindex.((cmap,), mcoll.vals, (fminmax,))
mesh!(collect(mcoll),backlight=1f0)
"""
"""
$(SIGNATURES)
Extract isosurfaces and plane interpolation for function on 3D tetrahedral mesh.
The basic observation is that locally on a tetrahedron, cuts with planes and isosurfaces
of P1 functions look the same. This method calculates data for several plane cuts and several
isosurfaces at once.
Input parameters:
- `coord`: 3 x n_points matrix of point coordinates
- `cellnodes`: 4 x n_cells matrix of point numbers per tetrahedron
- `func`: n_points vector of piecewise linear function values
- `planes`: vector of plane equations `ax+by+cz+d=0`,each stored as vector [a,b,c,d]
- `flevels`: vector of function isolevels
- `return_parent_cells`: if true, the parent cell indices are returned as a forth argument
Keyword arguments:
- `tol`: tolerance for tet x plane intersection
- `primepoints`: 3 x n_prime matrix of "corner points" of domain to be plotted. These are not in the mesh but are used to calculate the axis size e.g. by Makie
- `primevalues`: n_prime vector of function values in corner points. These can be used to calculate function limits e.g. by Makie
- `Tv`: type of function values returned
- `Tp`: type of points returned
- `Tf`: type of facets returned
Return values: (points, tris, values, [parents])
- `points`: vector of points (Tp)
- `tris`: vector of triangles (Tf)
- `values`: vector of function values (Tv)
- `parents`: vector of parent cell indices according to the `tris`
These can be readily turned into a mesh with function values on it.
Caveat: points with similar coordinates are not identified, e.g. an intersection of a plane and an edge will generate as many edge intersection points as there are tetrahedra adjacent to that edge. As a consequence, normal calculations for visualization always will end up with facet normals, not point normals, and the visual impression of a rendered isosurface will show its piecewise linear genealogy.
"""
function marching_tetrahedra(
coord::Matrix{Tc},
cellnodes::Matrix{Ti},
func,
planes,
flevels;
return_parent_cells = false,
tol = 1.0e-12,
primepoints = zeros(0, 0),
primevalues = zeros(0),
Tv = Float32,
Tp = SVector{3, Float32},
Tf = SVector{3, Int32}
) where {Tc, Ti}
return marching_tetrahedra(
[coord],
[cellnodes],
[func],
planes,
flevels;
return_parent_cells,
tol,
primepoints,
primevalues,
Tv,
Tp,
Tf
)
end
function marching_tetrahedra(
allcoords::Vector{Matrix{Tc}},
allcellnodes::Vector{Matrix{Ti}},
allfuncs,
planes,
flevels;
return_parent_cells = false,
tol = 1.0e-12,
primepoints = zeros(0, 0),
primevalues = zeros(0),
Tv = Float32,
Tp = SVector{3, Float32},
Tf = SVector{3, Int32}
) where {Tc, Ti}
# We could rewrite this for Meshing.jl
# CellNodes::Vector{Ttet}, Coord::Vector{Tpt}
nplanes = length(planes)
nlevels = length(flevels)
# Create output vectors
all_ixfaces = Vector{Tf}(undef, 0)
all_ixcoord = Vector{Tp}(undef, 0)
all_ixvalues = Vector{Tv}(undef, 0)
all_parentcells = Vector{Ti}(undef, 0)
@assert(length(primevalues) == size(primepoints, 2))
for iprime in 1:size(primepoints, 2)
@views push!(all_ixcoord, primepoints[:, iprime])
@views push!(all_ixvalues, primevalues[iprime])
end
planeq = zeros(4)
ixcoord = zeros(3, 6)
ixvalues = zeros(6)
cn = zeros(4)
node_indices = zeros(Int32, 4)
# Function to evaluate plane equation
@inbounds @fastmath plane_equation(plane, coord) = coord[1] * plane[1] + coord[2] * plane[2] + coord[3] * plane[3] + plane[4]
function pushtris(ns, ixcoord, ixvalues, itet)
# number of intersection points can be 3 or 4
if ns >= 3
last_i = length(all_ixvalues)
for is in 1:ns
@views push!(all_ixcoord, ixcoord[:, is])
push!(all_ixvalues, ixvalues[is]) # todo consider nan_replacement here
end
push!(all_ixfaces, (last_i + 1, last_i + 2, last_i + 3))
push!(all_parentcells, itet)
if ns == 4
push!(all_ixfaces, (last_i + 3, last_i + 2, last_i + 4))
push!(all_parentcells, itet)
end
end
return nothing
end
for igrid in 1:length(allcoords)
coord = allcoords[igrid]
cellnodes = allcellnodes[igrid]
func = allfuncs[igrid]
nnodes = size(coord, 2)
ntet = size(cellnodes, 2)
all_planeq = Vector{Float32}(undef, nnodes)
function calcxs()
return @inbounds for itet in 1:ntet
node_indices[1] = cellnodes[1, itet]
node_indices[2] = cellnodes[2, itet]
node_indices[3] = cellnodes[3, itet]
node_indices[4] = cellnodes[4, itet]
planeq[1] = all_planeq[node_indices[1]]
planeq[2] = all_planeq[node_indices[2]]
planeq[3] = all_planeq[node_indices[3]]
planeq[4] = all_planeq[node_indices[4]]
nxs = calculate_plane_tetrahedron_intersection!(
ixcoord,
ixvalues,
coord,
node_indices,
planeq,
func;
tol = tol
)
pushtris(nxs, ixcoord, ixvalues, itet)
end
end
@inbounds for iplane in 1:nplanes
@views @inbounds map!(
inode -> plane_equation(planes[iplane], coord[:, inode]),
all_planeq,
1:nnodes
)
calcxs()
end
# allocation free (besides push!)
@inbounds for ilevel in 1:nlevels
@views @inbounds @fastmath map!(
inode -> (func[inode] - flevels[ilevel]),
all_planeq,
1:nnodes
)
calcxs()
end
end
if return_parent_cells
return all_ixcoord, all_ixfaces, all_ixvalues, all_parentcells
else
return all_ixcoord, all_ixfaces, all_ixvalues
end
end
"""
$(SIGNATURES)
March through the given grid and extract points and values for given iso-line levels and/or given intersection lines.
From the returned point list and value list a line plot can be created.
Input:
coord: matrix storing the coordinates of the grid
cellnodes: connectivity matrix
func: function on the grid nodes to be evaluated
lines: vector of line definitions [a,b,c], s.t., ax + by + c = 0 defines a line
levels: vector of levels for the iso-surface
return_parent_cells: if true, a vector of parent cell indices according to the adjacencies is returned as a forth argument
Tc: scalar type of coordinates
Tp: vector type of coordinates
Tv: scalar type of function values
Output:
points: vector of 2D points of the intersections of the grid with the iso-surfaces or lines
adjacencies: vector of 2D vectors storing connected points in the grid
value: interpolated values of `func` at the intersection points
(optional) parents: indices on the parent grid cells
Note that passing both nonempty `lines` and `levels` will create a result with both types of points mixed.
"""
function marching_triangles(
coord::Matrix{T},
cellnodes::Matrix{Ti},
func,
lines,
levels;
return_parent_cells = false,
Tc = T,
Tp = SVector{2, Tc},
Tv = Float64
) where {T <: Number, Ti <: Number}
return marching_triangles([coord], [cellnodes], [func], lines, levels, return_parent_cells; Tc, Tp, Tv)
end
"""
$(SIGNATURES)
Variant of `marching_triangles` with multiple grid input
"""
function marching_triangles(
coords::Vector{Matrix{T}},
cellnodes::Vector{Matrix{Ti}},
funcs,
lines,
levels;
return_parent_cells = false,
Tc = T,
Tp = SVector{2, Tc},
Tv = Float64
) where {T <: Number, Ti <: Number}
points = Vector{Tp}(undef, 0)
values = Vector{Tv}(undef, 0)
adjacencies = Vector{SVector{2, Ti}}(undef, 0)
parents = Vector{Ti}(undef, 0)
for igrid in 1:length(coords)
func = funcs[igrid]
coord = coords[igrid]
# pre-allcate memory for triangle values (3 nodes per triangle)
objective_values = Vector{Tv}(undef, 3)
# the objective_func is used to determine the intersection (line equation or iso levels)
# the value_func is used to interpolate values at the intersections
function isect(tri_nodes, objective_func, value_func, itri)
(i1, i2, i3) = (1, 2, 3)
# 3 values of the objective function
f = objective_func
# sort f[i1] ≤ f[i2] ≤ f[i3]
f[1] <= f[2] ? (i1, i2) = (1, 2) : (i1, i2) = (2, 1)
f[i2] <= f[3] ? i3 = 3 : (i2, i3) = (3, i2)
f[i1] > f[i2] ? (i1, i2) = (i2, i1) : nothing
(n1, n2, n3) = (tri_nodes[i1], tri_nodes[i2], tri_nodes[i3])
dx31 = coord[1, n3] - coord[1, n1]
dx21 = coord[1, n2] - coord[1, n1]
dx32 = coord[1, n3] - coord[1, n2]
dy31 = coord[2, n3] - coord[2, n1]
dy21 = coord[2, n2] - coord[2, n1]
dy32 = coord[2, n3] - coord[2, n2]
df31 = f[i3] != f[i1] ? 1 / (f[i1] - f[i3]) : 0.0
df21 = f[i2] != f[i1] ? 1 / (f[i1] - f[i2]) : 0.0
df32 = f[i3] != f[i2] ? 1 / (f[i2] - f[i3]) : 0.0
if (f[i1] <= 0) && (0 < f[i3])
α = f[i1] * df31
x1 = coord[1, n1] + α * dx31
y1 = coord[2, n1] + α * dy31
value1 = value_func[n1] + α * (value_func[n3] - value_func[n1])
if (0 < f[i2])
α = f[i1] * df21
x2 = coord[1, n1] + α * dx21
y2 = coord[2, n1] + α * dy21
value2 = value_func[n1] + α * (value_func[n2] - value_func[n1])
else
α = f[i2] * df32
x2 = coord[1, n2] + α * dx32
y2 = coord[2, n2] + α * dy32
value2 = value_func[n2] + α * (value_func[n3] - value_func[n2])
end
push!(points, SVector{2, Tc}((x1, y1)))
push!(points, SVector{2, Tc}((x2, y2)))
push!(values, value1)
push!(values, value2)
# connect last two points
push!(adjacencies, SVector{2, Ti}((length(points) - 1, length(points))))
push!(parents, itri)
end
return
end
for itri in 1:size(cellnodes[igrid], 2)
# nodes of the current triangle
tri_nodes = @views cellnodes[igrid][:, itri]
for level in levels
# objective func is iso-level equation
@views @fastmath map!(
inode -> (func[inode] - level),
objective_values,
tri_nodes
)
@views isect(tri_nodes, objective_values, func, itri)
end
for line in lines
@fastmath line_equation(line, coord) = coord[1] * line[1] + coord[2] * line[2] + line[3]
# objective func is iso-level equation
@views @fastmath map!(
inode -> (line_equation(line, coord[:, inode])),
objective_values,
tri_nodes
)
@views isect(tri_nodes, objective_values, func, itri)
end
end
end
if return_parent_cells
return points, adjacencies, values, parents
else
return points, adjacencies, values
end
end