javafx.scene.shape.TriangleMesh Java Examples

The following examples show how to use javafx.scene.shape.TriangleMesh. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OrthoSliceMeshFX.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public void setTexCoords(final RealLocalizable texCoordMin, final RealLocalizable texCoordMax)
{
	final List<RealPoint> texCoordsPoints = calculateTexCoords(texCoordMin, texCoordMax);
	for (int row = 0; row < 2; ++row) {
		for (int col = 0; col < 2; ++col) {
			final MeshView meshView = meshViews.get(2 * row + col);
			if (meshView == null)
				continue;
			final TriangleMesh mesh = (TriangleMesh) meshView.getMesh();

			mesh.getTexCoords().clear();
			final int[] pointIndices = getPointIndicesForQuadrant(row, col);
			for (final int ptIndex : pointIndices) {
				texCoordsPoints.get(ptIndex).localize(buf2D);
				mesh.getTexCoords().addAll(buf2D);
			}
		}
	}
}
 
Example #2
Source File: MeshGeneratorJobManager.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private static MeshView makeMeshView(final PainteraTriangleMesh verticesAndNormals)
{
	final float[]      vertices = verticesAndNormals.getVertices();
	final float[]      normals  = verticesAndNormals.getNormals();
	final TriangleMesh mesh     = new TriangleMesh();
	mesh.getPoints().addAll(vertices);
	mesh.getNormals().addAll(normals);
	mesh.getTexCoords().addAll(0, 0);
	mesh.setVertexFormat(VertexFormat.POINT_NORMAL_TEXCOORD);
	final int[] faceIndices = new int[vertices.length];
	for (int i = 0, k = 0; i < faceIndices.length; i += 3, ++k)
	{
		faceIndices[i + 0] = k;
		faceIndices[i + 1] = k;
		faceIndices[i + 2] = 0;
	}
	mesh.getFaces().addAll(faceIndices);
	final PhongMaterial material = Meshes.painteraPhongMaterial();
	final MeshView mv = new MeshView(mesh);
	mv.setOpacity(1.0);
	mv.setCullFace(CullFace.FRONT);
	mv.setMaterial(material);
	mv.setDrawMode(DrawMode.FILL);
	return mv;
}
 
Example #3
Source File: CatmaidJsonLoader.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@Override
public TriangleMesh loadMesh(Path path) throws IOException {
	final Gson gson = new Gson();
	try (final FileReader reader = new FileReader(path.toFile())) {
		final JsonObject json = gson.fromJson(reader, JsonObject.class);
		final Document doc = Jsoup.parse(json.get(MESH_KEY).getAsString());
		final Elements indexedTriangleSet = doc.select(INDEXED_TRIANGLE_SET_KEY);
		final int[] indices = Stream
				.of(indexedTriangleSet.attr(INDEX_ATTRIBUTE_KEY).split(" "))
				.flatMapToInt(s -> IntStream.of(Integer.parseInt(s), 0))
				.toArray();
		final Elements coordinate = indexedTriangleSet.select(COORDINATE_KEY);
		final double[] vertices = Stream
				.of(coordinate.attr(POINT_ATTRIBUTE_KEY).split(" "))
				.mapToDouble(Double::parseDouble)
				.toArray();
		final float[] texCoordinates = new float[] {0.0f, 0.0f};
		// VertexFormat.POINT_TEXCOORD
		// p0, t0, p1, t1, p3, t3
		final TriangleMesh mesh = new TriangleMesh(VertexFormat.POINT_TEXCOORD);
		mesh.getTexCoords().setAll(texCoordinates);
		mesh.getPoints().setAll(fromDoubleArray(vertices));
		mesh.getFaces().setAll(indices);
		return mesh;
	}
}
 
Example #4
Source File: ObjWriter.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void writeMesh(
		final TriangleMesh mesh,
		final Path path) throws IOException {

	final float[] texCoords = new float[mesh.getTexCoords().size()];
	final float[] vertices = new float[mesh.getPoints().size()];
	final float[] normals = new float[mesh.getNormals().size()];
	final int[] faces = new int[mesh.getFaces().size()];
	mesh.getTexCoords().toArray(texCoords);
	mesh.getPoints().toArray(vertices);
	mesh.getNormals().toArray(normals);
	mesh.getFaces().toArray(faces);

	final Obj obj = Objs.createFromIndexedTriangleData(
			IntBuffer.wrap(faces),
			FloatBuffer.wrap(vertices),
			FloatBuffer.wrap(texCoords),
			FloatBuffer.wrap(normals));

	try (final OutputStream fos = new FileOutputStream(path.toFile())) {
		de.javagl.obj.ObjWriter.write(obj, fos);
	}
}
 
Example #5
Source File: PyramidMesh.java    From FXyzLib with GNU General Public License v3.0 6 votes vote down vote up
private TriangleMesh createPyramid(double hypotenuse , double height){
	
	TriangleMesh mesh = new TriangleMesh();
	
	float hy = (float)hypotenuse;
	float he = (float)height;
	
	mesh.getPoints().addAll(
			  0 ,   0 ,   0,    //point O
			  0 ,  he , -hy/2,  //point A
			-hy/2, he ,   0,    //point B
			 hy/2, he ,   0,	//point C
			  0 ,  he ,  hy/2	//point D
			);
	
	
	mesh.getTexCoords().addAll(0,0);
	
	mesh.getFaces().addAll(
			0 , 0 , 2 , 0 , 1 , 0 ,		// O-B-A
			0 , 0 , 1 , 0 , 3 , 0 ,		// O-A-C
			0 , 0 , 3 , 0 , 4 , 0 ,		// O-C-D
			0 , 0 , 4 , 0 , 2 , 0 ,		// O-D-B
			4 , 0 , 1 , 0 , 2 , 0 ,		// D-A-B
			4 , 0 , 3 , 0 , 1 , 0 		// D-C-A
			);
	
	
	return mesh;
	
}
 
Example #6
Source File: TexturedMesh.java    From FXyzLib with GNU General Public License v3.0 6 votes vote down vote up
protected TriangleMesh createMesh(MeshHelper mh) {
        float[] points0=mh.getPoints();
        float[] f = mh.getF();
        listVertices.clear();
        listVertices.addAll(IntStream.range(0, points0.length/3)
                        .mapToObj(i -> new Point3D(points0[3*i], points0[3*i+1], points0[3*i+2],f[i]))
                        .collect(Collectors.toList()));
        
        textureCoords=mh.getTexCoords();
        
        int[] faces0 = mh.getFaces();
        listFaces.clear();
        listFaces.addAll(IntStream.range(0, faces0.length/6)
                        .mapToObj(i -> new Face3(faces0[6*i+0], faces0[6*i+2], faces0[6*i+4]))
                        .collect(Collectors.toList()));
        
        listTextures.clear();
//        listTextures.addAll(listFaces);  
        listTextures.addAll(IntStream.range(0, faces0.length/6)
                        .mapToObj(i -> new Face3(faces0[6*i+1], faces0[6*i+3], faces0[6*i+5]))
                        .collect(Collectors.toList()));
        
        smoothingGroups=mh.getFaceSmoothingGroups();
        
        return createMesh();
    }
 
