Code Monkey home page Code Monkey logo

jcsg's Introduction

JCSG

Build Status Javadocs


Java implementation of BSP based CSG (Constructive Solid Geometry). It is the only simple and free Java implementation I am aware of. This implementation uses an optimized CSG algorithm based on csg.js (see CSG and Node classes). Thanks to the author for creating the csg.js library.

There's also the related VCSG library, a plugin for VRL-Studio and two extension libraries: JCSG-MeshExtension and JCSG-PathExtension.

In addition to CSG this library provides the following features:

  • optimized difference() and union() operations (many thanks to Sebastian Reiter)
  • extrusion of concave, non-intersecting polygons (uses Poly2Tri for triangulation)
  • convex hull (uses QuickHull3D)
  • weighted transformations (Scale, Rotation, Translation and Mirror)
  • STL import and export (STLLoader from Fiji)
  • OBJ export including material information (see screenshot below)
  • supports conversion of CSG's to JavaFX 3D nodes
  • 3d text support (using FXyz)

JCSG on stackoverflow.

To see what's possible with JCSG try JFXScad.

How to Build JCSG

Requirements

  • Java >= 11
  • Internet connection (dependencies are downloaded automatically)
  • IDE: Gradle Plugin (not necessary for command line usage)

IDE

Open the JCSG Gradle project in your favourite IDE (tested with NetBeans 7.4) and build it by calling the assemble task.

Command Line

Navigate to the Gradle project (e.g., path/to/JCSG) and enter the following command

Bash (Linux/OS X/Cygwin/other Unix-like shell)

bash gradlew assemble

Windows (CMD)

gradlew assemble

Code Sample:

// we use cube and sphere as base geometries
CSG cube = new Cube(2).toCSG();
CSG sphere = new Sphere(1.25).toCSG();

// perform union, difference and intersection
CSG cubePlusSphere = cube.union(sphere);
CSG cubeMinusSphere = cube.difference(sphere);
CSG cubeIntersectSphere = cube.intersect(sphere);
        
// translate geometries to prevent overlapping 
CSG union = cube.
        union(sphere.transformed(Transform.unity().translateX(3))).
        union(cubePlusSphere.transformed(Transform.unity().translateX(6))).
        union(cubeMinusSphere.transformed(Transform.unity().translateX(9))).
        union(cubeIntersectSphere.transformed(Transform.unity().translateX(12)));
        
// save union as stl
try {
    FileUtil.write(
            Paths.get("sample.stl"),
            union.toStlString()
    );
} catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

Thanks to

jcsg's People

Contributors

cpoliwoda avatar madhephaestus avatar miho avatar travisfw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jcsg's Issues

Creating a Polygon

Hi,

I am unable to reproduce the following example (found here)

List<Vector3d> vertices = new ArrayList<>();

vertices.add(Vector3d.xyz(0, 0, 0));
vertices.add(Vector3d.xyz(50, 25, 0));
vertices.add(Vector3d.xyz(100, 0, 0));
vertices.add(Vector3d.xyz(0, 100, 0));

List<Polygon> t = Polygon.fromConcavePoints(vertices);
CSG csg = CSG.fromPolygons(t);

All I get is this error:

This static method of interface Vector3d can only be accessed as Vector3d.xyz

Again, I might be doing something wrong and would really appreciate some help.

Respectfully

Stackoverflow

I have many instances over stackoverflow exception
Exception in thread "JavaFX Application Thread" java.lang.StackOverflowError
at java.util.HashSet.add(HashSet.java:220)
at java.util.stream.DistinctOps$1$2.accept(DistinctOps.java:174)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at eu.mihosoft.jcsg.Node.build(Node.java:244)
at eu.mihosoft.jcsg.Node.build(Node.java:259)
at eu.mihosoft.jcsg.Node.build(Node.java:259)
at eu.mihosoft.jcsg.Node.build(Node.java:259)
...

In one run I have a success rate of about 80% with 20% failures, where the geometries are similar but different.

I have tried increasing the stack size with this runtime option: -Xss16m
But this seems to make no difference.

Any thoughts or ideas please?
Thanks.
Jim

Extrude feature has issues when complex paths from text fonts are used

I have been attempting to make an automatic extrusion from text using Javas font's and the PathIterator interface. This is the gist that is working in BowlerStudio demonstrating that the points are being created in a sane way and in the right locations:

