下面列出了怎么用javafx.scene.shape.TriangleMesh的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
}
}
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;
}
@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;
}
}
@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);
}
}
/**
* 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();
}
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();
}
@Override
public void writeMesh(
final TriangleMesh mesh,
final Path path) throws IOException {
throw new UnsupportedOperationException("Not implemented yet!");
}
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());
}
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 ;
}
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];
}
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;
}
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();
}
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;
}
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;
}
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);
}
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());
}
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.");
}
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"));
}
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();
});
}
public TriangleMesh getMesh() {
return meshes.values().iterator().next();
}
public TriangleMesh getMesh(String key) {
return meshes.get(key);
}
private void addMesh(String key) {
if (facesStart >= faces.size()) {
// we're only interested in faces
smoothingGroupsStart = smoothingGroups.size();
return;
}
Map<Integer, Integer> vertexMap = new HashMap<>(vertexes.size() / 2);
Map<Integer, Integer> uvMap = new HashMap<>(uvs.size() / 2);
Map<Integer, Integer> normalMap = new HashMap<>(normals.size() / 2);
FloatArrayList newVertexes = new FloatArrayList(vertexes.size() / 2);
FloatArrayList newUVs = new FloatArrayList(uvs.size() / 2);
FloatArrayList newNormals = new FloatArrayList(normals.size() / 2);
boolean useNormals = true;
for (int i = facesStart; i < faces.size(); i += 2) {
int vi = faces.get(i);
Integer nvi = vertexMap.get(vi);
if (nvi == null) {
nvi = newVertexes.size() / 3;
vertexMap.put(vi, nvi);
newVertexes.add(vertexes.get(vi * 3));
newVertexes.add(vertexes.get(vi * 3 + 1));
newVertexes.add(vertexes.get(vi * 3 + 2));
}
faces.set(i, nvi);
int uvi = faces.get(i + 1);
Integer nuvi = uvMap.get(uvi);
if (nuvi == null) {
nuvi = newUVs.size() / 2;
uvMap.put(uvi, nuvi);
if (uvi >= 0) {
newUVs.add(uvs.get(uvi * 2));
newUVs.add(uvs.get(uvi * 2 + 1));
} else {
newUVs.add(0f);
newUVs.add(0f);
}
}
faces.set(i + 1, nuvi);
if (useNormals) {
int ni = faceNormals.get(i/2);
Integer nni = normalMap.get(ni);
if (nni == null) {
nni = newNormals.size() / 3;
normalMap.put(ni, nni);
if (ni >= 0 && normals.size() >= (ni+1)*3) {
newNormals.add(normals.get(ni * 3));
newNormals.add(normals.get(ni * 3 + 1));
newNormals.add(normals.get(ni * 3 + 2));
} else {
useNormals = false;
newNormals.add(0f);
newNormals.add(0f);
newNormals.add(0f);
}
}
faceNormals.set(i/2, nni);
}
}
TriangleMesh mesh = new TriangleMesh();
mesh.getPoints().setAll(newVertexes.toFloatArray());
mesh.getTexCoords().setAll(newUVs.toFloatArray());
mesh.getFaces().setAll(((IntegerArrayList) faces.subList(facesStart, faces.size())).toIntArray());
// Use normals if they are provided
if (useNormals) {
int[] newFaces = ((IntegerArrayList) faces.subList(facesStart, faces.size())).toIntArray();
int[] newFaceNormals = ((IntegerArrayList) faceNormals.subList(facesNormalStart, faceNormals.size())).toIntArray();
int[] smGroups = SmoothingGroups.calcSmoothGroups(mesh, newFaces, newFaceNormals, newNormals.toFloatArray());
mesh.getFaceSmoothingGroups().setAll(smGroups);
} else {
mesh.getFaceSmoothingGroups().setAll(((IntegerArrayList) smoothingGroups.subList(smoothingGroupsStart, smoothingGroups.size())).toIntArray());
}
int keyIndex = 2;
String keyBase = key;
while (meshes.get(key) != null) {
key = keyBase + " (" + keyIndex++ + ")";
}
meshes.put(key, mesh);
materials.put(key, material);
log(
"Added mesh '" + key + "' of " + mesh.getPoints().size() / mesh.getPointElementSize() + " vertexes, "
+ mesh.getTexCoords().size() / mesh.getTexCoordElementSize() + " uvs, "
+ mesh.getFaces().size() / mesh.getFaceElementSize() + " faces, "
+ mesh.getFaceSmoothingGroups().size() + " smoothing groups.");
log("material diffuse color = " + ((PhongMaterial) material).getDiffuseColor());
log("material diffuse map = " + ((PhongMaterial) material).getDiffuseMap());
facesStart = faces.size();
facesNormalStart = faceNormals.size();
smoothingGroupsStart = smoothingGroups.size();
}
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.");
}
private TriangleMesh newEmptyMesh() {
return new TriangleMesh();
}
public void setHeightData(float[][] arrayY, int spacing, Color color, boolean ambient, boolean fill) {
material = new PhongMaterial();
material.setSpecularColor(color);
material.setDiffuseColor(color);
mesh = new TriangleMesh();
// Fill Points
for (int x = 0; x < arrayY.length; x++) {
for (int z = 0; z < arrayY[0].length; z++) {
mesh.getPoints().addAll(x * spacing, arrayY[x][z], z * spacing);
}
}
//for now we'll just make an empty texCoordinate group
mesh.getTexCoords().addAll(0, 0);
int total = arrayY.length * arrayY.length;
int nextRow = arrayY.length;
//Add the faces "winding" the points generally counter clock wise
for (int i = 0; i < total - nextRow -1; i++) {
//Top upper left triangle
mesh.getFaces().addAll(i,0,i+nextRow,0,i+1,0);
//Top lower right triangle
mesh.getFaces().addAll(i+nextRow,0,i+nextRow + 1,0,i+1,0);
//Bottom
}
//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(material);
if (ambient) {
selfLight.getScope().add(meshView);
if(!getChildren().contains(selfLight))
getChildren().add(selfLight);
}
else if(getChildren().contains(selfLight))
getChildren().remove(selfLight);
setDepthTest(DepthTest.ENABLE);
}
public PolyLine3D(List<Point3D> points, int width, Color color) {
this.points = points;
this.width = width;
this.color = color;
setDepthTest(DepthTest.ENABLE);
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: points) {
mesh.getPoints().addAll(point.x,point.y,point.z);
mesh.getPoints().addAll(point.x,point.y,point.z+width);
}
//add dummy Texture Coordinate
mesh.getTexCoords().addAll(0,0);
//Now generate trianglestrips for each line segment
for(int i=2;i<points.size()*2;i+=2) { //add each segment
//Vertices wound counter-clockwise which is the default front face of any Triange
//These triangles live on the frontside of the line facing the camera
mesh.getFaces().addAll(i,0,i-2,0,i+1,0); //add primary face
mesh.getFaces().addAll(i+1,0,i-2,0,i-1,0); //add secondary Width face
//Add the same faces but wind them clockwise so that the color looks correct when camera is rotated
//These triangles live on the backside of the line facing away from initial the camera
mesh.getFaces().addAll(i+1,0,i-2,0,i,0); //add primary face
mesh.getFaces().addAll(i-1,0,i-2,0,i+1,0); //add secondary Width face
}
//Need to add the mesh to a MeshView before adding to our 3D scene
meshView = new MeshView(mesh);
meshView.setDrawMode(DrawMode.FILL); //Fill so that the line shows width
material = new PhongMaterial(color);
material.setDiffuseColor(color);
material.setSpecularColor(color);
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
AmbientLight light = new AmbientLight(Color.WHITE);
light.getScope().add(meshView);
getChildren().add(light);
getChildren().add(meshView);
}
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);
}
}
/**
* @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 >
* phimin.
* @param thetamin The starting polar angle [rad], -pi/2-pi/2.
* @param thetamax The ending polar angle [rad], -pi/2-pi/2, thetamax >
* thetamin.
* @param granularity The number of segments of curves approximations,
* granulariy > 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);
}
}
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();
}
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;
}