Example #7
Source File: SmoothingGroups.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Calculates smoothing groups for data formatted in TriangleMesh style
 * @param flatFaces An array of faces, where each triangle face is represented by 6 (vertex and uv) indices
 * @param flatFaceNormals An array of face normals, where each triangle face is represented by 3 normal indices
 * @param normals The array of normals
 * @return An array of smooth groups, where the length of the array is the number of faces
 */
public static int[] calcSmoothGroups(TriangleMesh mesh, int[] flatFaces, int[] flatFaceNormals, float[] normals) {
    int faceElementSize = mesh.getFaceElementSize();
    int[][] faces = new int[flatFaces.length/faceElementSize][faceElementSize];
    for (int f = 0; f < faces.length; f++) {
        for (int e = 0; e < faceElementSize; e++) {
            faces[f][e] = flatFaces[f * faceElementSize + e];
        }
    }
    int pointElementSize = mesh.getPointElementSize();
    int[][] faceNormals = new int[flatFaceNormals.length/pointElementSize][pointElementSize];
    for (int f = 0; f < faceNormals.length; f++) {
        for (int e = 0; e < pointElementSize; e++) {
            faceNormals[f][e] = flatFaceNormals[f * pointElementSize + e];
        }
    }
    SmoothingGroups smoothGroups = new SmoothingGroups(faces, faceNormals, normals);
    return smoothGroups.calcSmoothGroups();
}
 
Example #8
Source File: Utils.java    From RubikFX with GNU General Public License v3.0 5 votes vote down vote up
private static Point3D getMeshNormal(MeshView mesh){
    TriangleMesh tm=(TriangleMesh)mesh.getMesh();
    float[] fPoints=new float[tm.getPoints().size()];
    tm.getPoints().toArray(fPoints);
    Point3D BA=new Point3D(fPoints[3]-fPoints[0],fPoints[4]-fPoints[1],fPoints[5]-fPoints[2]);
    Point3D CA=new Point3D(fPoints[6]-fPoints[0],fPoints[7]-fPoints[1],fPoints[8]-fPoints[2]);
    Point3D normal=BA.crossProduct(CA);
    Affine a=new Affine(mesh.getTransforms().get(0));
    return a.transform(normal.normalize());
}
 
Example #9
Source File: MeshUtils.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
public static CSG mesh2CSG(Mesh mesh) throws IOException {

        List<Polygon> polygons = new ArrayList<>();
        List<Vector3d> vertices = new ArrayList<>();
        if(mesh instanceof TriangleMesh){
            // Get faces
            ObservableFaceArray faces = ((TriangleMesh)mesh).getFaces();
            int[] f=new int[faces.size()];
            faces.toArray(f);

            // Get vertices
            ObservableFloatArray points = ((TriangleMesh)mesh).getPoints();
            float[] p = new float[points.size()];
            points.toArray(p);

            // convert faces to polygons
            for(int i=0; i<faces.size()/6; i++){
                int i0=f[6*i], i1=f[6*i+2], i2=f[6*i+4];
                vertices.add(new Vector3d(p[3*i0], p[3*i0+1], p[3*i0+2]));
                vertices.add(new Vector3d(p[3*i1], p[3*i1+1], p[3*i1+2]));
                vertices.add(new Vector3d(p[3*i2], p[3*i2+1], p[3*i2+2]));
                polygons.add(Polygon.fromPoints(vertices));
                vertices = new ArrayList<>();
            }
        }

        return CSG.fromPolygons(new PropertyStorage(),polygons);
    }
 
Example #10
Source File: OctahedronMesh.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
private TriangleMesh createOctahedron(double hypotenuse , double height){
	
	TriangleMesh mesh = new TriangleMesh();
	
	float hy = (float)hypotenuse;
	float he = (float)height;
	
	mesh.getPoints().addAll(
			  0 ,   0 ,   0,    //point O
			  0 ,  he , -hy/2,  //point A
			-hy/2, he ,   0,    //point B
			 hy/2, he ,   0,	//point C
			  0 ,  he ,  hy/2,	//point D
			  0 , 2*he ,  0     //point E 
			);
	
	
	mesh.getTexCoords().addAll(0,0);
	
	mesh.getFaces().addAll(
			0 , 0 , 2 , 0 , 1 , 0 ,		// O-B-A
			0 , 0 , 1 , 0 , 3 , 0 ,		// O-A-C
			0 , 0 , 3 , 0 , 4 , 0 ,		// O-C-D
			0 , 0 , 4 , 0 , 2 , 0 ,		// O-D-B
			4 , 0 , 1 , 0 , 2 , 0 ,		// D-A-B
			4 , 0 , 3 , 0 , 1 , 0 ,		// D-C-A
			5 , 0 , 2 , 0 , 1 , 0 ,		// E-B-A
			5 , 0 , 1 , 0 , 3 , 0 ,		// E-A-C
			5 , 0 , 3 , 0 , 4 , 0 ,		// E-C-D
			5 , 0 , 4 , 0 , 2 , 0 		// E-D-B
			);
	
	
	return mesh;
	
}
 
Example #11
Source File: CSGMesh.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
private TriangleMesh createCSGMesh(){
    List<Vertex> vertices = new ArrayList<>();
    List<List<Integer>> indices = new ArrayList<>();

    listVertices.clear();
    primitive.getPolygons().forEach(p -> {
        List<Integer> polyIndices = new ArrayList<>();
        
        p.vertices.forEach(v -> {
            if (!vertices.contains(v)) {
                vertices.add(v);
                listVertices.add(new Point3D((float)v.pos.x, (float)v.pos.y, (float)v.pos.z));
                polyIndices.add(vertices.size());
            } else {
                polyIndices.add(vertices.indexOf(v) + 1);
            }
        });

        indices.add(polyIndices);
        
    });
    
    textureCoords=new float[]{0f,0f};
    listTextures.clear();
    listFaces.clear();
    indices.forEach(pVerts-> {
        int index1 = pVerts.get(0);
        for (int i = 0; i < pVerts.size() - 2; i++) {
            int index2 = pVerts.get(i + 1);
            int index3 = pVerts.get(i + 2);

            listTextures.add(new Face3(0, 0, 0));
            listFaces.add(new Face3(index1-1, index2-1, index3-1));
        }
    });
    int[] faceSmoothingGroups = new int[listFaces.size()];
    smoothingGroups=faceSmoothingGroups;
    
    return createMesh();
}
 
