On 10/03/2014 at 05:03, xxxxxxxx wrote:
There are many resources for maths online.
import c4d
import random
def iszero(x) :
r""" Returns True if *x* is near zero. """
return abs(x) < 1.0e-07
def perpendicular_vector(v) :
r""" Finds an arbitrary perpendicular vector to *v*. Sort of a lazy
implementation.. """
a, b = random.random(), random.random()
if not iszero(v.z) :
x, y, z = v.x, v.y, v.z
elif not iszero(v.y) :
x, y, z = v.x, v.z, v.y
elif not iszero(v.x) :
x, y, z = v.y, v.z, v.x
else:
raise ValueError('zero-vector')
c = (- x * a - y * b) / z
if not iszero(v.z) :
return c4d.Vector(a, b, c)
elif not iszero(v.y) :
return c4d.Vector(a, c, b)
elif not iszero(v.x) :
return c4d.Vector(b, c, a)
def describe_line(a, b) :
r""" Returns a description of a line based on the two
points *a* and *b* in space. *a* and *b* must not equal. """
assert a != b
return (a, (b - a))
def is_point_on_line(line, p) :
r""" Checks if the point *p* is element of the specified
*line*. """
d_a = (line[0] - p).Dot(line[1])
return iszero(d_a)
def describe_plane(a, b, c) :
r""" Returns a description of a plane based on tree
points *a*, *b* and *c* in space. *a*, *b* and *c* must
not equal and *c* must not be on the same line described
by *a* and *b*. """
assert a != b
assert a != c
assert not is_point_on_line(describe_line(a, b), c)
return (a, (b - a), (c - a))
def plane_normal(plane) :
r""" Returns the normal of the *plane*. """
return plane[1].Cross(plane[2]).GetNormalized()
def get_plane(name) :
r""" Returns the description of a plane based on the
specified *name*. The following values are accepted:
- *XZ*, *ZX*, *floor*
- *XY*, *YX*, *front*
- *YZ*, *ZY*, *right* """
name = name.lower()
if name in ('xz', 'zx', 'floor') :
n = c4d.Vector(0, 1, 0)
elif name in ('xy', 'yx', 'front') :
n = c4d.Vector(0, 0, 1)
elif name in ('yz', 'zy', 'right') :
n = c4d.Vector(1, 0, 0)
else:
raise ValueError
x1 = perpendicular_vector(n)
y1 = x1.Cross(n).GetNormalized()
return describe_plane(x1, y1, c4d.Vector(0))
def find_intersection(line, plane) :
r""" Finds the intersection of the *line* and *plane*.
Returns None if the line does not intersect the plane or
is element of it. """
n = plane_normal(plane)
d_a = (plane[0] - line[0]).Dot(n)
d_b = line[1].Dot(n)
if iszero(d_a) or iszero(d_b) :
# No intersection or line is part of the plane.
return None
return line[0] + (d_a / d_b) * line[1]
from c4d import Vector as V
line = describe_line(V(100), V(-100))
plane = get_plane('floor')
print find_intersection(line, plane)
Cheers,
-Niklas