Search Unity

[RELEASED] Math Library for Unity

Discussion in 'Assets and Asset Store' started by devast3d, Feb 16, 2014.

  1. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Hi all,

    After several month of work the library is finally on the asset store!

    Asset Store Link

    Follow me on Twitter.

    $UGTImage_Forum.png

    In short, it contains many helpful geometric and algebraic methods which many game developers will find useful. Brief contents below:


    Primitives in 2D/3D
    line, ray, segment, plane, aab, box, rectangle, circle, sphere, triangle, polygon

    Intersection
    e.g. ray-triangle

    Distance
    e.g. point to line

    Projection
    e.g. point to plane

    Bounding objects
    e.g. bounding boxes, spheres

    Point containment
    e.g. is point inside the triangle

    Side testing
    e.g. is box to the right side of the line

    Convex hull
    Inputs 2d or 3d point set and produces convex hulls

    Approximation
    e.g. build plane from the set of points

    Numerical methods
    e.g. linear system solver, integrals, roots..

    PRNG
    Pseudo random number generator with lots of useful sampling methods; Poisson disk sampling; shuffle bag

    Catmull-Rom splines
    with editor extension

    Utility functions
    for Vector2/3, Matrix4x4 and some generic math methods


    Link to the DOCUMENTATION file which describes everything in details.

    Small demo created with the library.










    Post your comments and feedback below!
     
    Last edited: Jun 7, 2014
  2. gonzorob

    gonzorob

    Joined:
    Dec 1, 2011
    Posts:
    96
    Looks great! Is there a reason why the source is not included? Also, do you have any plans to implement a convex hull algorithm? That would be an instant sell for me :)
     
  3. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Hi gonzorob, thanks for the interest! Convex hull construction is on my nearest TODO list, it will be added in the next version. Except for probably primitive objects, sources are useless without background theory and books :)
     
  4. gonzorob

    gonzorob

    Joined:
    Dec 1, 2011
    Posts:
    96
    awesome :) thanks for the quick reply!
     
  5. thienhaflash

    thienhaflash

    Joined:
    Jun 16, 2012
    Posts:
    513
    This is cool if more algorithm added, convex hull should be a must, there are a lot more algorithms out there to integrate, also source code, man
     
  6. MarcoMeter

    MarcoMeter

    Joined:
    Jun 14, 2013
    Posts:
    69
    I'm currently working on a project for making linear algebra more vivid to students by virtual reality (oculus rift).

    I'd like the user to create and modify shapes such as spheres, planes, rays,.. on runtime. All sort of intersections, points of interest, projections are supposed to be returned on the fly.

    I think I could write such demanding scripts on my own. In case of saving time, do you recommend your library for my project?

    Could you provide a demo? Trial?
    I really would like to see if your library fits my requirements before purchasing it.
     
  7. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Hi MarcoMeter,

    Good idea! I will create the demo showing basic concepts in action (at least intersection/projection/distance).

    I've spent 3 month of coding at nights (including writing documentation) to create this. And this considering I've used all external sources I could get (including C++ sources). With the books I could understand almost everything, but it's just damn a lot! I'm already using it myself on the main job, it helped to eradicate some physics raycasts, add segment intersection and line distance queries in the CAD project I'm working on. So think for yourself, if you need couple of objects and several intersections - you can try to do it, it's fun, on the other hand the library already has many common methods (for example there are 28 intersection tests in 2D and 35 tests in 3D - I will add more in the future) and test prefabs showing them in action ready for use.

    I will think about how to create trial version (it's little bit hard because it's just dll), maybe some free small subset from most of the sections so users can try how it feels before buying. By the way, if you are interested in what's exactly in the library - refer to the documentation (link in the first post) it describes pretty much everything the library has. And would you be interested in some videos showing how to use the library or the documentation is enough?

    p.s. 2d/3d convex hull stuff is undergoing testing and will soon be uploaded.
     
  8. MarcoMeter

    MarcoMeter

    Joined:
    Jun 14, 2013
    Posts:
    69
    Thanks for your fast reply.

    A video would be adorable.
    Any demonstration would be a pleasure.
     
  9. MarcoMeter

    MarcoMeter

    Joined:
    Jun 14, 2013
    Posts:
    69
    Does your library use collisions/colliders for calculating intersections points for example between two lines?
    Or did you implement an algorithm to solve linear equation systems?
     
  10. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    The library is not using anything from Physx. Actually solving linear system is not the best way here. It's not reusable nor it can say much about the intersection. Methods discover behavior of an intersection using dot product as main instrument (this also applicable to rays and segments).
     
  11. qewo

    qewo

    Joined:
    May 16, 2013
    Posts:
    3
    In post: http://forum.unity3d.com/threads/209060-Do-community-need-math-library You mentioned that making the math library deterministic would cause it to run slowly, but if you could make an alternate version that runs deterministic calculations i would definitely buy it. As with the previous post many people where asking about deterministic calculations (primarily Float operations), i think this maybe as your the only one offering something close to this. If you did manage to make your system deterministic any project attempting any form of lockstep networking would be sure to purchase the math library.
    I would be really happy if you would consider adding deterministic calculations to the math libary so for my lockstep networking project i would not have to learn crazily advanced mathematics :D
     
    nbg_yalta likes this.
  12. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Hi, qewo. I'm gradually researching this topic. So far I found that there are 3 ways to achieve determinism:

    1a. Use integers - floats can be converted to ints and operations will be applied to integer numbers then. Having sufficiently large int (e.g. 64 bits) some operations could be done, but generally this approach will lead to serious precision loss.

    1b. Use rational math - implement BigInteger (like in F#) and keep numerator and denominator as BigInts. This will allow to implement basic math: add, subs, mul, div and will also be exact (e.g. it's possible to implement exact predicates using this approach). But I haven't found anything about implementing square roots, exponents and trigonometry and without square root half of the algorithms could not be implemented.

    2. Don't invent anything. Use same compiler settings for the single platform. Despite this is somewhat limited, seems that people are using this to achieve determinism on one platform, e.g. Windows. The problem here is that it works in C++ and in C# it's impossible to achieve (at least this is what I found from googling), and most information is about CLR anyway and not about Mono runtime. The plus here is that it's still fast hardware floats.

    3. Implement custom floating number. I.e. go learn IEEE754 floating point format and implement it solely in software (this is sometimes called SoftFloat). I found couple of unfinished hobby projects and one for C++, but really nothing for C#. Also there's the famous article about floating point format, which is hundred pages long and simply blows your mind since first pages... Anyway, this is probably the most promising approach, but it requires REALLY serious time investment, as implementing full-blown float is not for the faint of heart. This approach will be also slow as 1a and 1b, I don't really know if this is applicable to run-time applications such as games..

    All in all, this task has nothing in common with math, it's hardcore low-level programming! By the way if you want to know which article is mention in item 3, here it is What Every Computer Scientist Should Know About Floating-Point Arithmetic. Just look at it and feel the power of floats! Also there is smart guy Bruce Dawson blogging about floats, you may look at his excellent mind blowing articles. One big problem is that I've found many articles describing that determinism is not possible under various conditions and none which describes how to achieve it (not counting same compiler settings which is not what we aim for). You may want to read this article http://randomascii.wordpress.com/2013/07/16/floating-point-determinism/ as well. After skimming through it, I really started to doubt that cross-platform determinism is theoretically possible :)
     
  13. qewo

    qewo

    Joined:
    May 16, 2013
    Posts:
    3
    Wow thanks for pointing me in the right direction, looks like i've got a lot of work to do :D
     
  14. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Heh, you're welcome! I'll also continue researching this vast topic.


    By the way, package has been updated:

    Version 1.1.0
    - Added ConvexHull class which allows to create hulls for 2D and 3D point sets (with test prefabs). See documentation for the description.
    - Added implicit conversions between some library type and Unity types (Ray and Ray3, Plane and Plane3, Bounds and AAB3)
    - Added Rectangle3 constructors from 4 points (with test prefab)
    - Added Mathfex.RandomBool()
    - Fixed Polygon3 intersection methods names
    - Fixed various typos in the documentation and code comments
    - Changed MathfEx, Vector2Ex, Vector3Ex, Matrix4x4Ex to Mathfex, Vector2ex, Vector3ex, Matrix4x4ex accordingly (more convenient to type). Use "Search and Replace" to fix the code.
    - Updated documentation
     
    Last edited: Feb 25, 2014
  15. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    I've create small demo using Math Library for Unity library.
    Link: Chambers Demo

    Demo consists of main menu and several small scenes, demonstrating some methods from the library coupled with some fancy graphics and programmer design. Below is the description of what was used. Notice that physics was not used in the demo.

    - Menu
    Ray-Cube, Ray-Rectangle intersection used for the 3D buttons. Mathfex.EvalOverlappedStep used in screen fade method and letters fade in from above of the screen, screen fade also uses collection shuffling to achieve nice random screen filling. Camera uses CatmullRom splines to fly to the cubes.

    - Intersection Test
    Shows 3D Ray-Triangle intersection routine. You can point over bent quad to see intersection parameters.

    - Distance Test
    Shows 2D Point-Box distance calculation. If you point the mouse near to the boxes, yellow segments will appear, showing closest points from the cursor to the boxes. You can change distance which is used in the calculation in the appropriate field. Click "reset" to respawn boxes.

    - Axis-aligned box
    Shows construction of aab's from points and aab's from other aab's. Click "reset" to respawn points. Click on the buttons "<", ">" to rotate the camera.

    - Side Test
    Shows Plane-Box, Plane-Sphere side queries.

    - Linear system solver
    Shows GUI panel which allows to solve systems of linear equations. Set system size, fill the number and press "Solve". The result will appear in the controls below "Solve" button.

    Here's screenshot of the main menu:
    $chambers_menu.png
     
  16. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Package has been updated.

    Version 1.2.0
    - Added pseudo random number generator class (Xorshift128 algorithm) with large amount of useful methods (test prefabs included). Users can create any number of streams of random numbers. The class is released in source code.
    - Added weighted sampler (samples index using an array of weights), triangle set sample (can sample meshes), poisson disk sampler (generates point set in 2D rectangular domain where distance between samples is not less than specified threshold). Also added 3D point set distance filtering which allows to filter existing 3D point sets so that distance between samples is not less than specified threshold. See documentation for more information and test prefabs. The classes are released in source code.
    - Added ShuffleBag class for generating endless random sequences of weighted values. See the documentation for more details. The class is released in source code.
    - Added Util static class. At the moment it contains only extension Shuffle() methods for arrays and IList collections. The method permutes item order in a collection. The class is released in source code.
    - Added Vector3ex.Barycentric(). It calculates barycentric coordinates of a point given triangle vertices.
    - Added PositiveInfinity and NegativeInfinity vectors to Vector2ex and Vector3ex.
    - Added SetEndpoints(), SetCenterDirectionExtent() methods to Segment2 and Segment3.
    - Added overloads which accept ref parameters to all Include and Contains methods of the primitive objects. It is advisable to use overloads with ref parameters.
    - Added overloads which accept arrays to AAB2/AAB3 CreateFromPoints() methods.
    - Added overloads which fill input arrays with vertices to Box2/Box3/Rectangle3 CalcVertices() methods.
    - Added CalcVertices() methods to AAB2/AAB3 which are similar to corresponding Box2/Box3 methods.
    - Documentation now includes description of the default constructor for each of the primitive objects. It is still preferable to use constructors with parameters.
    - Removed previously added Mathfex.RandomBool(). See new Rand class for the replacement.
    - Fixed various typos in the documentation and code comments
    - Fixed documentation for aab/box/circle/sphere static constructors (in some places functions were incorrectly describing parameter as array, where it should be IList).
    - Moved all test scripts to the separate namespace.
    - Polygon2 and Polygon3 default constructors made private so users won't accidentaly use them.
    - Slightly changed behavior of aab/box/circle/sphere CreateFromPoints methods when input set is empty. Now the methods won't throw an exception, but return empty instance.
    - Test scripts now use AAB2/AAB3/Box2/Box3/Rectangle3 CalcVertices() methods to draw primitives.

    Some screenshots of the new test prefabs
    [table]
    [tr]
    [td][/td]
    [td][/td]
    [td][/td]
    [/tr]
    [tr]
    [td][/td]
    [td][/td]
    [td][/td]
    [/tr]
    [tr]
    [td][/td]
    [td][/td]
    [td][/td]
    [/tr]
    [tr]
    [td][/td]
    [td][/td]
    [td][/td]
    [/tr]
    [/table]
     
    Last edited: Mar 12, 2014
  17. cl9-2

    cl9-2

    Joined:
    May 31, 2013
    Posts:
    417
    Hello,

    Can your library calculate the curvature along spline paths?

    Do you have any benchmarks comparing the performance and memory usage of Unity3d's Math operations with your Math Library? (Particularly in the areas of collision testing and vector and matrix calculations)
     
  18. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Hi,

    Catmull-Rom splines are C[SUP]1[/SUP] continuous, while curvature requires calculation of the second derivative (C[SUP]2[/SUP] continuity), thus it's meaningless for this kind of splines. For example, natural cubic splines do have C[SUP]2[/SUP] continuity, but they don't have locality (i.e. they require recalculation of the whole spline if any vertex is changed => slower splines). If you're interested in natural cubic splines, I can add them to the library.

    As for the math operations, what exactly do you mean? There are a lot of operations right now in the library. Particularly for vector/matrix operations (well, mostly for matrix operations, because there are several extension methods for vectors, mostly for convenience - you can look at all available operations in the documentation) they beat Unity counterpart in terms of performance. And there are many methods in the lib which aren't presented in Unity, so, well, sometimes there's nothing to compare with! (e.g. I've added a lot of methods to construct transformation matrices, but in Unity we only have Matrix4x4.TRS which is far from being performance wise..). One of the test prefabs does the comparison for matrix operations. If you need the exact numbers I can post the table.

    Yet again with regarding collision it's hard to compare directly. Physx has been designed for well... physics :) While I was working toward non-physics stuff. Let's look at the different cases.

    First one, you want to check whether the ray intersects with your fancy rotating and scaling buttons. In Unity you can do that by putting colliders on the object. You should be aware that static colliders incur performance cost, thus you should also add rigidbody. Then rigidbody will complain if tensor could not be calculated (object is nearly planar). Also scaling mesh colliders brings physx to its knees, etc etc... such kind of problems is PITA to solve with built-in physics (I've faced these problems myself often). Here my library will shine, as you only need to create primitives (most of them are just structs => fast to create/destroy) and check the intersection, no weird physx calls which kills your performance.

    But if you for example need to raycast regular huge gameplay scene, then here Physx will do better because (I suppose) it has some sort of space tree and will only test relevant subspace. And Physx is designed to test moving objects (e.g. continuous collision detection), while the library is designed around static objects. Dynamic collisions detection requires separate methods (e.g. GJK algorithms and so forth) and I don't think anyone will use external physics system anyway...
     
  19. The-Spaniard

    The-Spaniard

    Joined:
    Jan 7, 2012
    Posts:
    149
    Hi - Does this library have methods for finding the intersections of bezier curves, and of rays with bezier surfaces? If so, it could be exceedingly useful for me...
     
  20. movra

    movra

    Joined:
    Feb 16, 2013
    Posts:
    566
    Wow, full-screen that demo is flickering like crazy in the test chambers! Bettter fix it before we have another case of Dennō Senshi Porygon.
     
  21. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Right now it ain't have nor bezier curves neither surfaces. I will research this topic and their intersection as well.

    What's your spec? I got no flickering in full-screen. Maybe you're talking about fade-in/fade-out effect? :D
     
  22. The-Spaniard

    The-Spaniard

    Joined:
    Jan 7, 2012
    Posts:
    149
    From what I understand, there are no analytical ways of finding bezier curve or surface intersections, as the problem boils down to solving simultaneous polynomials of order 3 and above. Most solutions are arithmetic algorithms, like bezier clipping. I was just wondering if you had written such an algorithm in your library, to save me from having to do it myself!
     
  23. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    I've found the pdf document describing clipping algo already (discussions of stackoverflow shows that this is the best algo for bezier intersection). But first I need to implement bezier curves in the similar way how catmull-rom splines are implement (that is easy to use with nice editor extension), it takes quite a while to do that!
     
  24. The-Spaniard

    The-Spaniard

    Joined:
    Jan 7, 2012
    Posts:
    149
    It does! That's what I'm working on at the moment, and it does take some time...
     
  25. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Version 1.3.0 has arrived!

    - Added new type of splines - cubic splines (natural and closed). These splines have continuous second derivative. Natural cubic splines have zero second derivative at the ends, closed cubic splines have similar first and second derivative of the first and last spline points.
    - Catmull-Rom and cubic splines now derive from the base spline class.
    - Added methods which calculate Frenet frame, curvature and torsion to the base spline class.
    - Added test prefab Test_CubicSpline3 which shows curvature calculation of cubic spline.

    Screenshot of the new test prefab with curvature calculation.
    $1.3.0_SS1.png
     
    Last edited: Apr 9, 2014
  26. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Library Update. Version 1.3.1

    - Added Vector2/3ex.SetLength() and GrowLength() non-extension methods. Also added Vector3ex.AngleDeg(), AngleRad(), SignedAngleDeg(), SignedAngleRad() extension methods for getting angle between vectors.
    - Added Vector2/3ex.Length() and LengthSqr() extension methods for those who don't like magnitude and sqrMagnitude names.
    - Created Quaternionex class. Added extension method DeltaTo() which calculates difference between quaternions (delta rotation which when applied to the first quaternion will lead to the second quaternion). Also added ToStringEx() similar to Vector*ex methods (does not round the values).
    - Added Matrix4x4ex.CreateRotation() method. It allows to create rotation matrix around given point (no translation or scaling, for that use CreateSRT or CreateRT).
    - Added implicit conversion between AAB2 and UnityEngine.Rect. See AAB2 docs.
    - Added Plane3.AngleBetweenPlaneNormalAndLine() and Plane3.AngleBetweenPlaneAndLine() overloads which accept Vector3 rather than Line3.
    - Added several interpolation methods to the Mathfex: Lerp, LerpUnclamped, SinInterp, CosInterp, WobbleInterp, CurveInterp, FuncInterp. Also added Test_Interpolation test prefab showing these methods in action. See docs for more info.
    - Added Mathfex.Near() and Mathfex.NearZero(). Handy methods for comparing floats with each other and with zero using epsilon-check.
    - Fixed Matrix4x4ex.CreateSRT, Matrix4x4ex.CreateRT overloads which accepted rotationOrigin parameter.
    - Changed Mathfex.InterpolateBySigmoid() method name to Mathfex.SigmoidInterp().
     
  27. sysameca

    sysameca

    Joined:
    Mar 2, 2013
    Posts:
    99
    Hello there. I am no math guru, but i want to ask if this library can help me achieve a certain physics effect for my game.Basically what i am trying to achieve is: Make a circle collider slide on collision with any other collider (even mesh).I am basically doing it with vector projection right now and it works fine until the point i need collide with something else than a box collider.So i was wondering can the library can be in any help of me in this situation?
     
  28. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Why don't you use Unity built-in 2D physics stuff? E.g. https://docs.unity3d.com/Documentation/ScriptReference/Collider2D.html
    As for library it is mostly aimed towards geometry calculations rather than physics. You can look in the docs to check exactly what it contains.
     
  29. gonzorob

    gonzorob

    Joined:
    Dec 1, 2011
    Posts:
    96
    Hi,

    The convex hull algorithm you kindly implemented has been working really well so far (about 10x quicker than mine!) however it looks like we might be needing a concave hull algorithm also. Are you thinking about adding this at any point?
     
  30. bigSky

    bigSky

    Joined:
    Jan 31, 2011
    Posts:
    114
    The link to the documentation often brings up a :
    "Disabled link
    Access to this link has been disabled. Please ask the owner of the shared link to send a new link to access the file or the folder."

    and also, the demo - "invalid data file" in the unity web player.
     
  31. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Yeah, Dropbox recently disabled files with links, I already moved the file to google docs, should be working now, check the new link in the first post (asset store link should be updated in couple of days).

    I'll look what's wrong with the demo, thanks for the report!

    EDIT:

    Reuploaded demo to the hosting, for some reason it was corrupted. Should also be working now, please check.
     
    Last edited: May 19, 2014
  32. sysameca

    sysameca

    Joined:
    Mar 2, 2013
    Posts:
    99
    Hello again.I am sorry that my previous post was unclear and in a rush, but this time i want to know if it is possible to do such a thing with the math library.
    Ill explain quick and clear my problem which i can't achieve with Unity as far as I informed myself.
    In 2D i am casting a ray from the starting point A to the clicked position B which intersects a polygon collider(the green space).Then i am projecting the vector B-A on the pollygon collider's up Vector which looks something like this:

    $Projection2.jpg

    The thing I can't achieve with Unity is hitting the pollygon collider point from inside-out.It just does not detect a hit.So simple and plain I can ask: Can I achieve with this library a hit detection over any 2D collider from inside out?If I can achieve this then I can surely buy the library.
     
    Last edited: May 20, 2014
  33. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    @sysameca

    Hi,

    I see your point now. Let me explain. Following there are images of what you may find useful in your task. Images show intersection of a ray with an object.

    $AABIntr.png
    Image show Ray2-AAB2 intersection (left - ray is outside, right - ray is inside)


    $BoxIntr.png
    Image show Ray2-Box2 intersection (left - ray is outside, right - ray is inside)

    $CircleIntr.png
    Image show Ray2-Circle2 intersection (left - ray is outside, right - ray is inside)

    So for ray and axis-aligned box, general box and circle the library can find intersection in any configuration.

    Next, you need intersection with a generic polygon. The library had intersection routines for only convex polygons only so far. I've written intersection methods for generic (non-convex polygon) like in 20 minutes today. The idea is very simple: just check intersection of the ray with every edge of the polygon and return closest intersection point (if any). The image shows this concept:

    $PolyIntr.png

    Intersection method here do not care whether the ray is inside or outside (it's just Ray2-Segment2 intersection in a loop) . I've added the overloads which accepts segment array, not the polygon primitive. So this way you can even construct non-closed polyline and find intersection with it.

    One question though, what's the size of your polygons? As the ray will be checked against the every edge of the polygon/polyline, this may be slow when number of edges is huge. In this case it's better to split the polygon/polyline into several parts, build the AAB for each part and do fast Ray2-AAB2 check before Ray2-Polygon2 test. This will work for static geometry (if the geometry is changed AABs should also be recalculated).

    If this is what you need, I will submit library update to the asset store.
     
  34. sysameca

    sysameca

    Joined:
    Mar 2, 2013
    Posts:
    99
    Wow this is great.The geometry is static.The size of the polygon collider is not too big at all.It's a super simple and easy level setup with few colliders,but the fact that Unity does not give me that kind of control, gives me the pleasure to buy the library.But i am super glad that i can do this kind of checks.I am buying it so i can finish the game.Thanks!
     
  35. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    If you will buy the library before the update, PM me, I'll give you the file which does the intersection with the polygon (update usually takes ~1 week).
     
  36. YoYoooooooo

    YoYoooooooo

    Joined:
    Dec 10, 2012
    Posts:
    3
    Hi,

    This package looks damn good. Just 2 questions :
    - is any kind of precomputing required (for raycasting against meshes essentially)?
    - how does your raycasting compares to unity's Physics.RayCast() in terms of performance on large scenes (hundreds to thousands of objects, millions of poly globally)?

    Thanks
     
  37. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Hello,

    The library contains basic geometric algorithms required in many cases (e.g. ray-triangle intersect, point box distance etc). It doesn't go beyond that. So regarding to your case when you have a huge scene you will definitely need some preprocessing (BSP or something). In this case Physx I think will be faster as it has subdivision of the whole scene (try to move object with collider on it but without Rigidbody - you will notice a hiccup, during that lag Physx makes subdivision AFAIK).

    So, in short, if you have a subdivision of space (or willing to make one) the library will give you most of the actual geometric operations, if you want subdivision to be done for you, better stick to Physx.

    p.s. I was thinking many times about such case (huge scenes) and come to the conclusion that solving this problem requires actually writing physics library rather than geometric library and I don't think that people will use some 3d party physics instead of the built-in one.
     
  38. YoYoooooooo

    YoYoooooooo

    Joined:
    Dec 10, 2012
    Posts:
    3
    Thanks for your answer. I am actually trying to find some kind of magic that would avoid overhead due to bsp/octree/whatever space partionning update when an object is moved.
    Bounding volumes seem to be my only option, but not fast enough I'm afraid.
    Right now I can not think of any viable solution. :-(
     
    Last edited: May 22, 2014
  39. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    I suppose that one of the fastest ways of space partitioning is hierarchy of AABs (spheres might be faster but far less accurate). Generally writing efficient scene graph is totally not trivial task :)
     
  40. YoYoooooooo

    YoYoooooooo

    Joined:
    Dec 10, 2012
    Posts:
    3
    Ok, I will investigate AABB hierarchies fast update. Anyway, your lib is still providing part of the solution when at the polygon level.
    Thanks for the hints.
     
  41. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Library update 1.3.2 due to sysameca requests

    Version 1.3.2
    - Added ToSegmentArray() method to Polygon2/Polygon3 objects. It will convert a polygon to Segment2[] or Segment3[].
    - Added Intersection.TestRay2Polygon2(), Intersection.FindRay2Polygon2() methods. They allow to find intersection between a generic polygon and a ray. Each method has two overloads. One that accepts Polygon2 and other accepts Segment2[] parameter. Overloads which accept array work faster and also allow to pass non-closed polylines. Read the docs for more info.
    - Added Triangle2/3.CalcArea() static method for calculating area without constructing the triangle
    - Added Triangle2/3.CalcAnglesDeg/Rad() member and static methods for calculating triangle angles in degrees and radians.
    - Added Triangle2/3.EvalBarycentric() overload which accepts all 3 coordinates instead of calculating third one.
    - Added Vector2ex.AngleDeg/Rad() extension methods similar to Vector3ex methods (calcs angle between vectors).
    - Added more overloads for Vector2ex.Dot/DotPerp() and Vector3ex.Dot/Cross/UnitCross() (extension and static overloads accepting refs).
    - Moved Vector3ex.Barycentric() methods to Triangle3 object (also added member overloads). They are now called CalcBarycentricCoords(). Similar methods are added to Triangle2.
     
  42. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    865
    Hi my friend!

    Excellent library, I just bought it two days ago and I love it. I have a question about how to check for line overlaps.
    I was thinking to check every segment against every other segment in the line but I don't get good results. I always get overlaps!

    Here is the code of what I have right now:

    Code (CSharp):
    1. void OverlapCheck()
    2. {
    3.    bool overlapped = false;
    4.    for (int i = 0; i < Line.points2.Length - 1; i++)
    5.    {
    6.       var segment = new Segment2(Line.points2[i], Line.points2[i + 1]);
    7.  
    8.        for (int j = 0; j < Line.points2.Length - 1; j++)
    9.        {
    10.            if (j == i)
    11.            continue;
    12.  
    13.            var s = new Segment2(Line.points2[j], Line.points2[j + 1]);
    14.            IntersectionTypes intersectionType;
    15.  
    16.            overlapped = Intersection.TestSegment2Segment2(ref segment, ref s, out intersectionType);
    17.            if (overlapped)
    18.            {
    19.                Debug.Log("Overlapped: [" + i + "]" + "[" + j + "]" + overlaped);
    20.                GoBack();
    21.            }
    22.       }
    23.  }
    24.  }
     
  43. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    865
    Can you help me please, i don't know what i am doing wrong
     
  44. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Hi, sorry for the late reply (next time send me a PM for a faster response).

    Most likely you get intersection because two adjacent line segments intersect by their endpoints. And I suppose you want to check for self-intersection. Instead of Test method you should use FindSegment2Segment2 which also returns information about the intersection (parameter(s) and actual point(s)). They can be used to determine if you hit the endpoint!

    Let me know if this helps.
     
  45. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    865
    Thanks, that was it. This is how I solved it, let me know if there is a better way of doing this!

    Code (CSharp):
    1. for (int i = 0; i < segments.Count - 1; i++)
    2.         {
    3.             var s1 = segments[i];
    4.  
    5.             for (int j = 0; j < line.points2.Length - 1; j++)
    6.             {
    7.                 Segment2Segment2Intr info;
    8.                 var s2 = new Segment2(line.points2[j], line.points2[j + 1]);
    9.  
    10.                 bool found = Intersection.FindSegment2Segment2(ref s1, ref s2, out info);
    11.  
    12.                 if (found && info.IntersectionType == IntersectionTypes.Point)
    13.                 {
    14.                     if (!(info.Parameter0 <= 0f) && !(info.Parameter0 >= 1f))
    15.                     {
    16.                         Debug.Log(i.ToString() + "/" + j.ToString() + " " + info.Point0.ToString());
    17.                     }
    18.                 }
    19.             }
    20.         }
    This is how I understood it… info.Parameter0 and info.Parameter1 evaluate as a ratio where intersection occurs, if its 0 or 1 then intersection occurs either on start or end point of the segment. I had to check for <= 0 and >= 1 because it doesn't work the other way, sometimes I get small negative number.

    let me know if this is the correct way of doing things! Thanks!
     
  46. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    You're right, Parameter is 0 or 1 when intersection is on endpoint. You can slightly simplify the check

    1. if (info.Parameter0 > 0.0f && info.Parameter0 < 1.0f)
    2. {
    3. ...
    4. }
    Also instead of 0 and 1 you may want to specify eps and 1f-eps (where eps is small position value, e.g. 1e-5f, you can use Mathfex.ZeroTolerance) to avoid precision issues.
     
  47. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    865
    Hi! Thanks for suggestions! Mathfex.ZeroTolerance solve precision issues!
    Great package!
     
  48. SoftwareGeezers

    SoftwareGeezers

    Joined:
    Jun 22, 2013
    Posts:
    902
    Demo doesn't work for me. "Invalid data file"
     
  49. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Webhosting constantly wipes the build for unknown to me reason. I've uploaded this web build to the dropbox.
     
  50. devast3d

    devast3d

    Joined:
    May 30, 2010
    Posts:
    76
    Small update due to requests and bug reports

    Version 1.3.3
    - Added Capsule3 primitive.
    - Added Distance.Line3Box3() and Distance.Segment3Box3() methods.
    - Added Intersection.TestBox3Capsule3() method.
    - Fixed bug in spline vertex placement code.