Code covered by the BSD License

### Highlights fromgeom3d

4.75

4.8 | 21 ratings Rate this file 322 Downloads (last 30 days) File Size: 421 KB File ID: #24484

# geom3d

19 Jun 2009 (Updated 27 Nov 2012)

Library to handle 3D geometric primitives: create, intersect, display, and make basic computations

### Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

File Information
Description

The aim of geom3d library is to handle and visualize 3D geometric primitives such as points, lines, planes, polyhedra... It provides low-level functions for manipulating 3D geometric primitives, making easier the development of more complex geometric algorithms.

Some features of the library are:

- creation of various shapes (3D points, 3D lines, planes, polyhedra...) through an intuitive syntax. Ex:
createPlane(p1, p2, p3) to create a plane through 3 points.

- derivation of new shapes: intersection between 2 planes, intersection between a plane and a line, between a sphere and a line...

- functions for 3D polygons and polyhedra. Polyhedra use classical vertex-faces arrays (face array contain indices of vertices), and support faces with any number of vertices. Some basic models are provided (createOctaedron, createCubeoctaedron...), as well as some computation (like faceNormal or centroid)

- manipulation of planar transformation. Ex.:
ROT = createRotationOx(THETA);
P2 = transformPoint3d(P1, ROT);

- direct drawing of shapes with specialized functions. Clipping is performed automatically for unbounded shapes such as lines or rays. Ex:
drawPoint3d([50 50 25; 20 70 10], 'ro'); % draw some points
drawLine3d([X0 Y0 Z0 DX DY DZ]); % clip and draw straight line

The library is divided into two packages:
* geom3d for general computation in 3d
* meshes3d for representation and manipulation of polyhedral meshes

Several functions require the geom2d package, available on the FEx.

Additional help is provided in geom3d/Contents.m and meshes3d/Contents.m files, as well as summary files like 'points3d.m' or 'lines3d.m'.

Acknowledgements

This file inspired Image Ellipsoid 3 D and Intersect Plane Surf Ii.

MATLAB release MATLAB 7.9 (R2009b)
Other requirements Some functions require the geom2d library, also on the File Exchange (ID 7844)
Tags for This File
Everyone's Tags
Tags I've Applied
10 Jun 2013

Hi Khaled,
thanks for reporting problem. I will check behaviour for points given in spherical coords. The function works fine with points given as cartesian coordinates (assuming sphere is centered), so I hope this could help using the function.

Regards,
David

04 Jun 2013

With all respect for this valuable submission. I do have some slight critique. I downloaded geom3d to "quickly" check against my code for the determination of the spherical angle, as the function "sphericalAngle" promised. I only called sphericalAngle exactly as indicated in its help. I ended up wasting two hours of quality time ploughing through various fixes. [1] calls to functions whose names have been changed. Sorry , but I just stopped keeping track(some have already been mentioned in these comments) and [2] createPlane, was called from within sphericalAngle apparently with the wrong dimensions. [3] intersectLinePlane complained about matrix dimension mismatch on line 71. Honestly, I consider perseverance one of my strenghts, but I gave up at this point, as I can't say how much more time this really simple operation would/should cost me should I continue with geom3d. Sorry, but a smooth program flow is really important, especially in extensive code submissions such as this one.

28 May 2013

Hi Orestis,

You can check the function 'intersectPlaneMesh', that computes the 3D polygon resulting from the intersection of a polygonal mesh with a plane. The algorithm used is simple, so there can be numerical issues. Then you can compute the area with the function 'polygonArea3d'. By considering several planes, you should be able to do what you want.

There is no function in geom3d for reading STL files. So you should either write yout own, or find one.

regards,
David

27 May 2013

Dear David

Could you let me know if your library can be used i order to slice a 3d stl file with arbitrary planes?

The aim is to calculate the area bounded by the stl file in each slice.

With best regards

11 Mar 2013

Dear Dmitri,

thank you for your feedback! Actually, many functions require the geom2d contribution to work properly. I try to make geom3d as independent and self-contained as possible, but downloading geom2d as well is strongly recommended. I will update the different functions you mentioned to remove/reduce dependencies.

Regards,
David

08 Mar 2013

Great package! Some minor bugs:

