RoundCube

This example builds a cube with rounded edges and corners out of boolean shapes. It is a port to Geom4hep of the custom solid RoundCube defined in C++ in the UserLib example of Geant4.jl (UserLibrary.cpp), where it is a G4VSolid that delegates all its methods to a tree of G4UnionSolid and G4SubtractionSolid. It shows how to translate the boolean solids and the transformations of Geant4 to Geom4hep.

Note that

You can also download this example as a Jupyter notebook and a plain Julia source file.

Table of contents

Loading the modules

RotZXZ (rotations given by Euler angles) is not exported by Geom4hep, but it is available from the Rotations package that Geom4hep uses.

using Geom4hep, Geom4hep.Units
using Geom4hep.Rotations: RotZXZ
using LinearAlgebra
using CairoMakie: CairoMakie, Figure, Axis, LScene, heatmap!, Colorbar

const T = Float64;

From Geant4 to Geom4hep

The Geant4 solids map one to one to the Geom4hep shapes, with the same parameters:

Geant4Geom4hep
G4Box("cube", ca, ca, ca)Box{T}(ca, ca, ca)
G4Tubs("cyl", 0, r, ca, 0, 2 * M_PI)Tube{T}(0, r, ca, 0, 2π)
G4Orb("orb", r)Sphere{T}(0, r)
G4SubtractionSolid("s", A, B, t)BooleanSubtraction(A, B, t)
G4UnionSolid("u", A, B, t)BooleanUnion(A, B, t)

The transformations need more care. A G4Transform3D(rot, trans) places the second solid in the frame of the first one with the rotation rot applied to the solid, while a Transformation3D holds the rotation of the frame of the mother into the frame of the daughter, which is the inverse. A G4RotationMatrix(φ, θ, ψ) is built from Euler angles as the inverse of the rotation by φ around z, θ around the new x and ψ around the new z. The two inversions cancel, and G4Transform3D(G4RotationMatrix(φ, θ, ψ), G4ThreeVector(x, y, z)) becomes Transformation3D{T}(x, y, z, RotZXZ{T}(φ, θ, ψ)). A small helper makes the translation of the C++ code almost literal:

g4transform(x, y, z, φ=0, θ=0, ψ=0) = Transformation3D{T}(x, y, z, RotZXZ{T}(φ, θ, ψ));

Building the RoundCube

The C++ constructor RoundCube(a, r) translated line by line. A quarter s4 of the cube (a cube of side a/4 with three edges and one corner rounded with radius r) is cut out with subtractions. Four copies of it are glued to a central frame cube to make half of the cube, and the half is joined with itself rotated by π around z. The result is a cube of side a (half length a/2).

function roundcube(a, r)
    ca = a / 4
    cube  = Box{T}(ca, ca, ca)
    cyl   = Tube{T}(0, r, ca, 0, 2π)
    orb   = Sphere{T}(0, r)

    edge  = Box{T}(r, r, ca)
    vert  = Box{T}(r, r, r)
    frame = Box{T}(ca, ca, ca)

    # the material to remove along an edge (acyl) and at a corner (aorb)
    acyl1 = BooleanSubtraction(edge, cyl, g4transform(-r, -r, 0))
    acyl2 = BooleanSubtraction(edge, cyl, g4transform(-r, r, 0))
    acyl3 = BooleanSubtraction(edge, cyl, g4transform(r, r, 0))
    aorb  = BooleanSubtraction(vert, orb, g4transform(-r, -r, -r))

    # a corner of the cube with three rounded edges and a rounded vertex
    s1 = BooleanSubtraction(cube, acyl1, g4transform(ca, ca, 0))
    s2 = BooleanSubtraction(s1, acyl2, g4transform(ca, 0, ca, 0, π/2, 0))
    s3 = BooleanSubtraction(s2, acyl3, g4transform(0, ca, ca, 0, π/2, π/2))
    s4 = BooleanSubtraction(s3, aorb, g4transform(ca, ca, ca))

    # four corners around the frame make half of the cube (x > 0)
    u1 = BooleanUnion(frame, s4, g4transform(ca, ca, ca))
    u2 = BooleanUnion(u1, s4, g4transform(ca, ca, -ca, 0, π/2, 0))
    u3 = BooleanUnion(u2, s4, g4transform(ca, -ca, ca, 0, -π/2, 0))
    u4 = BooleanUnion(u3, s4, g4transform(ca, -ca, -ca, 0, π/2, π/2))

    # and the other half, rotated by π around z
    return BooleanUnion(u4, u4, g4transform(0, 0, 0, 0, 0, π))
end

a, r = 10cm, 1cm
rcube = roundcube(a, r);

The extent is the cube of side a:

extent(rcube)
([-50.00000000000001, -50.00000000000001, -50.0], [50.0, 50.0, 50.0])

Checking the shape

A rounded cube has a simple signed distance function: negative inside, positive outside. Comparing it with inside at random points checks every transformation of the construction (with the inverse rotations, thousands of points would disagree).

function sdf(p, h, r)
    q = abs.(p) .- (h - r)
    return norm(max.(q, 0)) - r + min(maximum(q), 0)
end
points = [Point3{T}((rand(3) .- 0.5) .* 1.2a) for _ in 1:100_000]
mismatches = count(points) do p
    d = sdf(p, a/2, r)
    abs(d) > 1e-6 && (inside(rcube, p) == kOutside) != (d > 0)
end
0

