JavaFX TriangleMesh Creation Facade Library

As seen in a previous blog post, creating a JavaFX TriangleMesh object is a multi-step process that doesn't need to be, involves keeping track of indices, passing long arrays of integers, mixing two types of indices, the object is modifiable and the API is not particularly self-documenting, nor well documented.

All these problems can be easily sorted out with a small facade library to create TriangleMesh objects. The code that uses it looks like this:

 Vertex vertexA = Vertex.from(0f, 0f, 300f);  
 Vertex vertexB = Vertex.from(0f, 300f, 0f);  
 Vertex vertexC = Vertex.from(300f, 0f, 0f);  
   
 Point2D textureVertexA = new Point2D(0.571f, 0.27f);  
 Point2D textureVertexB = new Point2D(0.143f, 0.508f);  
 Point2D textureVertexC = new Point2D(0.429f, 0.508f);  
   
 Set<Vertex> vertices = new HashSet<>(Arrays.asList(vertexA, vertexB, vertexC));  
   
 Set<TriangleMeshFace> faces = new HashSet<>();  
 faces.add(makeFace(vertexA, vertexD, vertexC, textureVertexA, textureVertexC, textureVertexD));  
   
 TriangleMeshFacade mesh = TriangleMeshFacade.from(vertices, faces);  
   
   
   
private static TriangleMeshFace makeFace(Vertex firstVertex, Vertex secondVertex, Vertex thirdVertex,  
      Point2D firstTextureVertex, Point2D secondTextureVertex, Point2D thirdTextureVertex) {  
   
   List<Vertex> vertices = Arrays.asList(firstVertex, secondVertex, thirdVertex);  
   List<Point2D> textureVertices = Arrays.asList(firstTextureVertex, secondTextureVertex, thirdTextureVertex);  
   return TriangleMeshFace.fromOrdered(vertices, textureVertices);  
}  

  • We are wrapping what were integers before into classes (eg. Vertex or Point2D) to get rid of a whole class of errors at compile time.
  • The new functions' names and the choices of data structures are self-documenting. For example, lists are not used in the public interface unless there is an actual order to the elements in the collection, using sets instead.
  • The mesh object is created in a single step and, unlike the object it wraps, it's unmodifiable (partly because we are not exposing all of TriangleMesh's functions).
Of course this library doesn't solve the problem that mesh creation is essentially unreadable code in the sense that the result cannot be typically visualized and we pass lists of coordinates. But that doesn't mean that we should be happy with the sloppiest API that accomplishes this.

All in all, it should be less error-prone and a developer new to the code will understand what is going on more easily.

Comments