1. circleToPolygon function is missing. It is called in demoRevolutionSurface,
drawTorus and torusMesh.
2. vectorNorm is now vectorNorm3d. It is used in intersectLineTriangle3d, triangleArea3d.
3. drawEdge is now drawEdge3d. It is used in demoGeom3d.

08 Mar 2013

One more bug: circleToPolygon function is missing. It is called in demoRevolutionSurface, drawTorus and torusMesh.

13 Feb 2013

@Sven
I am sorry , but I didn't know that point of view for plane creation. My background bibliography doesn't include such information.Thank you for informing me.

12 Feb 2013

@panagiotis: I highly recommend reading *again* the documentation for createPlane - it is very short and very clear, but your comment shows you still have a misunderstanding.

You seem to think that "3 points are a plane". This is not true. A plane is like a coordinate system - it has:

- An origin POINT
- An X-direction VECTOR
- A Y-direction VECTOR

You can *create* a plane from 3 points, but a plane is *not* just 3 points. When you read the help for createPlane, you will see the first example which shows you *exactly how* to create a plane from 3 points:

PLANE = createPlane(Pt1,Pt2,Pt3)

You will see that PLANE is NOT EQUAL to [Pt1,Pt2,Pt3]. There are *very* good reasons for this which you will understand once you read the help for createPlane.

12 Feb 2013

@David
You are right David , but didn't thought at all that there would be a misunderstaning for defining the plane by three points!I think it is commonly accepted. Haven't heard before for direction of plane from the third point.
Anyway, came up with something new.

In createPlane , you take into account only the 2nd & 3rd point for the cross product.You don't create vectors like p1-p2 & p1-p3.It looks to me as if you define the [0 0 0] , point for all planes. The normal in some cases looks wrong to me and didn't find any help.. If I use the vectors , results are fine.

plane=[1 1 1 ,2 2 1, 3 3 1]
planeNormal(plane)
ans = 0 0 0

I think that this should be a vector like [0 0 a].

12 Feb 2013

@panagiotis:
Apparently you did not really even try to get som help by yourself. Either "help planes3d", "help projPointOnPlane", or even "help geom3d" gives you the definition used in the library for representing planes.

Giving a low rating just because you did not want to read the doc is somewhat unfair...

By the way, many thanks to Sven for the support!

Regards,
David

11 Feb 2013

Sven,thank you for informing me. The truth is that I didn't got that deep in help..
As soon as I use the library again , I will reconsider the 1-star rating!
Thanks!

10 Feb 2013

Hi Panagiotis, the help for projPointOnPlane says "... PLANE is a [N*9] array (see createPlane for details)". The help for createPlane is very clear about the definition.

Anyway, I'm glad that your issue has now been identified. One further note is that your "other" direction vector was specified as [0 1 1], which isn't "normalised" (ie, it has a magnitude of more than 1). This won't affect projPointOnPlane but it can affect other functions such as planePosition if you intend on using them.

Hope this makes your code work again, and if so, perhaps you might reconsider the 1-star rating :)

09 Feb 2013

@ Sven
There was no such notice for this definition. I didn't know that the third point defines the plane's direction .

08 Feb 2013

@panagiotis:

Your definition of the plane does not make sense:

plane=[0 1 0 0 1 1 0 0 0];

Notice that elements 7:9 are all zero. Elements 7:9 give the plane's Y-axis direction vector. A vector of all zeros has no direction at all, therefore it is impossible to project a point onto this plane, because the plane doesn't exist.

08 Feb 2013

@Sven(strong defense for this library!)

point=[0 0 0];
plane=[0 1 0 0 1 1 0 0 0];
projPointOnPlane(point,plane)
ans = NaN NaN NaN

07 Feb 2013

@panagiotis:

>> projPointOnPlane([100 100 0],[0 0 0 1 0 0 0 1 0])

ans =

100 100 0

... seems fine to me. Please provide a reproducible error.

07 Feb 2013

The main problem I found is in projectionPointOnPlane in geom3d library. We tried to project a point on a plane on which the point already belongs to. The result that came up was NaN instead of the point's coordinates. That led to some problems with other functions like intersection..

Panagiotis

06 Feb 2013