https://gist.github.com/madhephaestus/da78cb13a62c1a5c691f

If you uncomment line 45, you will get the error.

I use a simple loop to create the array list of points from the PathIterator then extrude the points with the Extrude.points. This causes this exception:

java.lang.RuntimeException: Intersecting Constraints eu.mihosoft.vrl.v3d.ext.org.poly2tri.DelaunayTriangle@152491d5 is constrained Edge accross [389.1875,-64.78125]
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.DTSweep.flipEdgeEvent(DTSweep.java:614)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.DTSweep.flipEdgeEvent(DTSweep.java:654)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.DTSweep.edgeEvent(DTSweep.java:591)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.DTSweep.edgeEvent(DTSweep.java:360)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.DTSweep.sweep(DTSweep.java:136)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.DTSweep.triangulate(DTSweep.java:103)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.Poly2Tri.triangulate(Poly2Tri.java:127)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.Poly2Tri.triangulate(Poly2Tri.java:117)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.Poly2Tri.triangulate(Poly2Tri.java:86)
at eu.mihosoft.vrl.v3d.ext.org.poly2tri.PolygonUtil.concaveToConvex(PolygonUtil.java:99)
at eu.mihosoft.vrl.v3d.Extrude.extrude(Extrude.java:92)
at eu.mihosoft.vrl.v3d.Extrude.points(Extrude.java:82)
at eu.mihosoft.vrl.v3d.Extrude$points.call(Unknown Source)
at Script1.run(Script1.groovy:57)
at com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine.runGroovy(ScriptingEngine.java:376)
at com.neuronrobotics.bowlerstudio.scripting.ScriptingEngine.inlineScriptRun(ScriptingEngine.java:340)
at com.neuronrobotics.bowlerstudio.scripting.ScriptingEngineWidget$5.run(ScriptingEngineWidget.java:426)

javacadtext

Feature request: Processing library

Many people would be really happy if a CSG library existed for Processing. Just saying ;)

Processing (processing.org) is based in Java 7. I took a look at porting the code myself, but first I would have to study how to port Java 8 code to Java 7. Would that be a complicated task? Never did Java 8.