Example #12
Source File: ConeMesh.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
private TriangleMesh createCone(int divisions, float radius, float height) {
    TriangleMesh mesh = new TriangleMesh();
    //Start with the top of the cone, later we will build our faces from these
    mesh.getPoints().addAll(0,0,0); //Point 0: Top of the Cone        
    //Generate the segments of the bottom circle (Cone Base)
    double segment_angle = 2.0 * Math.PI / divisions;
    float x, z;
    double angle;
    double halfCount = (Math.PI / 2 - Math.PI / (divisions / 2)); 
    // Reverse loop for speed!! der
    for(int i=divisions+1;--i >= 0; ) {
        angle = segment_angle * i;
        x = (float)(radius * Math.cos(angle - halfCount));
        z = (float)(radius * Math.sin(angle - halfCount));
        mesh.getPoints().addAll(x,height,z); 
    }   
    mesh.getPoints().addAll(0,height,0); //Point N: Center of the Cone Base

    //@TODO Birdasaur for now we'll just make an empty texCoordinate group
    //@DUB HELP ME DUBi Wan Kanobi, you are my only hope!
    //I'm not good at determining Texture Coordinates
    mesh.getTexCoords().addAll(0,0); 
    //Add the faces "winding" the points generally counter clock wise
    //Must loop through each face, not including first and last points
    for(int i=1;i<=divisions;i++) {
        mesh.getFaces().addAll( //use dummy texCoords, @TODO Upgrade face code to be real 
            0,0,i+1,0,i,0,           // Vertical Faces "wind" counter clockwise
            divisions+2,0,i,0,i+1,0   // Base Faces "wind" clockwise
        ); 
    }
    return mesh;
}
 
Example #13
Source File: MeshHelper.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
public MeshHelper(TriangleMesh tm) {
    this.points = tm.getPoints().toArray(points);
    this.texCoords = tm.getTexCoords().toArray(texCoords);
    this.faces = tm.getFaces().toArray(faces);
    this.faceSmoothingGroups = tm.getFaceSmoothingGroups().toArray(faceSmoothingGroups);
    this.f=new float[points.length/3];
}
 
Example #14
Source File: TrapezoidMesh.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
private TriangleMesh createTrapezoid (double smallSize , double bigSize , double high ,double depth){
    TriangleMesh m = new TriangleMesh();
    float s = ((float)smallSize) ;
    float b = ((float)bigSize);
    float h = ((float)high);
    float d = ((float)depth);

    //create Points
    m.getPoints().addAll(
            -s/2 , -h/2 ,  d/2,	// A = 0
            s/2 , -h/2 ,  d/2,	// B = 1
            -b/2 ,  h/2 ,  d/2,	// C = 2
            b/2 ,  h/2 ,  d/2,	// D = 3
            -s/2 , -h/2 , -d/2,	// E = 4
            s/2 , -h/2 , -d/2,	// F = 5
            -b/2 ,  h/2 , -d/2,	// G = 6
            b/2 ,  h/2 , -d/2	// H = 7
    );

    m.getTexCoords().addAll(0,0);

    m.getFaces().addAll(
            0 , 0 , 1 , 0 , 3 , 0 ,		// A-B-D
            0 , 0 , 3 , 0 , 2 , 0 , 	// A-D-C
            0 , 0 , 2 , 0 , 6 , 0 ,		// A-C-G
            0 , 0 , 6 , 0 , 4 , 0 , 	// A-G-E
            0 , 0 , 4 , 0 , 1 , 0 ,		// A-E-B
            1 , 0 , 4 , 0 , 5 , 0 , 	// B-E-F
            1 , 0 , 5 , 0 , 7 , 0 ,		// B-F-H
            1 , 0 , 7 , 0 , 3 , 0 ,		// B-H-D
            3 , 0 , 7 , 0 , 6 , 0 ,		// D-H-G
            3 , 0 , 6 , 0 , 2 , 0 ,		// D-G-C
            6 , 0 , 7 , 0 , 5 , 0 ,		// G-H-F
            6 , 0 , 5 , 0 , 4 , 0		// G-F-E
    );

    return m ;
}
 
Example #15
Source File: CatmaidJsonWriter.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeMesh(
		final TriangleMesh mesh,
		final Path path) throws IOException {

	throw new UnsupportedOperationException("Not implemented yet!");
}
 
Example #16
Source File: Utils.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Point3D getMeshNormal(MeshView mesh){
    TriangleMesh tm = (TriangleMesh) mesh.getMesh();
    float[] fPoints = new float[tm.getPoints().size()];
    tm.getPoints().toArray(fPoints);
    Point3D BA = new Point3D(fPoints[3] - fPoints[0], fPoints[4] - fPoints[1], fPoints[5] - fPoints[2]);
    Point3D CA = new Point3D(fPoints[6] - fPoints[0], fPoints[7] - fPoints[1], fPoints[8] - fPoints[2]);
    Point3D normal = BA.crossProduct(CA);
    Affine a = new Affine(mesh.getTransforms().get(0));
    return a.transform(normal.normalize());
}
 