@panagiotis: please describe the actual issue(s) you found. I would bet that if you found a reproducible error, David would very quickly address it. Just saying "there are errors with intersections" isn't actually very helpful, and doesn't let anybody improve the package above the 1-star you feel it deserves at the moment.

06 Feb 2013

Dear David,
I am using your library for a couple of months and I have found some errors especially on projecting points and intersection..
Thought you might find it helpful.

Panagiotis

28 Jan 2013

Hi Charles,
I have created a project page on sourceforge call "matgeom", that gather geom2d and geom3d. There are some forum facilities, so this should be easier to post data there I think.
http://matgeom.sourceforge.net/

Regards,
David

20 Jan 2013

Dear David,
I'm trying to use surfToMesh and then meshSurfaceArea function to calculate the approximate area covered by the dots with X and Y coordinates specified on X-Y plane. However, the area returns the value that does not make sense to me. I wonder if it's possible for me to attach the matrix here and get some help why it does not work in my code. The dots I have represents nearly a semi-circle and the result gives me the area close to a full circle of that diameter. Is there some tolerance setting on meshing? Thank you very much!

Best,
Charles

14 Dec 2012

HI Sir
Basically i have to draw that 3D rectangle and divinde its faces in
different infinitesimal areas, and divide that rectangle in small volums.
then i need to take the coordinates of Vertices of areas and volumes and
also coordinates of their central point
clc
clear all
close all
for x=0:1:2;
for y=0:1:2;
plot3([x,x],[0,2],[y,y]);
hold on
end
end
for x=0:1:2;
for y=0:1:2;
plot3([0,2],[x,x],[y,y]);
hold on
end
end
for x=0:1:2;
for y=0:1:2;
plot3([y,y],[x,x],[0,2]);
hold on
end
end
i need something like this but this is square and i dont know how to get
the required co ordinates
Best Regards

13 Dec 2012

Many thanks David!!!
Nam

27 Nov 2012

@Hoai-Nam,
I have submitted a new version with some new functions you should find useful:
* functions 'reversePlane' and 'reverseLine3d', that avoid explicitely permutting the directions vectors
* function intersectPlaneMesh, that returns the intersection between a plane and a 3D mesh. Not a full clipping function yet, but this should help!

regards,
David

21 Nov 2012

David, thanks a lot! Yuri

13 Nov 2012

@Yuri,
The function sphericalAngle assumes the input points are located on the surface of the unit sphere, that is not the case in your problem.
I think you should use the "angle3Points3d" function, that computes the angle between 3 points in space, using the second point as center of the angle.

anglePoints3d(p1, j1, l1)
ans =
1.5708

08 Nov 2012

Dear David,

Thanks for your very useful toolbox!

I've used some of your functions and I've found some things :

+ My problem :
I have a 3D point set. I create a minimum convex hull of this point set, using convhulln, so I have a list of facets of the convex hull.

I'd like to clip this convex hull by a plane. And this leads me to your function.

+ There 2 ways to do this with your toolbox :

1/ Use the function clipConvexPolyhedronHP. It works for my problem!
However if we want to have a side of convex hull (below or above to the plane) to clip, we must have a right plane input!!!

For example:
chX = convhulln(Pts); %Pts : 3D point set

% Select 3 points on the plane z=vClip
P=[0 0 vClip;
0 1 vClip;
1 0 vClip];
% Create plane z=vClip
plane=createPlane(P);

% This function createPlane gives me : plane=[0,0,0.7,0,1,0,1,0,0]
% Then the function clipConvexPolyhedronHP returns me a wrong polyhedron. So I permute the 2 direction vectors of the plane : plane=[0,0,0.7,1,0,0,0,1,0] and it returns me a polyhedron with the right side that I desire.

So do you have a tip to use the function createPlane to have a good result (so I dont have to permute the 2 direction vectors of the plane) ?

2/ Use the function polyhedronSlice. It doesn't work because it doesnt return only the intersection points of the plane and the polyhedron, but also some points that are wrong (see the image https://dl.dropbox.com/u/8702546/WEB/image_1.png).

However, if the function works, I can control the side of polyhedron that I want to clip by a simple command of Matlab!

So I feedback you this to correct the function polyhedronSlice!

Regards,
Nam

06 Nov 2012

David, very nice and useful package. Thanks.