The volume, estimated by sampling for boolean shapes, can be compared with the exact one: a cube of side a - 2r, six slabs on its faces, quarter cylinders along the 12 edges and eighths of a sphere at the 8 corners.

b = a - 2r
exact = b^3 + 6b^2 * r + 3π * r^2 * b + 4π/3 * r^3
capacity(rcube) / exact
1.0000061359048178

Shape functions

The boolean shape answers all the shape functions. A ray along the diagonal enters the cube at a rounded corner, at a distance √3(a/2 - r) + r from the center:

dir = normalize(Vector3{T}(-1, -1, -1))
p = Point3{T}(10cm, 10cm, 10cm)
distance_to_in(rcube, p, dir), norm(p) - (√3 * (a/2 - r) + r)
(93.92304845413263, 93.92304845413264)

The normal on a rounded edge points away from the axis of the edge:

normal(rcube, Point3{T}(a/2 - r + r/√2, a/2 - r + r/√2, 1cm))
3-element Geom4hep.Vector3{Float64} with indices SOneTo(3):
 0.7071067811865476
 0.7071067811865476
 0.0

The operands touch along internal seams (the planes x = 0, y = 0 and z = 0), and overlap elsewhere (the central cube ends at ±a/4, inside the corners). Points on a seam are inside, and the points where a seam meets the surface are on the surface, with the normal of the surface. At the centre of a face, four operands meet:

p_seam, p_face = Point3{T}(0, 0, 3cm), Point3{T}(a/2, 0, 0)
inside(rcube, p_seam) == kInside, inside(rcube, p_face) == kSurface, normal(rcube, p_face)
(true, true, [1.0, 0.0, -0.0])

Checking the classification and the normals at random points of the surface, many of them on the seams or on the planes where the operands overlap:

function surface_point(q, h, r)                     # projection on the surface, and the normal
    c = clamp.(q, -(h - r), h - r)
    d = q - c
    norm(d) > 0 && return c + r * normalize(d), normalize(d)
    i = argmax(abs.(q))
    n = Vector3{T}(ntuple(j -> j == i ? sign(q[i]) : 0, 3))
    return Point3{T}(ntuple(j -> j == i ? sign(q[i]) * h : q[j], 3)), n
end
seams = (0, a/4, -a/4)
bad = 0
for _ in 1:5000
    q = (rand(3) .- 0.5) .* 1.2a
    for _ in 1:rand(0:2)
        q[rand(1:3)] = rand(seams)                  # move to one or two of these planes
    end
    p, n = surface_point(Point3{T}(q...), a/2, r)
    global bad += inside(rcube, p) != kSurface || normal(rcube, p) ⋅ n < 0.9999
end
bad
0

Drawing

The mesh of a boolean shape is computed with boolean operations on the meshes of its operands (csg_mesh), so draw shows the surface of the result. Here the RoundCube and one of its corners (s4, the right operand of the unions), also as a wireframe that shows the triangles of the mesh:

corner = rcube.left.right
fig = Figure(size=(900, 300))
draw!(LScene(fig[1, 1], show_axis=false), rcube)
draw!(LScene(fig[1, 2], show_axis=false), corner)
draw!(LScene(fig[1, 3], show_axis=false), corner; wireframe=true)
fig

The mesh is closed, and the volume it encloses is close to the exact one (the curved surfaces are approximated by 64 facets):

m = csg_mesh(rcube)
P, F = coordinates(m), faces(m)
sum(f -> P[f[1]] ⋅ (P[f[2]] × P[f[3]]), F) / 6 / exact
0.9994835331531164

draw_distance_to_in checks the surface independently of the mesh: it shoots random rays and draws the points where they enter the shape:

draw_distance_to_in(rcube, 50_000)

A slice of inside through a corner region shows the rounded edges and vertex:

xs = range(0, 0.6a, length=300)
fig = Figure(size=(900, 400))
for (i, z) in enumerate((0, a/2 - r/2))
    ax = Axis(fig[1, i], aspect=1, title="z = $(z) mm", xlabel="x (mm)", ylabel="y (mm)")
    heatmap!(ax, xs, xs, [Int(inside(rcube, Point3{T}(x, y, z))) for x in xs, y in xs], colormap=:grays)
end
fig

Using it in a geometry

Like any other shape, the RoundCube can fill volumes and be navigated. Here a few of them of different materials and radii of the edges are placed in a world box, and an X-ray image is made (see the Navigation example).

world = Volume{T}("world", Box{T}(40cm, 40cm, 15cm), Material{T}("air"; density=0.0012))
for (i, (radius, density)) in enumerate(((0.5cm, 2.7), (1.5cm, 7.87), (3cm, 11.35), (4cm, 1.0)))
    vol = Volume{T}("rcube$i", roundcube(20cm, radius), Material{T}("m$i"; density=density))
    x, y = (i - 1) % 2 == 0 ? -18cm : 18cm, (i - 1) ÷ 2 == 0 ? -18cm : 18cm
    place_daughter!(world, Transformation3D{T}(x, y, 0, 0, 0, π/8), vol)
end
model = close_geometry(world)
u, v, image, _ = xray(model, 3, 400)
fig = Figure(size=(600, 500))
ax = Axis(fig[1, 1], aspect=1, xlabel="x (mm)", ylabel="y (mm)")
hm = heatmap!(ax, u, v, image, colormap=:grays)
Colorbar(fig[1, 2], hm, label="mass thickness (g/cm³ × mm)")
fig

This page was generated using Literate.jl.