Example #17
Source File: Fx3DRawDataFileDataset.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
public Fx3DRawDataFileDataset(RawDataFile dataFile,
        float[][] intensityValues, int rtResolution, int mzResolution,
        double maxBinnedIntensity, String fileName, Color peakColor) {
    super(dataFile, fileName, peakColor);
    this.intensityValues = intensityValues;
    this.rtResolution = rtResolution;
    this.mzResolution = mzResolution;
    this.maxBinnedIntensity = maxBinnedIntensity;
    mesh = new TriangleMesh();

    peakListIndices = new int[rtResolution][mzResolution];
    float factorX = (float) SIZE / rtResolution;
    float factorZ = (float) SIZE / mzResolution;

    for (int i = 0; i < rtResolution; i++) {
        for (int j = 0; j < mzResolution; j++) {
            if (maxIntensityValue < intensityValues[i][j]) {
                maxIntensityValue = intensityValues[i][j];
            }
        }
    }

    for (int x = 0; x < rtResolution; x++) {
        for (int z = 0; z < mzResolution; z++) {
            mesh.getPoints().addAll((float) x * factorX,
                    -intensityValues[x][z] * AMPLIFI, (float) z * factorZ);
            if (intensityValues[x][z] > 0.022 * maxIntensityValue) {
                peakListIndices[x][z] = 1;
            }
        }
    }

    int rtLength = rtResolution;
    int mzLength = mzResolution;
    float rtTotal = rtLength;
    float mzTotal = mzLength;

    for (float x = 0; x < rtLength - 1; x++) {
        for (float y = 0; y < mzLength - 1; y++) {

            float x0 = x / rtTotal;
            float y0 = y / mzTotal;
            float x1 = (x + 1) / rtTotal;
            float y1 = (y + 1) / mzTotal;

            mesh.getTexCoords().addAll( //
                    x0, y0, // 0, top-left
                    x0, y1, // 1, bottom-left
                    x1, y0, // 2, top-right
                    x1, y1 // 3, bottom-right
            );
        }
    }

    // faces
    for (int x = 0; x < rtLength - 1; x++) {
        for (int z = 0; z < mzLength - 1; z++) {

            int tl = x * mzLength + z; // top-left
            int bl = x * mzLength + z + 1; // bottom-left
            int tr = (x + 1) * mzLength + z; // top-right
            int br = (x + 1) * mzLength + z + 1; // bottom-right

            int offset = (x * (mzLength - 1) + z) * 8 / 2; // div 2 because
                                                           // we have u AND
                                                           // v in the list

            // working
            mesh.getFaces().addAll(bl, offset + 1, tl, offset + 0, tr,
                    offset + 2);
            mesh.getFaces().addAll(tr, offset + 2, br, offset + 3, bl,
                    offset + 1);

        }
    }
    setNodeColor(peakColor);
    meshView.setMesh(mesh);
    meshView.setCullFace(CullFace.NONE);
    meshView.setDrawMode(DrawMode.FILL);
    meshView.setDepthTest(DepthTest.ENABLE);
    LOG.finest("Plot mesh is ready.");
}
 
Example #18
Source File: Fx3DRawDataFileDataset.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public Fx3DRawDataFileDataset(RawDataFile dataFile, float[][] intensityValues, int rtResolution,
    int mzResolution, double maxBinnedIntensity, String fileName, Color peakColor) {
  super(dataFile, fileName, peakColor);
  this.intensityValues = intensityValues;
  this.rtResolution = rtResolution;
  this.mzResolution = mzResolution;
  this.maxBinnedIntensity = maxBinnedIntensity;
  mesh = new TriangleMesh();

  peakListIndices = new int[rtResolution][mzResolution];
  float factorX = (float) SIZE / rtResolution;
  float factorZ = (float) SIZE / mzResolution;

  for (int i = 0; i < rtResolution; i++) {
    for (int j = 0; j < mzResolution; j++) {
      if (maxIntensityValue < intensityValues[i][j]) {
        maxIntensityValue = intensityValues[i][j];
      }
    }
  }

  for (int x = 0; x < rtResolution; x++) {
    for (int z = 0; z < mzResolution; z++) {
      mesh.getPoints().addAll((float) x * factorX, -intensityValues[x][z] * AMPLIFI,
          (float) z * factorZ);
      if (intensityValues[x][z] > 0.022 * maxIntensityValue) {
        peakListIndices[x][z] = 1;
      }
    }
  }

  int rtLength = rtResolution;
  int mzLength = mzResolution;
  float rtTotal = rtLength;
  float mzTotal = mzLength;

  for (float x = 0; x < rtLength - 1; x++) {
    for (float y = 0; y < mzLength - 1; y++) {

      float x0 = x / rtTotal;
      float y0 = y / mzTotal;
      float x1 = (x + 1) / rtTotal;
      float y1 = (y + 1) / mzTotal;

      mesh.getTexCoords().addAll( //
          x0, y0, // 0, top-left
          x0, y1, // 1, bottom-left
          x1, y0, // 2, top-right
          x1, y1 // 3, bottom-right
      );
    }
  }

  // faces
  for (int x = 0; x < rtLength - 1; x++) {
    for (int z = 0; z < mzLength - 1; z++) {

      int tl = x * mzLength + z; // top-left
      int bl = x * mzLength + z + 1; // bottom-left
      int tr = (x + 1) * mzLength + z; // top-right
      int br = (x + 1) * mzLength + z + 1; // bottom-right

      int offset = (x * (mzLength - 1) + z) * 8 / 2; // div 2 because
                                                     // we have u AND
                                                     // v in the list

      // working
      mesh.getFaces().addAll(bl, offset + 1, tl, offset + 0, tr, offset + 2);
      mesh.getFaces().addAll(tr, offset + 2, br, offset + 3, bl, offset + 1);

    }
  }
  setNodeColor(peakColor);
  meshView.setMesh(mesh);
  meshView.setCullFace(CullFace.NONE);
  meshView.setDrawMode(DrawMode.FILL);
  meshView.setDepthTest(DepthTest.ENABLE);
  logger.finest("Plot mesh is ready.");
}
 
Example #19
Source File: OBJWriter.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
public OBJWriter(TriangleMesh mesh, String fileName){
    this.mesh=mesh;
    this.fileName=fileName;
}
 
Example #20
Source File: MeshUtils.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
public static void mesh2STL(String fileName, Mesh mesh) throws IOException{

        if(!(mesh instanceof TriangleMesh)){
            return;
        }
        // Get faces
        ObservableFaceArray faces = ((TriangleMesh)mesh).getFaces();
        int[] f=new int[faces.size()];
        faces.toArray(f);

        // Get vertices
        ObservableFloatArray points = ((TriangleMesh)mesh).getPoints();
        float[] p = new float[points.size()];
        points.toArray(p);

        StringBuilder sb = new StringBuilder();
        sb.append("solid meshFX\n");

        // convert faces to polygons
        for(int i=0; i<faces.size()/6; i++){
            int i0=f[6*i], i1=f[6*i+2], i2=f[6*i+4];
            Point3D pA=new Point3D(p[3*i0], p[3*i0+1], p[3*i0+2]);
            Point3D pB=new Point3D(p[3*i1], p[3*i1+1], p[3*i1+2]);
            Point3D pC=new Point3D(p[3*i2], p[3*i2+1], p[3*i2+2]);
            Point3D pN=pB.subtract(pA).crossProduct(pC.subtract(pA)).normalize();

            sb.append("  facet normal ").append(pN.getX()).append(" ").append(pN.getY()).append(" ").append(pN.getZ()).append("\n");
            sb.append("    outer loop\n");
            sb.append("      vertex ").append(pA.getX()).append(" ").append(pA.getY()).append(" ").append(pA.getZ()).append("\n");
            sb.append("      vertex ").append(pB.getX()).append(" ").append(pB.getY()).append(" ").append(pB.getZ()).append("\n");
            sb.append("      vertex ").append(pC.getX()).append(" ").append(pC.getY()).append(" ").append(pC.getZ()).append("\n");
            sb.append("    endloop\n");
            sb.append("  endfacet\n");
        }

        sb.append("endsolid meshFX\n");

        // write file
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(fileName), Charset.forName("UTF-8"),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
            writer.write(sb.toString());
        }
    }
 