I think a possible Processing CSG library would include only a subset of the JCSG features, since it's already possible to create spheres, cubes, and other shapes, it's easy to display them simply by calling shape(myShape), where myShape is of type PShape. Processing has many 3D libraries available with mesh generation features (http://hg.postspectacular.com/toxiclibs/, http://hemesh.wblut.com/ and others), which offer iso surfaces, convex hull, polyhedrons, tubes, bending, stretching, and other kinds of distortion. Only CSG is missing :)

Are there plans for such a Processing library? Otherwise, do you know of a Java 8 to 7 translation guide?

Thanks!

Creating pyramids

Hi,
Do you have any examples of creating pyramids and intersecting them with each other?
Thanks Best

CSG class : issue in OBJ file generation : faces are not saved

Hello,

Currently, using the method toObjString(StringBuilder sb) {...} leads to a file whose content looks like:

Group

g v3d.csg

Vertices

v 0.0 10.0 0.0
v 2.0 10.0 0.0
v 2.0 5.0 0.0
v 10.0 5.0 0.0

Faces

Indices of faces are not written in the file. The issue can be easily solved by adding one line in a loop of the method (update of the indices list, see last line below):

    for (Polygon p : polygons) {
        List<Integer> polyIndices = new ArrayList<>();

        p.vertices.stream().forEach((v) -> {
            if (!vertices.contains(v)) {
                vertices.add(v);
                v.toObjString(sb);
                polyIndices.add(vertices.size());
            } else {
                polyIndices.add(vertices.indexOf(v) + 1);
            }
        });
        
        // The line below solves the issue, but was it the idea of the dev ??
        indices.add(new PolygonStruct(null, polyIndices, null));

    }

Regards

RoundedCube should not ignore 'center' field

Code of RoundedCube class completely ignores value of field center.
This way it's impossible to create RoundedCube that is NOT centered at (0,0,0) even when centered is set to false.

How to set color to Java JCSG object? [JavaFX]

I'm currently using the Java JCSG library to create Constructive Solid Geometry objects such as intersections, unions and difference between 3D objects. Using the JCSG library, I have the following code for creating objects (cube in this case)

private static CSG createCube(double w, double h, double d) { return new Cube(w, h, d).toCSG(); }
and whenever I want to set the colour of this specific CSG object I use the following

private static CSG color(CSG shape, Color c) { return shape.color(c); }
However when I transform these objects to a MeshView and pass them to the javafx.scene.Group the color is the default one (red):
`
Group world = new Group();
System.out.println(this.objects.size());
for (CSG p : this.objects) {
var x = p.toJavaFXMesh().getAsMeshViews().get(0);

        for(Material m: p.toJavaFXMesh().getMaterials()){
            System.out.println(m.toString());

            // System.out.println(m1.getDiffuseColor().toString());
            x.setMaterial((PhongMaterial)m);
        }
        world.getChildren().add(x);
    }

    Scene scene = new Scene(world, WIDTH, HEIGHT, true);
    scene.setFill(Color.PALETURQUOISE);
    scene.setCamera(camera);

    // initMouseControl(world, scene, primaryStage);
    addEventHandlers(scene, camera);
    primaryStage.setTitle("Pane");
    primaryStage.setScene(scene);
    primaryStage.show();

Where this.objects holds all the objects that I created in another class.
package me.emil;

import javafx.scene.paint.Color;
import me.emil.helpers.Pane;

public class App {
public static void main(String[] args) {
CSGStorage singleton = CSGStorage.getInstance();
var x = singleton.sphere(50);
x = singleton.translate(x, 100, 0, 0);
x = singleton.color(x, Color.YELLOW);
singleton.addPrimitive(x);

    Pane p = new Pane();
    p.launchPane();
}

}
`

Difficulty locating .jar file download

[Disclaimer, I may have only had trouble because I'm dumb]

The .jar download link was a bit hard for me to find. There's the very small link to bintray from the README, then it says "No direct downloads selected for this package," so you have to click "Files," then it looks like there's nothing there until you see the quite tiny "0.5.7" folder, then the right download is in the list with a bunch of other stuff... maybe I'm just dumb but I wasted a good amount of time thinking there was no .jar download and trying to figure out how to use Gradle with the source code to try and make something importable to my project.

Edit: I've now been using the library for a bit and it's freaking fantastic. Just thought I'd mention my appreciation!

TL;DR Please someone smarter than me make the link easier to find.

[FEATURE ADD] Add a simplified API to CSG

CSG is the user facing object and should have wrapper functions to simplify use of the objects in scripts. The old API should not be changed, just helper functions need to be added.

Question: How to create a projection for generating DXF

I would like to generated CNC files for a laser cutter and need to reduce a CSG down to the polygon formed by the CSG and its intersection with a given plane. In OpenSCAD this is called "projection".

This feature would have a large number of other uses such as smart support structure generation for 3d printing, detection of unprintable parts, even better dynamic generation of parts that have to fit together and pull apart.

https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/3D_to_2D_Projection

STL file generated for a simple Polyhedron (L shape) : one face should not be part of the model

Hello,

I want to generate a simple polyhedron (L shape) with the following code:

    List<Vector3d> listPoint = new ArrayList<Vector3d>();
    listPoint.add(Vector3d.xyz(0, 10, 0));
    listPoint.add(Vector3d.xyz(2, 10, 0));
    listPoint.add(Vector3d.xyz(2, 5, 0));
    listPoint.add(Vector3d.xyz(10, 5, 0));
    listPoint.add(Vector3d.xyz(10, 0, 0));
    listPoint.add(Vector3d.xyz(0, 0, 0));
    listPoint.add(Vector3d.xyz(0, 10, 20));
    listPoint.add(Vector3d.xyz(2, 10, 20));
    listPoint.add(Vector3d.xyz(2, 5, 20));
    listPoint.add(Vector3d.xyz(10, 5, 20));
    listPoint.add(Vector3d.xyz(10, 0, 20));
    listPoint.add(Vector3d.xyz(0, 0, 20));
    listPoint.add(Vector3d.xyz(4, 5, 20));
    List<List<Integer>> listFace = new ArrayList<List<Integer>>();
    listFace.add(Arrays.asList(0, 1, 2, 3, 4, 5));
    listFace.add(Arrays.asList(8, 7, 6, 11, 10, 9));
    listFace.add(Arrays.asList(1, 0, 6, 7));
    listFace.add(Arrays.asList(2, 1, 7, 8));
    listFace.add(Arrays.asList(3, 2, 8, 9));
    listFace.add(Arrays.asList(4, 3, 9, 10));
    listFace.add(Arrays.asList(5, 4, 10, 11));
    listFace.add(Arrays.asList(0, 5, 11, 6));
    CSG polyhedron = new Polyhedron(listPoint, listFace).toCSG();

The STL generated file for this polyhedron looks like this:

polyhedronwithonebadface

The red triangle should not be there. Otherwise, everything is fine.

Do I misuse the Polyhedron class, or is there an issue in its implementation ? (of course, using the
Extrude.points(...) method would be the right choice in that case, but I need to focus on Polyhedrons).

Regards

Cylinder rotation in Z axis

Can anyone tell me whether cylinder rotation in Z axis is working or not?

It seems to fail for me - not sure if I'm doing something wrong.

In this example I am trying to build a square pyramid out of cylindrical poles and can't get it to work at all. Any thoughts?

This is my test code.

import eu.mihosoft.jcsg.CSG;
import eu.mihosoft.jcsg.Cylinder;
import eu.mihosoft.jcsg.FileUtil;
import eu.mihosoft.vvecmath.Transform;

import java.io.IOException;
import java.nio.file.Paths;

public class PoleTest
{
    public static void main(String[] args) throws IOException
    {
        CSG result = new PoleTest().toCSG();
        FileUtil.write(Paths.get("PoleTest.stl"), result.toStlString());
    }

    public CSG pole(double length, double radius, double rotX, double rotY, double rotZ, double trX, double trY, double trZ)
    {
        System.out.printf("rotX=%.2f rotY = %.2f rotZ = %.2f%n", rotX, rotY, rotZ);
        CSG innerCyl = new Cylinder(radius, length, 16).toCSG();
        return innerCyl.transformed(Transform.unity().rotX(rotX).rotY(rotY).rotZ(rotZ))
            .transformed(Transform.unity().translate(trX, trY, trZ));
    }

    public CSG toCSG()
    {
        double armLength = 150;
        double armRadius = 5;

        CSG pole1 = pole(armLength, armRadius,0, 60,0, 0,0,45);
        CSG pole2 = pole(armLength*2, armRadius,30, 45,45, armLength, 0, 0);
        CSG pole3 = pole(armLength, armRadius,45, 0,90, 0, armLength,0);
        CSG pole4 = pole(armLength, armRadius,45, 90,0, armLength,armLength,0);
        return pole1.union(pole2).union(pole3).union(pole4);
    }
}

Unioning spheres ends up with too many polygons

After unioning about 70 spheres together, I end up with a lot of polygons, as shown this image:

image

It also takes 5+ minutes to do all of the unions. Do you have any ideas on how to speed this up/clean up the end result? Thanks!

InvocationTargetException when performing boolean operations on complex shapes with JCSG

When I load a .stl and convert to CSG (of the JCSG library) through this method, any boolean operation I perform fails. However simple models native to the JCSG library works fine.

So I get my CSG in a HashMap with the Node (JavaFX node of the CAD model) as a key and then perform the boolean operation union for example like this:

HashMap<Node, CSG> objCSGMap = contentModel.getObjectCSGMap();
Node obj1 = contentModel.getObjGroup().getChildren().get(0);
Node obj2 = contentModel.getObjGroup().getChildren().get(1);
CSG csg1 = objCSGMap.get(obj1);
CSG csg2 = objCSGMap.get(obj2);
CSG result = csg1.union(csg2);
contentModel.set3dContent(result.toJavaFXMeshSimple().getAsMeshViews().get(0), null);

This is the error message:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$383/1876978274.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/2117255219.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 55 more
Caused by: java.lang.StackOverflowError
at eu.mihosoft.vrl.v3d.Node.lambda$build$30(Node.java:244)
at eu.mihosoft.vrl.v3d.Node$$Lambda$429/1450630044.accept(Unknown Source)
at java.util.ArrayList.forEach(Unknown Source)
at eu.mihosoft.vrl.v3d.Node.build(Node.java:243)
at eu.mihosoft.vrl.v3d.Node.build(Node.java:258)
at eu.mihosoft.vrl.v3d.Node.build(Node.java:258)
at eu.mihosoft.vrl.v3d.Node.build(Node.java:258)

However, this works fine:

CSG csg1 = new Cube(10, 70, 4).toCSG();
CSG csg2 = new Cube(40).toCSG();
CSG result = csg1.union(csg2);
contentModel.set3dContent(result.toJavaFXMeshSimple().getAsMeshViews().get(0), null);

So it looks like boolean operations work fine for simple CSG objects from the JCSG library itself and not imported CAD files that have been converted to CSG objects through this method.

Multiple uinions cause StackOverflow Error

I've written this code:

public class Main {

    public static void main(String[] args) throws IOException {
        CSG cube = STL.file(Paths.get("cube.stl"));

        CSG union = cube;
        for (int x = 0; x < 100; x++) {
            union = union.union(cube.transformed(Transform.unity().translateX(x * 10)));
        }

        try {
            FileUtil.write(Paths.get("sample.stl"), union.toStlString());
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

But after 26 unions i get this error:

Exception in thread "main" java.lang.StackOverflowError
at java.util.stream.AbstractPipeline.wrapSink(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.collect(Unknown Source)
at eu.mihosoft.jcsg.Node.build(Node.java:244)
at eu.mihosoft.jcsg.Node.build(Node.java:265)

I'm trying to combine multiple objects to one but unluckily i get this error :/

Split in two objects after difference

Hello and thanks for your work,
I am struggling with a little problem.
Is it possible to split an object in two by building the difference with another object.

Screenshot from 2019-12-03 11-10-01
Screenshot from 2019-12-03 11-10-39

How can I split the green object in two CSGs? I want to keep the lower part.

Thanks.

[FEATURE ADD] Add a bezier extrude

I wrote a Bezier extursion, that lets you extrude along a bezier curve for making complex geometry, would you be interested in me pulling it out to make a clean PR for your upstream system?

It is a lot of work to pull it out to make the PR work, so ill only do it if you are interested in merging that feature (without having to pull all the rest of stuff iv been working on)

Here is the function i would be adding (along with its helper functions)
https://github.com/NeuronRobotics/JCSG/blob/master/src/main/java/eu/mihosoft/vrl/v3d/Extrude.java#L365

samples in the JCSG

First of all, it's a very impressive work.

The project is easy to setup.
However, when I tried the Egg.java or EggCup.java in the sample package
It gives me these:

Exception in thread "main" java.lang.StackOverflowError
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureExplicitCapacity(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at eu.mihosoft.vrl.v3d.Plane.splitPolygon(Plane.java:159)
at eu.mihosoft.vrl.v3d.Node.lambda$2(Node.java:244)
at eu.mihosoft.vrl.v3d.Node$$Lambda$9/4952965.accept(Unknown Source)
at java.util.ArrayList.forEach(Unknown Source)
at eu.mihosoft.vrl.v3d.Node.build(Node.java:243)

I'm not sure it's a bug or something I run the samples not correctly.

Please advise.

Thanks.

Why does "difference" keep parts in the CSG that don't "intersect"

Hi,

We're working with your library and noticed something curious, why does the "substract" function keep parts that don't intersect with the given part?

Imho if they don't intersect then A.difference(B) should just return A

(we ran into a visual issue and now fixed it by first checking if the parts intersect before executing the difference)

image

How to make a csg from complicated svg?

I really appreciate your effort.

I am going to try to make a 3D viewport with CSG function.

It is very important to me about extrusion from DXF section or SVG such as complicated shape.

May I ask why fail to extrude these svg files?

2D section.zip

Quantizing vertices?

Hello.

One issue with CSG as opposed to voxel-based geometry is that there's essentially no upper bound on the complexity of the geometry that can be created. For example, if you create a sphere and then subtract hundreds of tiny spheres from the surface of it, the result will be a very large number of polygons.

One way to get around this is to provide an optional quantization value that causes vertex coordinates to be snapped to the nearest multiple of the value. For example, specifying a quantization value of 1.0 would cause all created vertices to snap to integer coordinates. A value of 0.01 would snap vertex coordinates to the nearest 0.01 and so on. If coincident vertices are eliminated after snapping, this has the effect of putting an effective upper bound on the complexity of the geometry that can be created (at the obvious cost of making the system less able to express nice smooth geometry with high quantization values).

In real-time simulations where users can modify geometry in real-time, having that upper bound can be very important to keep performance to an acceptable level.

How much work do you think would be involved in adding this (optional, opt-in) feature to JCSG?

Calculate Volume of CSG

We should add calculateVolume() and calculateSurfaceArea() methods for CSG objects since this library is used for 3d printing where it's nice to know/estimate how much filament is needed.

[FEATURE ADD] Add SVG loading and extrusion

I have this feature ready to go as well as #32 and can do a clean-room import of this code if the API additions to CSG I made in #33 are approved. This includes a generic bezier path extraction in 2 dimensions for full featured SVG loading (lines and curves). I have used this feature to create an SVG in inkscape, then extrude it in JCSG. The SVG loader can detect when objects are "holes" and semi-intelligently remove holes on the fly. For a functioning example:

https://github.com/Technocopia/Graphics/blob/master/Graphics/SimplifiedLogo/simplified%20logo.svg

becomes

https://github.com/Technocopia/Graphics/blob/master/Graphics/SimplifiedLogo/simplified_logo.stl

How to import OBJ ?

Thank you for this wonderful library @miho .

I'm testing the different functions of JCSG and would like to know how to import an OBJ file.

Writing MyObj = Importer3D.load("column.obj") returns the following error:

Unknown 3D file format [obj] at eu.mihosoft.jcsg.ext.openjfx.importers.Importer3D.loadIncludingAnimation(Importer3D.java:139)

Another attempt with MyObj= ObjImporter("C:/Users/solub/Desktop/meshes/column.obj") returns:

java.net.MalformedURLException: unknown protocol: c
at java.net.URL.(URL.java:600)
at java.net.URL.(URL.java:490)
at java.net.URL.(URL.java:439)
at eu.mihosoft.jcsg.ext.openjfx.importers.obj.ObjImporter.(ObjImporter.java:108)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

Am I doing something wrong here ?

Text3d ignores fonts

Using public Text3d(String text, String fontName, double fontSize, double depth) and Font names:

"Times New Roman"
"Arial"
"Helvetica"

All produce the same result.

(This is cool feature to finally have, thank you!)

License

Can I use in production for commercial use? Where should I mention author?

WeightedTubeSample example causes StackOverflowError

Hi,

When trying out your bundled examples, the 'WeightedTubeSample' crashes with the following stack trace:

Exception in thread "main" java.lang.StackOverflowError
	at java.util.HashMap.put(HashMap.java:612)
	at java.util.HashSet.add(HashSet.java:220)
	at java.util.stream.DistinctOps$1$2.accept(DistinctOps.java:174)
	at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
	at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
	at eu.mihosoft.jcsg.Node.build(Node.java:244)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)
	at eu.mihosoft.jcsg.Node.build(Node.java:259)

Tested against v0.5.7.
The RoundedCubeSample works fine.

Pyramids with top radius of 0 cause any shape to be differenced to fail

If you create a pyramid by making a cylinder with a radius of zero, then triangulation function fails when doing a difference operation between this object and any other.

CSG torso = new Cylinder( 30, // Radius at the bottom
0, // Radius at the top
60, // Height
(int)4 //resolution
).toCSG()//convert to CSG to display

CSG cover = new Cube( 200,// X dimention
200,// Y dimention
200// Z dimention
).toCSG()

Both of these shapes are valid.

This operation however will fail:

cover.difference(torso);

Changing the top radius to a small number is a hack to fix this issue:

CSG torso = new Cylinder( 30, // Radius at the bottom
0.001, // Radius at the top
60, // Height
(int)4 //resolution
).toCSG()//convert to CSG to display

This bug is related to #15 in that it originates in the triangulation function falling off the front surface and ending up inverting the surfaces.

Text3d support

Hi,

Why existing mechanism of displaying 3d text was commented (during refactoring?) ? Is is possible to return it back?

Thanks,
Slava

RoundedCube should be centered by default

RoundedCube class has private field centered which gets false value during initialization as there's no explicit initialization of that field. The whole functionality that is controlled by that flag field looks to me like copy pasted from Cube class with the only difference that in Cube class it is explicitly initialized with true value. This copy-paste mistake makes it impossible to control centered field in RoundedCube as the only method the changes its value (noCenter()) changes it to false so there's no possibility to change it to true.

Feature Add to resolve #16

In this feature a function should be added that takes in a CSG and a slice plane and returns a list of polygons of all the features at that plane. This would add the feature to resolve #16

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.