I have a question about sphericalAngle function. I defined the following plane:
>> p1 = [1, 1, 1]; p2 = [100, 100, 1]; p3 = [1, 100, 1];
>> pl = createPlane(p1, p2, p3);

Then a point outside the plane and the projection point onto the plane:

>> l1 = [40,40,40];
>> j1 = projPointOnPlane(l1, pl);

I'd expect the angle between l1, j1 and any point on the plane to be pi/2. However, this is what I get:

>> alpha_rad = sphericalAngle(l1, j1, p3)

1.5745 (~ pi/2)

>> alpha_rad = sphericalAngle(l1, j1, p1)

0 + 2.1073e-08i (= 0)

>> alpha_rad = sphericalAngle(l1, j1, p2)

3.1416 - 0.0000i (= pi)

Can you, please, clarify the way the function works?

Thanks

25 Oct 2012

Very nice. thanks

16 Oct 2012

Great tools.

05 Jul 2012
29 Jun 2012
18 Jun 2012

Hi David,

Thank you. I miss understand the definition. I thought it was the origin and the end point. Thanks a lot.

Best,
Haochen

18 Jun 2012

Hi David,
I´ll try to use some of that functions. First of all i want to do only one slice in order to get the intersection points, only after that i´ll do it with the other parallel planes.
Thanks.

Regards,
Eduardo

18 Jun 2012

Hi Eduardo,
What you want to do seems possible, but to my knowledge there is no direct method.
There are some functions in the "meshes3d" sub-package that could help you, like intersectLineMesh3d or polyhedronSlice. You can also use intersectEdgePlane -> you can obtain the set of intersection points between a plane and all edges. If you want to represent the slice as 3D polygon, you will still need to link points in appropriate order.

@Haochen:
Beware of the definition of 3D line. In the toolbox 3D line is represented by [x0 y0 z0 dx dy dz]. In order to define a vertical line you should use [0.6 0 0 0 0 10]. In this case you will get the correct result.

Regards,
David

18 Jun 2012

Hi Eduardo,
What youwant to do seems possible, but to my knowledge there is no direct method.
There are some functions in the "meshes3d" sub-package that could help you, like intersectLineMesh3d or polyhedronSlice. You can also use intersectEdgePlane -> you can obtain the set of intersection points between a plane and all edges. If you want to represent the slice as 3D polygon, you will still need to link points in appropriate order.

Regards,
David

14 Jun 2012

Hi David,

Thanks a lot for this great tool. I am using the intersectLinePolygon3d function. Some of the results seem not make sense. For example:

pts3d = [-1 -1 5;1 -1 5;1 1 5];
line=[0.6 0 0 0.6 0 10];
[inter inside] = intersectLinePolygon3d(line, pts3d);

And I got:
nter =

0.9000 0 5.0000

inside =

1

Should we expect to get inter = 0.6 0 5?

Thanks so much,
Haochen

11 Jun 2012

Hi David
I´m trying to slice a triangular mesh. I´m not an expert in Matlab and i´m having some difficulties in implementing this. I have the edges, and i´m trying to get the intersection points with several parallel planes...
Can you give me a hand?
Thank´s.

Regards,
Eduardo

15 May 2012

Hi Amanda,
I do not know similar library for scilab. I suspect you need to re-code everything...
If you are looking for a free alternative, I can mention a port to octave of libraries geom3d+geom2d:
http://octave.sourceforge.net/geometry/index.html

regards,
David

11 May 2012

Hi, David
Having been using this package for years. Really love it. Thanks for your gr8 job. Now I'm researching using Scilab to replace Matlab for some application. Searched scilab but didn't find geom3d available there. Any suggestion?

11 May 2012
10 May 2012
03 Mar 2012

Hi Nir,
did you mean 3D polygon or 3D mesh ? It seems you speak about mesh, right ? In this case you case use function "intersectLineMesh" (contained in the updated submission). This should do the job.

@Benjamin: I have also added a function polygonArea3d in the update.

29 Feb 2012

Hey David,
It seems that the functions:
intersectRayPolygon3d
intersectLinepolygon3d
Don't work properly.
I have a rectangular 3D polygon (fairly simple, like an elongated cube) defined by both the vertices and the planes of it's sides.
A line or a ray, with a location in the middle of it in ANY direction should generate an intersection point. This does not work. Not for a line nor a ray.