Example #21
Source File: CatmaidJsonLoader.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
		PlatformImpl.startup(() -> {});
		final Path path = Paths.get(System.getProperty("user.home"), "Downloads", "catmaid-meshes", "Block3.json");
		final TriangleMesh mesh = new CatmaidJsonLoader().loadMesh(path);
		final double[] min = {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY};
		final double[] max = {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY};
		for (int i = 0; i < mesh.getPoints().size(); i += 3) {
			for (int d = 0; d < 3; ++d) {
				min[d] = Math.min(min[d], mesh.getPoints().get(i + d));
				max[d] = Math.max(max[d], mesh.getPoints().get(i + d));
			}
		}
		System.out.print(Arrays.toString(min) +" " + Arrays.toString(max));
		final Interval interval = Intervals.smallestContainingInterval(new FinalRealInterval(min, max));
		final MeshView mv = new MeshView(mesh);
		mv.setMaterial(Meshes.painteraPhongMaterial(Color.WHITE));
		mv.setDrawMode(DrawMode.FILL);
		mv.setCullFace(CullFace.BACK);
		final Viewer3DFX viewer = new Viewer3DFX(800, 600);
		viewer.meshesEnabledProperty().set(true);
		mv.setOpacity(1.0);
		viewer.setInitialTransformToInterval(interval);
		final MeshView mv2 = new MeshView(mesh);
		mv.setMaterial(Meshes.painteraPhongMaterial());
		mv.setDrawMode(DrawMode.FILL);
		mv.setCullFace(CullFace.BACK);
		mv2.setTranslateX(100);
		viewer.meshesGroup().getChildren().addAll(mv, mv2);
		Platform.setImplicitExit(true);
		Platform.runLater(() -> {
			final Scene scene = new Scene(viewer);
			final Stage stage = new Stage();
			stage.setScene(scene);
			stage.setWidth(800);
			stage.setHeight(600);
			stage.show();
		});
//		final String mesh = "<IndexedTriangleSet  index='0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35'><Coordinate point='440474 99212 136120 440474 119212 136120 460474 99212 136120 460474 99212 136120 440474 119212 136120 460474 119212 136120 440474 99212 136120 460474 99212 136120 460474 99212 156120 440474 99212 136120 460474 99212 156120 440474 99212 156120 440474 119212 136120 440474 119212 156120 460474 119212 156120 440474 119212 136120 460474 119212 156120 460474 119212 136120 440474 99212 156120 460474 119212 156120 440474 119212 156120 440474 99212 156120 460474 99212 156120 460474 119212 156120 440474 99212 136120 440474 119212 156120 440474 119212 136120 440474 99212 136120 440474 99212 156120 440474 119212 156120 460474 99212 136120 460474 119212 136120 460474 99212 156120 460474 119212 136120 460474 119212 156120 460474 99212 156120'/></IndexedTriangleSet>";
//		final Document doc = Jsoup.parse(mesh);
//		System.out.println(doc);
//		System.out.println(doc.select("IndexedTriangleSet").attr("index"));
	}
 
Example #22
Source File: ObjLoader.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
		PlatformImpl.startup(() -> {});
		// https://people.sc.fsu.edu/~jburkardt/data/obj/obj.html
//		final String objFile = "al.obj";
//		final String objFile = "diamond.obj";
		final String objFile = "alfa147.obj";
		final Path path = Paths.get(System.getProperty("user.home"), "Downloads", objFile);
		final TriangleMesh mesh = new ObjLoader().loadMesh(path);
		final double[] min = {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY};
		final double[] max = {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY};
		for (int i = 0; i < mesh.getPoints().size(); i += 3) {
			for (int d = 0; d < 3; ++d) {
				min[d] = Math.min(min[d], mesh.getPoints().get(i + d));
				max[d] = Math.max(max[d], mesh.getPoints().get(i + d));
			}
		}
		final Interval interval = Intervals.smallestContainingInterval(new FinalRealInterval(min, max));
		final MeshView mv = new MeshView(mesh);
		mv.setMaterial(Meshes.painteraPhongMaterial(Color.WHITE));
		mv.setDrawMode(DrawMode.FILL);
		mv.setCullFace(CullFace.BACK);
		final Viewer3DFX viewer = new Viewer3DFX(800, 600);
		viewer.meshesEnabledProperty().set(true);
		mv.setOpacity(1.0);
		viewer.setInitialTransformToInterval(interval);
		final MeshView mv2 = new MeshView(mesh);
		mv.setMaterial(Meshes.painteraPhongMaterial());
		mv.setDrawMode(DrawMode.FILL);
		mv.setCullFace(CullFace.BACK);
		mv2.setTranslateX(100);
		viewer.meshesGroup().getChildren().addAll(mv, mv2);
//		final double factor = 1;
//		final double w = 1*factor, h = 2*factor, d = 3*factor;
//		final Box box = new Box(w, h, d);
//		box.setCullFace(CullFace.NONE);
//		box.setOpacity(1.0);
//		box.setMaterial(Meshes.painteraPhongMaterial(Color.RED));
//		viewer.meshesGroup().getChildren().add(box);
		Platform.setImplicitExit(true);
		Platform.runLater(() -> {
			final Scene scene = new Scene(viewer);
			final Stage stage = new Stage();
			stage.setScene(scene);
			stage.setWidth(800);
			stage.setHeight(600);
			stage.show();
		});
	}
 
