# distance to a curved box

 How to compute the distance to a rounded box: ``` float distToCBox( vec3 pos, vec3 box, float rad ) { return length( max( abs(pos) - box + vec3(rad), 0.0 ) ) - rad; } ``` pos, position in space of the point box, size of the box in x, y and z (half size) rad, radious of the curved borders The box is of course centered at the origin and aligned to the xyz axes – you will have to pretransform the point to get the distance to an arbitrarily rotated and translated curved cube.

## 4 thoughts on “distance to a curved box”

1. Jan

You could use 8 spheres with the same radius as the rounded edge and position them in the corners. Then, find out which of the sphere-centers is nearest to position X, calculate the distance and subtract the radius.

Hey, how do you think I found that formula? 🙂

The formula above computes the distance to 6 planes, 12 cylinders and 8 spheres but in a much more compact and efficient way that what you propose.

3. Lex

NICE!

To compare, I came up with the following kludzy way of just rounding off 4 sides of a pillar while playing with ‘4kgfxmon_pack’, doing some distance-field raymarching. So that’s not even including the rounded spherical corners like in your code.

float roundedPillar(vec3 p, vec4 plr, float radius)
{
float dist = 1000;
float size = plr.w;
vec3 rel = p-plr.xyz;
if (rel.x > size)
{
if(rel.z > -size && rel.z < size)
dist = rel.x – size;
else
{
if (rel.z < -size)
dist = length(rel.xz-vec2(size, -size));
else
dist = length(rel.xz-vec2(size, size));
}
}
else
{
if(rel.x -size && rel.z < size)
dist = -(rel.x+size);
else
{
if(rel.z size)
dist = rel.z – size;
else
dist = -(rel.z+size);
}
}