Vertices:
0 0 0
0 0 2.7000
5.7000 0 0
5.7000 0 2.7000
5.7000 7.0000 0
5.7000 7.0000 2.7000
0 7.0000 0
0 7.0000 2.7000

Ray
Origin: 2.8508 3.5013 1.3500
Direction: -0.1 0.1 1

Help?

27 Feb 2012

Thanks mate. Beer flies out to you :)

24 Feb 2012

Hi Ben,

you can check the function "polyhedronSlice". It computes the 3D polygon that results from the intersection of a polyhedron with a plane. Example of use:
[nodes faces] = createCube;
plane = createPlane([.5 .5 .5], [2 3 4]);
poly = polyhedronSlice(nodes, faces, plane);
figure; hold on;
drawMesh(nodes, faces, 'facealpha', .5);
fillPolygon3d(poly, 'm');

There is no (not yet...) function for computing area of a 3D polygon. However it can be obtained by projecting on the intersecting plane:
poly2d = planePosition(poly, plane);
area = abs(polygonArea(poly2d))

Regards, David

16 Feb 2012

Hi David,

Thanks for your very nice work. I am searching for a routine that can find the (area of a) polygon that results from the intersection between a plane and a cube. Would this be possible with your library?

Regards, Ben

10 Feb 2012

Hi Patrik,

no, you haven't missed it, and it could be useful. I will add it in a future release.

regards

08 Feb 2012

distanceLine3d works on infinite lines a+t*b. Sometimes (collision detection) the distance between line segments AB and CD is required. A distanceSegment3d would be useful.

The same is true for points (distancePointSegment ).

Or did I just miss it?

07 Feb 2012

Nicely written, good comments - thank you!

13 Dec 2011
07 Aug 2011
20 Jul 2011

@Qais,
you should install both geom2d and geom3d, typically in the same directory. Then you have to add directories to the path, using te 'addpath' function, or the 'File->Set Path' menu). You need to add at least the directories 'geom2d', 'geom3d', 'polygons2d', 'meshes3d', and eventually 'polynomialCurves2d'.

Some demos are provided with each archive, you can run them directly, and have an idea on the syntax.

I will also try to add some info on the matGeom web page (that gathers geom2d and geom3d), at http://matgeom.sourceforge.net .

Hope this helps

19 Jul 2011

Dear David,
I am just start using Matlab in my research for geometrical computation. I appreciate if you would like to demonstarate how to use this library(3d or 2d) since each function I used give me syntax error about other functions as undefined. I am a biginner in Matlab and may be my question is dump question. I am very thankful.

22 May 2011

@Khaled and Qais,
What I had in mind was to use the following procedure :
* compute intersection of line and polygon plane
* project polyingon vertices onto the plane (ie, compute their 2D coords)
* project intersection point onto the plane
* check if 2D intersection point is within the 2D polygon.
The following piece of code should do the job (assuming poly3d is N-by-3 and line is 1-by-6):
plane = createPlane(poly3d(1:3, :));
inter = intersectLinePlane(line, plane);
poly2d = projPointOnPlane(poly3d, plane);
pInt2d = projPointOnPlane(inter, plane);
inside = xor(isPointInPolygon(pInt2d, poly2d), polygonArea(poly2d) < 0);
inter = inter(inside, :);

Both geom2d and geom3d are required. I will add functions 'intersectLinePolygon3d' and 'intersecRayPolygon3d' in the next release.

regards

21 May 2011

Dear David:
I read your comment for Khaled question. It is not clear to me about what you said"The best is to use 3D plane, and eventually to project all points on the plane, then to use function for 2D polygons." Which points we should project on 3D plane and from my understanding line intersect a polygon in one point.

16 Feb 2011

Hi Khaled,
to create a 3D polygon, you simply need to concatenate their coordinates into a N-by-3 array, e.g. poly=cat(1,p1,p2,p3);
There are no fucntions for intersections of 3D line with 3D polygon. The best is to use 3D plane, and eventually to project all points on the plane, then to use function for 2D polygons.

15 Feb 2011

Dear eng. David,

Thanks, this powerful toolbox is very helpful.

I tried to create a 3D polygon from four or three 3D points, and couldn't. So instead I tried to create a plane, but when finding an intersection with a 3D line the answer will not be accurate as the plane was polygon.