Example #23
Source File: TexturedMesh.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
protected TriangleMesh createMesh(){
        TriangleMesh triangleMesh = new TriangleMesh();
        triangleMesh.getPoints().setAll(helper.updateVertices(listVertices));
        switch(textureType.get()){
            case NONE:
                triangleMesh.getTexCoords().setAll(textureCoords);
                triangleMesh.getFaces().setAll(helper.updateFacesWithTextures(listFaces,listTextures));
                break;
            case PATTERN: 
                if(areaMesh.getHeight()>0 && areaMesh.getWidth()>0){
                    triangleMesh.getTexCoords().setAll(
                        helper.updateTexCoordsWithPattern((int)rectMesh.getWidth(),
                                (int)rectMesh.getHeight(),patternScale.get(),
                                areaMesh.getHeight()/areaMesh.getWidth()));
                } else {
                    triangleMesh.getTexCoords().setAll(
                        helper.updateTexCoordsWithPattern((int)rectMesh.getWidth(),
                                (int)rectMesh.getHeight(),patternScale.get()));
                }
                triangleMesh.getFaces().setAll(helper.updateFacesWithTextures(listFaces,listTextures));
                break;
            case IMAGE: 
                triangleMesh.getTexCoords().setAll(textureCoords);
                if(listTextures.size()>0){
                    triangleMesh.getFaces().setAll(helper.updateFacesWithTextures(listFaces,listTextures));
                } else { 
                    triangleMesh.getFaces().setAll(helper.updateFacesWithVertices(listFaces));
                }
                break;
            case COLORED_VERTICES_1D:
                triangleMesh.getTexCoords().setAll(helper.getTexturePaletteArray());
                triangleMesh.getFaces().setAll(helper.updateFacesWithFunctionMap(listVertices, listFaces));
                break;
            case COLORED_VERTICES_3D:
                triangleMesh.getTexCoords().setAll(helper.getTexturePaletteArray());
                triangleMesh.getFaces().setAll(helper.updateFacesWithDensityMap(listVertices, listFaces));
                break;
            case COLORED_FACES:
                triangleMesh.getTexCoords().setAll(helper.getTexturePaletteArray());
                triangleMesh.getFaces().setAll(helper.updateFacesWithFaces(listFaces));
                break;
        }
        
        int[] faceSmoothingGroups = new int[listFaces.size()]; // 0 == hard edges
        Arrays.fill(faceSmoothingGroups, 1); // 1: soft edges, all the faces in same surface
        if(smoothingGroups!=null){
//            for(int i=0; i<smoothingGroups.length; i++){
//                System.out.println("i: "+smoothingGroups[i]);
//            }
            triangleMesh.getFaceSmoothingGroups().addAll(smoothingGroups);
        } else {
            triangleMesh.getFaceSmoothingGroups().addAll(faceSmoothingGroups);
        }
        
        System.out.println("nodes: "+listVertices.size()+", faces: "+listFaces.size());
//        System.out.println("area: "+helper.getMeshArea(listVertices, listFaces));
        
        return triangleMesh;
    }
 
