Login  Register

Re: Need help understanding use of TextRenderer

Posted by Ryan McFall on Feb 13, 2021; 2:22pm
URL: https://forum.jogamp.org/Need-help-understanding-use-of-TextRenderer-tp4041009p4041017.html

Sure, I'm happy to post the code that I used in case someone stumbles across this question in the future!

First, some building block methods:

This one retrieves the current ModelView matrix - since there may have been calls to glTranslate, glRotate, etc. that position the property somewhere on the board, I need this matrix to help me compute where the property is in screen coordinates.

private static Matrix4d getModelViewMatrix (GL gl) {
  float[] modelViewMatrix = new float[16];
  gl.glGetFloatv(GLMatrixFunc.GL_MODELVIEW_MATRIX, modelViewMatrix, 0);
  Matrix4d mvMatrix = new Matrix4d();
  mvMatrix.set(modelViewMatrix);
  return mvMatrix;
}

Next is getScreenCoordinatesForPoint. It uses the model view matrix from above to transform the (x,y) coordinates in the property's coordinate system (with (0,0) in the center of the property) to the world coordinates where the property is being drawn. Then, it uses a utility method to map those world coordinates into screen coordinates.

private static Vector2i getScreenCoordinatesForPoint(GL gl, Matrix4d mvMatrix, double x, double y) {
  Vector4d point = new Vector4d(x, y, 1.0, 1.0).mul(mvMatrix);
  return GLUtilities.worldToViewport(gl, MonopolyWindow.world, point.x, point.y);
}

Finally, the method to render the text now that I know where it should go in the viewport:

private static void renderPropertyName(Property property, GLCanvas canvas, TextRenderer renderer, Matrix4d mvMatrix) {
        
  LinkedList lines = breakPropertyNameIntoLines(property.getName(), canvas, renderer, mvMatrix);
  final int lineSpacing = 6;
      
  GL2 gl = (GL2) canvas.getGL();
  Vector2i textLocation = getScreenCoordinatesForPoint(gl, mvMatrix, 0, PROPERTY_HEIGHT/2 - HEADER_HEIGHT);

  renderer.beginRendering(Utilities.getCanvasWidth(canvas), Utilities.getCanvasHeight(canvas));
  {
    for (String line : lines) {
      Rectangle2D bounds = renderer.getBounds(line);
      textLocation.y -= (lineSpacing + bounds.getHeight());
      renderer.draw(line, (int) (textLocation.x-bounds.getWidth()/2), textLocation.y);
    }
  }
  renderer.endRendering();
}

Hope that's helpful!