Is there a possible way to create a 3D polygon from four or three points? and
Is there a possible way to find a intersection between a 3D line and 3D polygon?

19 Jan 2011
01 Dec 2010

Incredibly helpful toolbox. Mostly intuitive function calls, and thorough documentation to make integration easy.

06 May 2010

11 Dec 2009

Excellent package for spatial manipulation. Extensive toolbox, that handles input intuitively. The only suggestion I have is, for completeness, to document some of the methods of calling functions for the more obscure functions. Eg., localToGlobal3d has one documented method of calling, but under the hood it parses input in many different ways. I find myself typing "edit" instead of "help" just to make sure I'm using things efficiently.

07 Dec 2009

The format for cylinder is as follow: [xv yv zy R xc yc zc], with:
[xv yv zv] the direction vector of the cylinder,
R the radius of the cylinder
[xc yc zc] the origin of the cylinder.
the L parameter, which is given in help, is not used.
The cylinder is considered infinite, please use "linePosition3d" if you need finite cylinder.
Please note that this format is not consistent with the function "drawCylinder", for example. Therefore the function "intersectLineCylinder" is likely to change in a future release.
DL

03 Dec 2009

Hi,

I tried the "intersectLineCylinder" what are the definitions of: xa, ya, za, and L for cylinder??..Please anybody

01 Sep 2009

Hi,
I have uploaded a new version, that fixes reported bugs, and have added some demos. Demos are available as published m-files, and can be accessed through the file presentation above. They demonstrates some usage possibilities.

Most drawing functions follow the 'plot' syntax. Data are given first, then optional couples of parameter name and value. If not implemented, try using "h=drawMyShape(...)", then set up options using "set(h, 'color', 'k')" for example.

For bug reports and suggestions, the best is to sent me directly and e-mail (can be found in my author page, replace "DOT" by ".").

DL

03 Aug 2009

This package aims at solving visualization problems, I often have. However, I have not been able to I'm trying to use this package, but experiencing a number of problems:

1. How are the colors controlled of the objects drawn?
2. I want to draw cylindrical representation of arrows, since quiver3 together with drawPlane does not work well, possibly due to lack of control of drawing order. Instead I want to draw thick arrows, and I'm using drawCylinder.m. However, in line 89 is used the non-existing function local2Global.m. It appears to be replaceable by localToGlobal3d, if localToGlobal3d line 29 is replaced with "center = varargin{1};".

For suggestions to corrections, etc. what is the best procedure?

Thanks, Jon

17 Jul 2009

This library and its companion, geom2d, are shining jewels - indispensable for doing non-trivial calculations on objects in 2d and 3d space.

By the way, leave all the files in the geom3d directory and add the directory to your path. Then you can type "help geom3d" or "doc geom3d" and get properly linked help text in the command window or the help window. The Contents.m file is the proper "MATLAB way" of providing documentation.

19 Jun 2009

it is too bad that this (apparently) full-fledged software package does not come with an appropriate and modern help/intro/example module called a published m-file...

as of now, it is somewhat tedious for a naive user to have to wade through the help sections of the individual help files (or the densly written contents.m) - and it will (most likely) not give your package as much attention as it probably deserves...

us

26 Aug 2009

some bug fixes, demo files as published m-files.

31 Aug 2009

29 Jul 2010

fixed bugs in rotations and in drawing of some shapes, added rotation by Euler angles, various update in doc and in code

14 Jan 2011

Add new functions for meshes and polyhedra, and for 3D transforms (rotations, basis transform). See file changelog.txt

30 Jun 2011

use degrees for drawing shapes, split lib into packages 'geom3d' and meshes3d

13 Oct 2011

various code cleanup and speed improvements, mainly contributed by Sven Holcombe (many thanks!)

02 Mar 2012

bug fixes, new functions for spherical polygons, for reading meshes (off foramt), for point-edge distance, and for computing surface area of 3D polygons, meshes, or ellipsoids.

05 Apr 2012

fix bugs in demos

27 Nov 2012

several bug fixes, new functions (fitLine3d, parallelPlane, reversePlane, intersectPlaneMesh, meshCentroid...), and fonctions for creating meshes from patches or geometric primitives.