Example #24
Source File: TorusMesh.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
private TriangleMesh createTorus(
        int radiusDivisions,
        int tubeDivisions,
        float radius,
        float tRadius,
        float tubeStartAngle,
        float xOffset,
        float yOffset,
        float zOffset) {

    int numVerts = tubeDivisions * radiusDivisions;
    int faceCount = numVerts * 2;
    float[] points = new float[numVerts * 3],
            texCoords = new float[numVerts * 2];
    int[] faces = new int[faceCount * 6];

    int pointIndex = 0, texIndex = 0, faceIndex = 0;
    float tubeFraction = 1.0f / tubeDivisions;
    float radiusFraction = 1.0f / radiusDivisions;
    float x, y, z;

    int p0 = 0, p1 = 0, p2 = 0, p3 = 0, t0 = 0, t1 = 0, t2 = 0, t3 = 0;

    // create points
    for (int tubeIndex = 0; tubeIndex < tubeDivisions; tubeIndex++) {

        float radian = tubeStartAngle + tubeFraction * tubeIndex * 2.0f * 3.141592653589793f;

        for (int radiusIndex = 0; radiusIndex < radiusDivisions; radiusIndex++) {

            float localRadian = radiusFraction * (radiusIndex) * 2.0f * 3.141592653589793f;

            points[pointIndex + 0] = x = (radius + tRadius * ((float) Math.cos(radian))) * ((float) Math.cos(localRadian) + xOffset);
            points[pointIndex + 1] = y = (radius + tRadius * ((float) Math.cos(radian))) * ((float) Math.sin(localRadian) + yOffset);
            points[pointIndex + 2] = z = (tRadius * (float) Math.sin(radian) * zOffset);

            pointIndex += 3;

            float r = radiusIndex < tubeDivisions ? tubeFraction * radiusIndex * 2.0F * 3.141592653589793f : 0.0f;
            texCoords[texIndex] = (0.5F + (float) (Math.sin(r) * 0.5D));
            texCoords[texIndex + 1] = ((float) (Math.cos(r) * 0.5D) + 0.5F);

            texIndex += 2;

        }

    }
    //create faces        
    for (int point = 0; point < (tubeDivisions); point++) {
        for (int crossSection = 0; crossSection < (radiusDivisions); crossSection++) {
            p0 = point * radiusDivisions + crossSection;
            p1 = p0 >= 0 ? p0 + 1 : p0 - (radiusDivisions);
            p1 = p1 % (radiusDivisions) != 0 ? p0 + 1 : p0 - (radiusDivisions - 1);
            p2 = (p0 + radiusDivisions) < ((tubeDivisions * radiusDivisions)) ? p0 + radiusDivisions : p0 - (tubeDivisions * radiusDivisions) + radiusDivisions;
            p3 = p2 < ((tubeDivisions * radiusDivisions) - 1) ? p2 + 1 : p2 - (tubeDivisions * radiusDivisions) + 1;
            p3 = p3 % (radiusDivisions) != 0 ? p2 + 1 : p2 - (radiusDivisions - 1);

            t0 = point * (radiusDivisions) + crossSection;
            t1 = t0 >= 0 ? t0 + 1 : t0 - (radiusDivisions);
            t1 = t1 % (radiusDivisions) != 0 ? t0 + 1 : t0 - (radiusDivisions - 1);
            t2 = (t0 + radiusDivisions) < ((tubeDivisions * radiusDivisions)) ? t0 + radiusDivisions : t0 - (tubeDivisions * radiusDivisions) + radiusDivisions;
            t3 = t2 < ((tubeDivisions * radiusDivisions) - 1) ? t2 + 1 : t2 - (tubeDivisions * radiusDivisions) + 1;
            t3 = t3 % (radiusDivisions) != 0 ? t2 + 1 : t2 - (radiusDivisions - 1);

            try {
                faces[faceIndex] = (p2);
                faces[faceIndex + 1] = (t3);
                faces[faceIndex + 2] = (p0);
                faces[faceIndex + 3] = (t2);
                faces[faceIndex + 4] = (p1);
                faces[faceIndex + 5] = (t0);

                faceIndex += 6;

                faces[faceIndex] = (p2);
                faces[faceIndex + 1] = (t3);
                faces[faceIndex + 2] = (p1);
                faces[faceIndex + 3] = (t0);
                faces[faceIndex + 4] = (p3);
                faces[faceIndex + 5] = (t1);
                faceIndex += 6;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    TriangleMesh localTriangleMesh = new TriangleMesh();
    localTriangleMesh.getPoints().setAll(points);
    localTriangleMesh.getTexCoords().setAll(texCoords);
    localTriangleMesh.getFaces().setAll(faces);

    return localTriangleMesh;
}
 
Example #25
Source File: CubeMesh.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
private TriangleMesh createCube(float size) {
    TriangleMesh m = new TriangleMesh();

    float hw = size / 2,
            hh = hw,
            hd = hh;

    //create points
    m.getPoints().addAll(
        hw, hh, hd,
        hw, hh, -hd,
        hw, -hh, hd,
        hw, -hh, -hd,
        -hw, hh, hd,
        -hw, hh, -hd,
        -hw, -hh, hd,
        -hw, -hh, -hd
    );
    float x0 = 0.0f, x1 = 1.0f / 4.0f, x2 = 2.0f / 4.0f, x3 =  3.0f / 4.0f, x4 = 1.0f;
    float y0 = 0.0f, y1 = 1.0f /3.0f, y2 = 2.0f / 3.0f, y3 = 1.0f;
    
    
    
    m.getTexCoords().addAll(
        (x1 + getImagePadding()), (y0 + getImagePadding()), //0,1                
        (x2 - getImagePadding()), (y0 + getImagePadding()), //2,3             
        (x0)                    , (y1 + getImagePadding()), //4,5
        (x1 + getImagePadding()), (y1 + getImagePadding()), //6,7           
        (x2 - getImagePadding()), (y1 + getImagePadding()), //8,9           
        (x3),                     (y1 + getImagePadding()), //10,11           
        (x4),                     (y1 + getImagePadding()),  //12,13           
        (x0),                     (y2 - getImagePadding()), //14,15           
        (x1 + getImagePadding()), (y2 - getImagePadding()), //16,17           
        (x2 - getImagePadding()), (y2 - getImagePadding()), //18,19           
        (x3),                     (y2 - getImagePadding()), //20,21           
        (x4),                     (y2 - getImagePadding()), //22,23           
        (x1 + getImagePadding()), (y3 - getImagePadding()), //24,25           
        (x2),                     (y3 - getImagePadding())  //26,27
        
    );
    
    
    m.getFaces().addAll(
        0, 10, 2, 5, 1, 9,
        2, 5, 3, 4, 1, 9,
        
        4, 7, 5, 8, 6, 2,
        6, 2, 5, 8, 7, 3,
        
        0, 13, 1, 9, 4, 12,
        4, 12, 1, 9, 5, 8,
        
        2, 1, 6, 0, 3, 4,
        3, 4, 6, 0, 7, 3,
        
        0, 10, 4, 11, 2, 5,
        2, 5, 4, 11, 6, 6,
        
        1, 9, 3, 4, 5, 8,
        5, 8, 3, 4, 7, 3
    );
    
    return m;
}
 
Example #26
Source File: Text3DMesh.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
private void createLetter(String letter) {
    
    Text3DHelper helper = new Text3DHelper(letter, font.get(), fontSize.get());
    List<Point3D> origin = helper.getOffset();
    
    final int ind=indSegments.get();
    helper.getLineSegment().stream().map(poly->poly.getPath()).forEach(path->letterPath=Shape.union(letterPath, path));
    helper.getLineSegment().stream().forEach(poly->{
        final List<Point3D> points=poly.getPoints();
        List<List<Point3D>> holes=null;
        if(poly.getHoles().size()>0){
            holes=poly.getHoles().stream().map(LineSegment::getPoints).collect(Collectors.toList());
        }
        List<Point3D> invert = IntStream.range(0,points.size())
                .mapToObj(i->points.get(points.size()-1-i))
                .distinct().collect(Collectors.toList());
        Bounds bounds = null;
        if(joinSegments.get()){
            bounds=letterPath.getBoundsInParent();
        }
        TriangulatedMesh polyMesh = new TriangulatedMesh(invert,holes,level.get(),height.get(),0d,bounds);
        if(indSegments.get()>ind && joinSegments.get()){
            /*
            Combine new polyMesh with previous polyMesh into one single polyMesh
            */
            MeshHelper mh = new MeshHelper((TriangleMesh)meshes.get(meshes.size()-1).getMesh());
            MeshHelper mh1 = new MeshHelper((TriangleMesh)polyMesh.getMesh());
            mh1.addMesh(mh);
            polyMesh.updateMesh(mh1);
            meshes.set(meshes.size()-1,polyMesh);
        } else {
            meshes.add(polyMesh);
        }
        polyMesh.getTransforms().addAll(new Translate(offset.get(ind).x-origin.get(0).x+indLetters.get()*gap.doubleValue(),0,0));
        polyMesh.setCullFace(CullFace.BACK);
        polyMesh.setDrawMode(DrawMode.FILL);
        polyMesh.setDepthTest(DepthTest.ENABLE);
        polyMesh.setId(poly.getLetter());
        System.out.println("l "+poly.getLetter());
        indSegments.getAndIncrement();
    });
    indLetters.getAndIncrement();
}
 
Example #27
Source File: ObjImporter.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public TriangleMesh getMesh() {
    return meshes.values().iterator().next();
}
 
Example #28
Source File: ObjImporter.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public TriangleMesh getMesh(String key) {
    return meshes.get(key);
}
 
Example #29
Source File: SphereSegment.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param radius radius of the sphere segment
 * @param color The sphere segment color.
 * @param phimin The starting azimutal angle [rad], 0-2*pi.
 * @param phimax The ending azimutal angle [rad], 0-2*pi, phimax &gt;
 * phimin.
 * @param thetamin The starting polar angle [rad], -pi/2-pi/2.
 * @param thetamax The ending polar angle [rad], -pi/2-pi/2, thetamax &gt;
 * thetamin.
 * @param granularity The number of segments of curves approximations,
 * granulariy &gt; 2.
 * @param ambient Whether to have an ambient light or not
 * @param fill whether to show filled with the color param or as wire mesh
 */
public SphereSegment(double radius, Color color,
        double phimin, double phimax, double thetamin, double thetamax,
        int granularity, boolean ambient, boolean fill) {

    this.radius = radius;
    this.color = color;
    this.phimin = phimin;
    this.phimax = phimax;
    this.thetamin = thetamin;
    this.thetamax = thetamax;
    this.granularity = granularity;
    this.ambient = ambient;
    this.fill = fill;
    setDepthTest(DepthTest.ENABLE);

    mesh = new TriangleMesh();
    // Fill Points
    double phi = phimin;
    double theta;

    PhongMaterial maxPhong = new PhongMaterial();
    maxPhong.setSpecularColor(color);
    maxPhong.setDiffuseColor(color);

    for (int i = 0; i < granularity + 1; i++) {
        theta = thetamin;
        for (int j = 0; j < granularity + 1; j++) {
            Point3D p3D = new Point3D((float) (radius * Math.cos(theta) * Math.sin(phi)),
                    (float) (radius * Math.cos(theta) * Math.cos(phi)),
                    (float) (radius * Math.sin(theta)));
            mesh.getPoints().addAll(new Float(p3D.getX()), new Float(p3D.getY()), new Float(p3D.getZ()));
            theta += (thetamax - thetamin) / granularity;
        }
        phi += (phimax - phimin) / granularity;
    }

    //for now we'll just make an empty texCoordinate group
    mesh.getTexCoords().addAll(0, 0);
    //Add the faces "winding" the points generally counter clock wise
    for (int i = 0; i < granularity; i++) {
        int multiplier = (i * granularity) + i;
        //Up the Outside
        for (int j = multiplier; j < granularity + multiplier; j++) {
            mesh.getFaces().addAll(j, 0, j + 1, 0, j + granularity + 1, 0); //lower triangle
            mesh.getFaces().addAll(j + granularity + 1, 0, j + 1, 0, j + granularity + 2, 0); //upper triangle
        }
        //Down the Inside            
        for (int j = granularity + multiplier; j > multiplier; j--) {
            mesh.getFaces().addAll(j, 0, j - 1, 0, j + granularity + 1, 0); //lower triangle
            mesh.getFaces().addAll(j - 1, 0, j + granularity, 0, j + granularity + 1, 0); //upper triangle
        }
    }

    //Create a viewable MeshView to be added to the scene
    //To add a TriangleMesh to a 3D scene you need a MeshView container object
    meshView = new MeshView(mesh);
    //The MeshView allows you to control how the TriangleMesh is rendered
    if (fill) {
        meshView.setDrawMode(DrawMode.FILL);
    } else {
        meshView.setDrawMode(DrawMode.LINE); //show lines only by default
    }
    meshView.setCullFace(CullFace.BACK); //Removing culling to show back lines

    getChildren().add(meshView);
    meshView.setMaterial(maxPhong);
    if (ambient) {
        AmbientLight light = new AmbientLight(Color.WHITE);
        light.getScope().add(meshView);
        getChildren().add(light);
    }
}
 
Example #30
Source File: ScatterPlotMesh.java    From FXyzLib with GNU General Public License v3.0 4 votes vote down vote up
public void setXYZData(ArrayList<Double> xData, ArrayList<Double> yData, ArrayList<Double> zData) {
        xAxisData = xData;
        yAxisData = yData;
        zAxisData = zData;
        getChildren().clear();
        //for now we will always default to x axis
        //later we could maybe dynamically determine the smallest axis and then
        //uses 0's for the other axes that are larger.
        ArrayList<Point3D> point3DList = new ArrayList<>();

        for(int i=0;i<xAxisData.size();i++) {
            //some safety checks for array sizes
            double translateY = 0.0;
            double translateZ = 0.0;            
            if(!yAxisData.isEmpty() && yAxisData.size() > i)
                translateY = yAxisData.get(i);
            if(!zAxisData.isEmpty() && zAxisData.size() > i)
                translateZ = zAxisData.get(i);
            setTranslateX(xAxisData.get(i));
            //Convert to Floats and build list of adjusted points
            point3DList.add(new Point3D(new Float(xAxisData.get(i)), new Float(translateY), new Float(translateZ)));

            float width = 1;
            final TriangleMesh mesh = new TriangleMesh();
            //add each point. For each point add another point shifted on Z axis by width
            //This extra point allows us to build triangles later
            for(Point3D point: point3DList) {
                //Rear points
                //top right rear point
                mesh.getPoints().addAll(point.x+width,point.y+width,point.z+width);
                //top left rear point
                mesh.getPoints().addAll(point.x-width,point.y+width,point.z+width);
                //bottom right rear point
                mesh.getPoints().addAll(point.x+width,point.y-width,point.z+width);
                //bottom left rear point
                mesh.getPoints().addAll(point.x-width,point.y-width,point.z+width);
                //Front points
                //top right front point
                mesh.getPoints().addAll(point.x+width,point.y+width,point.z-width);
                //top left front point
                mesh.getPoints().addAll(point.x-width,point.y+width,point.z-width);
                //bottom right front point
                mesh.getPoints().addAll(point.x+width,point.y-width,point.z-width);
                //bottom left front point
                mesh.getPoints().addAll(point.x-width,point.y-width,point.z-width);
            }
            //add dummy Texture Coordinate
            mesh.getTexCoords().addAll(0,0);
            //Now generate nodes for each point
            for(int p=8;p<point3DList.size()*7;p+=8) {  //add each segment
                //Wind the next 8 vertices as a cube.  The cube itself will represent the data
                //Vertices wound counter-clockwise which is the default front face of any Triangle
                //Rear triangle faces should be wound clockwise to face away from center
                mesh.getFaces().addAll(p,0,p+3,0,p+2,0); //TRR,BLR,BRR
                mesh.getFaces().addAll(p+3,0,p,0,p+1,0); //BLR,TRR,TLR
                //left side faces
                mesh.getFaces().addAll(p+1,0,p+5,0,p+3,0); //TLR,TLF,BLR
                mesh.getFaces().addAll(p+5,0,p+7,0,p+3,0); //TLF,BLR,BLF
                //front side faces
                mesh.getFaces().addAll(p+5,0,p+7,0,p+4,0); //TLF,BLF,TLR
                mesh.getFaces().addAll(p+4,0,p+7,0,p+6,0); //TRF,BLF,BRF
                //front side faces
                mesh.getFaces().addAll(p+4,0,p+6,0,p+2,0); //TRF,BRF,BRR
                mesh.getFaces().addAll(p+4,0,p+2,0,p,0); //TRF,BRR,TRR
               
                //Top faces
                mesh.getFaces().addAll(p,0,p+1,0,p+3,0); //TRR,TLR,TRF
                mesh.getFaces().addAll(p+1,0,p+5,0,p+3,0); //TLR,TLF,TRF
               
                //bottom faces
                mesh.getFaces().addAll(p+3,0,p+7,0,p+6,0); //BLR,BLF,BRF
                mesh.getFaces().addAll(p+3,0,p+6,0,p+2,0); //BLR,BRF,BRR
            }
           
            //Need to add the mesh to a MeshView before adding to our 3D scene
            MeshView meshView = new MeshView(mesh);
            meshView.setDrawMode(DrawMode.FILL);  //Fill so that the line shows width
                              
            Color hsb = Color.hsb((new Double(i)  / 12) * 360, 1.0, 1.0, 0.5);
            PhongMaterial material = new PhongMaterial(hsb);
            material.setDiffuseColor(hsb);
            material.setSpecularColor(hsb);
            meshView.setMaterial(material);
            //Make sure you Cull the Back so that no black shows through
            meshView.setCullFace(CullFace.BACK);    
//            //Add some ambient light so folks can see it
//            Group line = new Group();
//            AmbientLight light = new AmbientLight(Color.WHITE);
//            light.getScope().add(meshView);
//            line.getChildren().add(light);
//            line.getChildren().add(meshView);           
            getChildren().addAll(meshView);           
        }
    }