Worldwind Custom Renderable Picking Issue - java

I'm going through this tutorial
Whenever my mouse hovers over the cube created with this code (my version below), the Atmosphere and Stars disappear.
This is how it looks normally:
This is how it looks when I hover over the cube (Look at the atmosphere):
I'm not sure what is going on here.
/*
* Copyright (C) 2012 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwindx.examples.tutorial;
import gov.nasa.worldwind.Configuration;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.layers.RenderableLayer;
import gov.nasa.worldwind.pick.PickSupport;
import gov.nasa.worldwind.render.*;
import gov.nasa.worldwind.util.OGLUtil;
import gov.nasa.worldwindx.examples.ApplicationTemplate;
import javax.media.opengl.*;
import java.awt.*;
/**
* Example of a custom {#link Renderable} that draws a cube at a geographic position. This class shows the simplest
* possible example of a custom Renderable, while still following World Wind best practices. See
* http://goworldwind.org/developers-guide/how-to-build-a-custom-renderable/ for a complete description of this
* example.
*
* #author pabercrombie
* #version $Id: Cube.java 691 2012-07-12 19:17:17Z pabercrombie $
*/
public class Cube extends ApplicationTemplate implements Renderable
{
/** Geographic position of the cube. */
protected Position position;
/** Length of each face, in meters. */
protected double size;
/** Support object to help with pick resolution. */
protected PickSupport pickSupport = new PickSupport();
// Determined each frame
protected long frameTimestamp = -1L;
protected OrderedCube currentFramesOrderedCube;
/**
* This class holds the Cube's Cartesian coordinates. An instance of it is added to the scene controller's ordered
* renderable queue during picking and rendering.
*/
protected class OrderedCube implements OrderedRenderable
{
/** Cartesian position of the cube, computed from
* {#link gov.nasa.worldwindx.examples.tutorial.Cube#position}. */
protected Vec4 placePoint;
/** Distance from the eye point to the cube. */
protected double eyeDistance;
/**
* The cube's Cartesian bounding extent.
*/
protected Extent extent;
public double getDistanceFromEye()
{
return this.eyeDistance;
}
public void pick(DrawContext dc, Point pickPoint)
{
// Use same code for rendering and picking.
this.render(dc);
}
public void render(DrawContext dc)
{
Cube.this.drawOrderedRenderable(dc, Cube.this.pickSupport);
}
}
public Cube(Position position, double sizeInMeters)
{
this.position = position;
this.size = sizeInMeters;
}
public void render(DrawContext dc)
{
// Render is called twice, once for picking and once for rendering. In both cases an OrderedCube is added to
// the ordered renderable queue.
OrderedCube orderedCube = this.makeOrderedRenderable(dc);
if (orderedCube.extent != null)
{
if (!this.intersectsFrustum(dc, orderedCube))
return;
// If the shape is less that a pixel in size, don't render it.
if (dc.isSmall(orderedCube.extent, 1))
return;
}
// Add the cube to the ordered renderable queue. The SceneController sorts the ordered renderables by eye
// distance, and then renders them back to front.
dc.addOrderedRenderable(orderedCube);
}
/**
* Determines whether the cube intersects the view frustum.
*
* #param dc the current draw context.
*
* #return true if this cube intersects the frustum, otherwise false.
*/
protected boolean intersectsFrustum(DrawContext dc, OrderedCube orderedCube)
{
if (dc.isPickingMode())
return dc.getPickFrustums().intersectsAny(orderedCube.extent);
return dc.getView().getFrustumInModelCoordinates().intersects(orderedCube.extent);
}
/**
* Compute per-frame attributes, and add the ordered renderable to the ordered renderable list.
*
* #param dc Current draw context.
*/
protected OrderedCube makeOrderedRenderable(DrawContext dc)
{
// This method is called twice each frame: once during picking and once during rendering. We only need to
// compute the placePoint, eye distance and extent once per frame, so check the frame timestamp to see if
// this is a new frame. However, we can't use this optimization for 2D continuous globes because the
// Cartesian coordinates of the cube are different for each 2D globe drawn during the current frame.
if (dc.getFrameTimeStamp() != this.frameTimestamp || dc.isContinuous2DGlobe())
{
OrderedCube orderedCube = new OrderedCube();
// Convert the cube's geographic position to a position in Cartesian coordinates. If drawing to a 2D
// globe ignore the shape's altitude.
if (dc.is2DGlobe())
{
orderedCube.placePoint = dc.getGlobe().computePointFromPosition(this.position.getLatitude(),
this.position.getLongitude(), 0);
}
else
{
orderedCube.placePoint = dc.getGlobe().computePointFromPosition(this.position);
}
// Compute the distance from the eye to the cube's position.
orderedCube.eyeDistance = dc.getView().getEyePoint().distanceTo3(orderedCube.placePoint);
// Compute a sphere that encloses the cube. We'll use this sphere for intersection calculations to determine
// if the cube is actually visible.
orderedCube.extent = new Sphere(orderedCube.placePoint, Math.sqrt(3.0) * this.size / 2.0);
// Keep track of the timestamp we used to compute the ordered renderable.
this.frameTimestamp = dc.getFrameTimeStamp();
this.currentFramesOrderedCube = orderedCube;
return orderedCube;
}
else
{
return this.currentFramesOrderedCube;
}
}
/**
* Set up drawing state, and draw the cube. This method is called when the cube is rendered in ordered rendering
* mode.
*
* #param dc Current draw context.
*/
protected void drawOrderedRenderable(DrawContext dc, PickSupport pickCandidates)
{
this.beginDrawing(dc);
try
{
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
if (dc.isPickingMode())
{
Color pickColor = dc.getUniquePickColor();
pickCandidates.addPickableObject(pickColor.getRGB(), this, this.position);
gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue());
}
// Render a unit cube and apply a scaling factor to scale the cube to the appropriate size.
gl.glScaled(this.size, this.size, this.size);
this.drawUnitCube(dc);
}
finally
{
this.endDrawing(dc);
}
}
/**
* Setup drawing state in preparation for drawing the cube. State changed by this method must be restored in
* endDrawing.
*
* #param dc Active draw context.
*/
protected void beginDrawing(DrawContext dc)
{
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
int attrMask = GL2.GL_CURRENT_BIT | GL2.GL_COLOR_BUFFER_BIT;
gl.glPushAttrib(attrMask);
if (!dc.isPickingMode())
{
dc.beginStandardLighting();
gl.glEnable(GL.GL_BLEND);
OGLUtil.applyBlending(gl, false);
// Were applying a scale transform on the modelview matrix, so the normal vectors must be re-normalized
// before lighting is computed.
gl.glEnable(GL2.GL_NORMALIZE);
}
// Multiply the modelview matrix by a surface orientation matrix to set up a local coordinate system with the
// origin at the cube's center position, the Y axis pointing North, the X axis pointing East, and the Z axis
// normal to the globe.
gl.glMatrixMode(GL2.GL_MODELVIEW);
Matrix matrix = dc.getGlobe().computeSurfaceOrientationAtPosition(this.position);
matrix = dc.getView().getModelviewMatrix().multiply(matrix);
double[] matrixArray = new double[16];
matrix.toArray(matrixArray, 0, false);
gl.glLoadMatrixd(matrixArray, 0);
}
/**
* Restore drawing state changed in beginDrawing to the default.
*
* #param dc Active draw context.
*/
protected void endDrawing(DrawContext dc)
{
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
if (!dc.isPickingMode())
dc.endStandardLighting();
gl.glPopAttrib();
}
/**
* Draw a unit cube, using the active modelview matrix to orient the shape.
*
* #param dc Current draw context.
*/
protected void drawUnitCube(DrawContext dc)
{
// Vertices of a unit cube, centered on the origin.
float[][] v = {{-0.5f, 0.5f, -0.5f}, {-0.5f, 0.5f, 0.5f}, {0.5f, 0.5f, 0.5f}, {0.5f, 0.5f, -0.5f},
{-0.5f, -0.5f, 0.5f}, {0.5f, -0.5f, 0.5f}, {0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, -0.5f}};
// Array to group vertices into faces
int[][] faces = {{0, 1, 2, 3}, {2, 5, 6, 3}, {1, 4, 5, 2}, {0, 7, 4, 1}, {0, 7, 6, 3}, {4, 7, 6, 5}};
// Normal vectors for each face
float[][] n = {{0, 1, 0}, {1, 0, 0}, {0, 0, 1}, {-1, 0, 0}, {0, 0, -1}, {0, -1, 0}};
// Note: draw the cube in OpenGL immediate mode for simplicity. Real applications should use vertex arrays
// or vertex buffer objects to achieve better performance.
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
gl.glBegin(GL2.GL_QUADS);
try
{
for (int i = 0; i < faces.length; i++)
{
gl.glNormal3f(n[i][0], n[i][1], n[i][2]);
for (int j = 0; j < faces[0].length; j++)
{
gl.glVertex3f(v[faces[i][j]][0], v[faces[i][j]][1], v[faces[i][j]][2]);
}
}
}
finally
{
gl.glEnd();
}
}
protected static class AppFrame extends ApplicationTemplate.AppFrame
{
public AppFrame()
{
super(true, true, false);
RenderableLayer layer = new RenderableLayer();
Cube cube = new Cube(Position.fromDegrees(35.0, -120.0, 3000), 100000);
layer.addRenderable(cube);
getWwd().getModel().getLayers().add(layer);
}
}
public static void main(String[] args)
{
Configuration.setValue(AVKey.INITIAL_LATITUDE, 35.0);
Configuration.setValue(AVKey.INITIAL_LONGITUDE, -120.0);
Configuration.setValue(AVKey.INITIAL_ALTITUDE, 2550000);
Configuration.setValue(AVKey.INITIAL_PITCH, 45);
Configuration.setValue(AVKey.INITIAL_HEADING, 45);
ApplicationTemplate.start("World Wind Custom Renderable Tutorial", AppFrame.class);
}
}

I have reproduced the problem, both with the tutorial Cube class that is included in worldwind.jar and your Cube class that draws a helpfully larger cube.
I have traced the point at which the atmosphere disappears is when the hidden buffer for the GLCanvas is swapped within the WorldWind render code, so the problem is that for some reason the atmosphere and stars layers are not drawn on the hidden buffer during rendering in picking mode using your code.
I then found that the example with Cylinders included as gov.nasa.worldwindx.examples.Cylinders.class draws pickable 3D shapes (cylinders) on the globe and does not exhibit this problem (there are others - Boxes for example is extremely close to this tutorial).
I think that that the issue is with the implementation of OrderedRenderable in this tutorial example - in the Cylinders example, the actual Cylinder class extends RigidShape which in turn extends AbstractShape, which is the class that actually implements OrderedRenderable. It's definitely a bug. Maybe you can work from the Boxes example to get the functionality you need.

I ended up getting an answer on the worldwind forums: http://forum.worldwindcentral.com/showthread.php?46115-Worldwind-Custom-Renderable-Picking-Issue&p=125173
Add a gl push matrix call in the begin drawing method:
protected void beginDrawing(DrawContext dc)
{
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
int attrMask = GL2.GL_CURRENT_BIT | GL2.GL_COLOR_BUFFER_BIT;
gl.glPushAttrib(attrMask);
if (!dc.isPickingMode())
{
dc.beginStandardLighting();
gl.glEnable(GL.GL_BLEND);
OGLUtil.applyBlending(gl, false);
// Were applying a scale transform on the modelview matrix, so the normal vectors must be re-normalized
// before lighting is computed.
gl.glEnable(GL2.GL_NORMALIZE);
}
// Multiply the modelview matrix by a surface orientation matrix to set up a local coordinate system with the
// origin at the cube's center position, the Y axis pointing North, the X axis pointing East, and the Z axis
// normal to the globe.
gl.glPushMatrix();
gl.glMatrixMode(GL2.GL_MODELVIEW);
Matrix matrix = dc.getGlobe().computeSurfaceOrientationAtPosition(this.position);
matrix = dc.getView().getModelviewMatrix().multiply(matrix);
double[] matrixArray = new double[16];
matrix.toArray(matrixArray, 0, false);
gl.glLoadMatrixd(matrixArray, 0);
}
And additionally, add a gl pop matrix call in the end drawing:
protected void endDrawing(DrawContext dc)
{
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
if (!dc.isPickingMode())
dc.endStandardLighting();
gl.glPopMatrix();
gl.glPopAttrib();
}

move
if (!dc.isPickingMode())
dc.endStandardLighting();
from
protected void endDrawing(DrawContext dc)
after
gl.glLoadMatrixd(matrixArray, 0);
in
protected void beginDrawing(DrawContext dc)

Related

Libgdx TiledMap bug in render

I do a Mario like game with the libgdx library.
All works fine but sometime (especially when the camera goes fast) my TileMap has a little bug during the render.
A picture worth thousand word, so here it is : http://postimg.org/image/4tudtwewn/
I have tried to increment FPS, but there is no change. I have no idea where that is come from.
Here is my code :
public void show() {
TmxMapLoader loader = new TmxMapLoader();
this.plan = loader.load("maps/level-"+this.world+"-"+this.level+".tmx");
this.renderer = new OrthogonalTiledMapRenderer(this.plan);
...
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
this.renderer.render();// rendu de la carte
Batch batch = this.renderer.getSpriteBatch();
...
This happens when your Camera's position is not perfectly aligned with screen-space coordinates (pixels).
This results in some sprites being rounded to the next pixel while some other (that were connected to those) being rounded to the previous one, resulting in visible ugly glitches.
The easiest fix I could come up with is making sure that the Camera position is always perfectly aligned with screen-space coordinates.
public class TileMapCamera extends OrthographicCamera {
// Map tile size to round to
private int tileSize;
/**
* Create a pixel-perfect camera for a map with the specified tile size
* #param tileSize
*/
public TileMapCamera(int tileSize){
this.tileSize = tileSize;
}
#Override
public void update(){
// Round position to avoid glitches
float prevx = position.x;
float prevy = position.y;
position.x = (int)(position.x * tileSize) / (float)tileSize;
position.y = (int)(position.y * tileSize) / (float)tileSize;
super.update();
position.set(prevx, prevy, 0);
}
}
This works for a tile-based coordinate viewport:
mapViewport = new FitViewport(16, 15, new TileMapCamera(map.getProperties().get("tilewidth", Integer.class)));
If you're working with pixel-based coordinate viewports, you should round the camera position to the nearest integer instead.
I think its about the filtering.
This will help:
TiledMapRenderer Artifact
If the problem you are referring to, is the spacing you can fix when you import the tileset as it says Tenfour04
add or change pixel padding.

How to locate texture on sphere in jME3?

I would like to place JPEG texture map on sphere. It works for me, but I want to rotate texture by 180 degrees. I.e I want image to start not from zero UV coordinates, but earlier.
UPDATE
I have tried to reassign texture coordinates of a sphere. Texture coordinates are float, and I was hoping they are not constrained to the range of [0..1]. Otherwise it should placed my image into the region of [0..1 x 0..1].
It did something like latter, but not precise:
I.e. entire image was put into small region of a sphere. But, this exact region, where it is located, corresponds with negative values of U, i.e. at the same longitude, where image margin was in previous experiment (top sphere).
Why?
Image is here: https://en.wikipedia.org/wiki/File:Equirectangular_projection_SW.jpg
The code is follows:
package tests.com.jme3;
import java.nio.FloatBuffer;
import com.jme3.app.SimpleApplication;
import com.jme3.font.BitmapText;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.scene.shape.Sphere;
import com.jme3.util.BufferUtils;
public class Try_TextureTransform extends SimpleApplication {
public static void main(String[] args) {
Try_TextureTransform app = new Try_TextureTransform();
app.setShowSettings(false);
app.start(); // start the game
}
final float speed = 0.01f;
BitmapText hudText;
Sphere sphere1Mesh, sphere2Mesh;
Material sphere1Mat, sphere2Mat;
Geometry sphere1Geo, sphere2Geo;
Quaternion orientation;
DirectionalLight sun;
#Override
public void simpleInitApp() {
flyCam.setEnabled(false);
setDisplayStatView(false);
setDisplayFps(false);
hudText = new BitmapText(guiFont, false);
hudText.setSize(guiFont.getCharSet().getRenderedSize()); // font size
hudText.setColor(ColorRGBA.Blue); // font color
hudText.setText(""); // the text
hudText.setLocalTranslation(300, hudText.getLineHeight()*2, 0); // position
guiNode.attachChild(hudText);
sphere1Mesh = new Sphere(50, 50, 2);
sphere1Mesh.setTextureMode(Sphere.TextureMode.Projected); // matrc
sphere1Mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
sphere1Mat.setTexture("ColorMap", assetManager.loadTexture("textures/Equirectangular_projection_SW.jpg"));
sphere1Geo = new Geometry("Sphere2", sphere1Mesh);
sphere1Geo.setMaterial(sphere1Mat);
sphere1Geo.setLocalTranslation(0, 0, 2);
sphere2Mesh = new Sphere(50, 50, 2);
VertexBuffer vb = sphere2Mesh.getBuffer(Type.Position);
FloatBuffer fb = (FloatBuffer) vb.getData();
float[] vertexCoordinates = BufferUtils.getFloatArray(fb);
VertexBuffer vb2 = sphere2Mesh.getBuffer(Type.TexCoord);
FloatBuffer fb2 = (FloatBuffer) vb2.getData();
float[] uvCoordinates = BufferUtils.getFloatArray(fb2);
double rho;
for (int i = 0; i < vertexCoordinates.length/3; ++i) {
uvCoordinates[i*2] = (float) Math.atan2(vertexCoordinates[i*3+1], vertexCoordinates[i*3]);
rho = Math.sqrt(Math.pow( vertexCoordinates[i*3], 2) + Math.pow( vertexCoordinates[i*3+1], 2));
uvCoordinates[i*2+1] = (float) Math.atan2(vertexCoordinates[i*3+2], rho);
}
//apply new texture coordinates
VertexBuffer uvCoordsBuffer = new VertexBuffer(Type.TexCoord);
uvCoordsBuffer.setupData(Usage.Static, 2, com.jme3.scene.VertexBuffer.Format.Float, BufferUtils.createFloatBuffer(uvCoordinates));
sphere2Mesh.clearBuffer(Type.TexCoord);
sphere2Mesh.setBuffer(uvCoordsBuffer);
//sphere2Mesh.setTextureMode(Sphere.TextureMode.Projected); // better quality on spheres
sphere2Mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
sphere2Mat.setTexture("ColorMap", assetManager.loadTexture("textures/Equirectangular_projection_SW.jpg"));
sphere2Geo = new Geometry("Sphere2", sphere2Mesh);
sphere2Geo.setMaterial(sphere2Mat);
sphere2Geo.setLocalTranslation(0, 0, -2);
cam.setLocation(new Vector3f(-10, 0, 0));
cam.lookAt(Vector3f.ZERO, Vector3f.UNIT_Z);
rootNode.attachChild(sphere1Geo);
rootNode.attachChild(sphere2Geo);
}
#Override
public void simpleUpdate(float tpf) {
Vector2f cursorPosition = inputManager.getCursorPosition();
Vector3f cursorPositionWorld = cam.getWorldCoordinates(cursorPosition, 1);
orientation = new Quaternion().fromAngleAxis(cursorPositionWorld.z*speed, Vector3f.UNIT_Y);
orientation.multLocal(new Quaternion().fromAngleAxis(-cursorPositionWorld.y*speed, Vector3f.UNIT_Z));
rootNode.setLocalRotation(orientation);
}
}
The correct way to do this is just to rotate the geometry as you see fit or edit the texture (techniques 1 and 2) but because you talk about modifying the texture coordinates themselves I include techniques 3 and 4 in case you are using this example to learn a larger technique for when it is appropriate.
Technique 1 - Rotate the geometry
Rotate the geometry so that it is orientated the way you want it. This is by far the easiest, most appropriate and most understandable technique and what I recommend
//Add this
Quaternion quat=new Quaternion();
quat.fromAngles(0 ,0 , FastMath.PI);
sphere1Geo.setLocalRotation(quat);
Complete program
public class Main extends SimpleApplication {
public static void main(String[] args) {
Main app = new Main();
app.setShowSettings(false);
app.start(); // start the game
}
final float speed = 0.01f;
BitmapText hudText;
Quaternion orientation;
DirectionalLight sun;
#Override
public void simpleInitApp() {
flyCam.setEnabled(false);
setDisplayStatView(false);
setDisplayFps(false);
hudText = new BitmapText(guiFont, false);
hudText.setSize(guiFont.getCharSet().getRenderedSize()); // font size
hudText.setColor(ColorRGBA.Blue); // font color
hudText.setText(""); // the text
hudText.setLocalTranslation(300, hudText.getLineHeight()*2, 0); // position
guiNode.attachChild(hudText);
cam.setLocation(new Vector3f(10, 0, 0));
cam.lookAt(Vector3f.ZERO, Vector3f.UNIT_Z);
addOriginalSphere();
addRotatedSphere();
}
public void addOriginalSphere(){
Sphere sphere1Mesh = new Sphere(50, 50, 2);
sphere1Mesh.setTextureMode(Sphere.TextureMode.Projected); // matrc
Material sphere1Mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
sphere1Mat.setTexture("ColorMap", assetManager.loadTexture("Textures/world.png"));
Geometry sphere1Geo = new Geometry("Original Sphere", sphere1Mesh);
sphere1Geo.setMaterial(sphere1Mat);
sphere1Geo.setLocalTranslation(0, -2, 0);
rootNode.attachChild(sphere1Geo);
}
public void addRotatedSphere(){
Sphere sphere1Mesh = new Sphere(50, 50, 2);
sphere1Mesh.setTextureMode(Sphere.TextureMode.Projected); // matrc
Material sphere1Mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
sphere1Mat.setTexture("ColorMap", assetManager.loadTexture("Textures/world.png"));
Geometry sphere1Geo = new Geometry("Rotated Sphere", sphere1Mesh);
sphere1Geo.setMaterial(sphere1Mat);
sphere1Geo.setLocalTranslation(0, 2, 0);
//Add this
Quaternion quat=new Quaternion();
quat.fromAngles(0 ,0 , FastMath.PI);
sphere1Geo.setLocalRotation(quat);
rootNode.attachChild(sphere1Geo);
}
#Override
public void simpleUpdate(float tpf) {
}
}
Technique 2 - Edit the texture to conform to the way you want it to be
Many image editing programs exist, the one I use is Paint.Net and (like most editing software) gives exact pixel mouse coordinates. Just cut and paste the image such that greenwich is at the far left. In your case you need to edit the image anyway because it has that horrible white border on it.
Technique 3 - Mess with the vertex texture co-ordinates
This is overkill for this and is not what I recomend. But if this is an excercise to learn to create your own custom mesh then read on
public void addRotatedSphere_ByMessingWithMesh(){
Sphere sphere1Mesh = new Sphere(50, 50, 2);
sphere1Mesh.setTextureMode(Sphere.TextureMode.Projected); // matrc
FloatBuffer textureBuffer=sphere1Mesh.getFloatBuffer(Type.TexCoord);
float[] newTextureCoordinates=new float[textureBuffer.capacity()];
for(int i=0;i<newTextureCoordinates.length;i++){
//texture buffer goes x co-ordinate, y coordinate, x coordinate, y coordinate
if (i%2!=1){
newTextureCoordinates[i]=(float)((textureBuffer.get(i)+0.5)%1);
}else{
newTextureCoordinates[i]=textureBuffer.get(i);
}
}
sphere1Mesh.setBuffer(Type.TexCoord, 2,newTextureCoordinates);
Material sphere1Mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
sphere1Mat.setTexture("ColorMap", assetManager.loadTexture("Textures/world.png"));
Geometry sphere1Geo = new Geometry("Rotated Sphere", sphere1Mesh);
sphere1Geo.setMaterial(sphere1Mat);
sphere1Geo.setLocalTranslation(0, 2, 0);
rootNode.attachChild(sphere1Geo);
}
This has a problem because the seam at the back is not done properly; because the true texture coordinates go 0,0.2,0.4,0.8,1. Whereas out new ones do a wrap around on the far side. In this specific example you can do a manual handling of the seam but you can already see that this is a pain.
Technique 4 - Write your own shader
This is bordering on rediculus but you could write a custom shader that would take the true texture coordinates and apply a transformation similar to the one performed within Technique 3, but this would be done on the graphics card and is a nightmare to debug.
It goes without saying that that would be using a small nuclear weapon to kill a fly and I shall not explain all the step explicity (but its heavily based on unshaded.j3md and unshaded.vert
Create the following files to define our new material
Material definition
Only change is to mention our custom vertex shader rather than use the custom one
MaterialDef Unshaded {
MaterialParameters {
Texture2D ColorMap
Texture2D LightMap
Color Color (Color)
Boolean VertexColor (UseVertexColor)
Boolean SeparateTexCoord
// Texture of the glowing parts of the material
Texture2D GlowMap
// The glow color of the object
Color GlowColor
// For hardware skinning
Int NumberOfBones
Matrix4Array BoneMatrices
// Alpha threshold for fragment discarding
Float AlphaDiscardThreshold (AlphaTestFallOff)
//Shadows
Int FilterMode
Boolean HardwareShadows
Texture2D ShadowMap0
Texture2D ShadowMap1
Texture2D ShadowMap2
Texture2D ShadowMap3
//pointLights
Texture2D ShadowMap4
Texture2D ShadowMap5
Float ShadowIntensity
Vector4 Splits
Vector2 FadeInfo
Matrix4 LightViewProjectionMatrix0
Matrix4 LightViewProjectionMatrix1
Matrix4 LightViewProjectionMatrix2
Matrix4 LightViewProjectionMatrix3
//pointLight
Matrix4 LightViewProjectionMatrix4
Matrix4 LightViewProjectionMatrix5
Vector3 LightPos
Vector3 LightDir
Float PCFEdge
Float ShadowMapSize
}
Technique {
VertexShader GLSL100: MatDefs/TextureSplitting.vert
FragmentShader GLSL100: Common/MatDefs/Misc/Unshaded.frag
WorldParameters {
WorldViewProjectionMatrix
}
Defines {
SEPARATE_TEXCOORD : SeparateTexCoord
HAS_COLORMAP : ColorMap
HAS_LIGHTMAP : LightMap
HAS_VERTEXCOLOR : VertexColor
HAS_COLOR : Color
NUM_BONES : NumberOfBones
DISCARD_ALPHA : AlphaDiscardThreshold
}
}
Technique {
}
Technique PreNormalPass {
VertexShader GLSL100 : Common/MatDefs/SSAO/normal.vert
FragmentShader GLSL100 : Common/MatDefs/SSAO/normal.frag
WorldParameters {
WorldViewProjectionMatrix
WorldViewMatrix
NormalMatrix
}
Defines {
NUM_BONES : NumberOfBones
}
}
Technique PreShadow {
VertexShader GLSL100 : Common/MatDefs/Shadow/PreShadow.vert
FragmentShader GLSL100 : Common/MatDefs/Shadow/PreShadow.frag
WorldParameters {
WorldViewProjectionMatrix
WorldViewMatrix
}
Defines {
COLOR_MAP : ColorMap
DISCARD_ALPHA : AlphaDiscardThreshold
NUM_BONES : NumberOfBones
}
ForcedRenderState {
FaceCull Off
DepthTest On
DepthWrite On
PolyOffset 5 3
ColorWrite Off
}
}
Technique PostShadow15{
VertexShader GLSL150: Common/MatDefs/Shadow/PostShadow15.vert
FragmentShader GLSL150: Common/MatDefs/Shadow/PostShadow15.frag
WorldParameters {
WorldViewProjectionMatrix
WorldMatrix
}
Defines {
HARDWARE_SHADOWS : HardwareShadows
FILTER_MODE : FilterMode
PCFEDGE : PCFEdge
DISCARD_ALPHA : AlphaDiscardThreshold
COLOR_MAP : ColorMap
SHADOWMAP_SIZE : ShadowMapSize
FADE : FadeInfo
PSSM : Splits
POINTLIGHT : LightViewProjectionMatrix5
NUM_BONES : NumberOfBones
}
ForcedRenderState {
Blend Modulate
DepthWrite Off
PolyOffset -0.1 0
}
}
Technique PostShadow{
VertexShader GLSL100: Common/MatDefs/Shadow/PostShadow.vert
FragmentShader GLSL100: Common/MatDefs/Shadow/PostShadow.frag
WorldParameters {
WorldViewProjectionMatrix
WorldMatrix
}
Defines {
HARDWARE_SHADOWS : HardwareShadows
FILTER_MODE : FilterMode
PCFEDGE : PCFEdge
DISCARD_ALPHA : AlphaDiscardThreshold
COLOR_MAP : ColorMap
SHADOWMAP_SIZE : ShadowMapSize
FADE : FadeInfo
PSSM : Splits
POINTLIGHT : LightViewProjectionMatrix5
NUM_BONES : NumberOfBones
}
ForcedRenderState {
Blend Modulate
DepthWrite Off
PolyOffset -0.1 0
}
}
Technique Glow {
VertexShader GLSL100: Common/MatDefs/Misc/TextureSplitting.vert
FragmentShader GLSL100: Common/MatDefs/Light/Glow.frag
WorldParameters {
WorldViewProjectionMatrix
}
Defines {
NEED_TEXCOORD1
HAS_GLOWMAP : GlowMap
HAS_GLOWCOLOR : GlowColor
NUM_BONES : NumberOfBones
}
}
}
Vertex shader
Use a translation to map the true texture coordinates to the shifted coordinates. Incidently if you think this isn't java; it isn't. Its OpenGL Shader Langauge.
#import "Common/ShaderLib/Skinning.glsllib"
uniform mat4 g_WorldViewProjectionMatrix;
attribute vec3 inPosition;
#if defined(HAS_COLORMAP) || (defined(HAS_LIGHTMAP) && !defined(SEPARATE_TEXCOORD))
#define NEED_TEXCOORD1
#endif
attribute vec2 inTexCoord;
attribute vec2 inTexCoord2;
attribute vec4 inColor;
varying vec2 texCoord1;
varying vec2 texCoord2;
varying vec4 vertColor;
void main(){
#ifdef NEED_TEXCOORD1
texCoord1 = inTexCoord;
texCoord1.x=texCoord1.x+0.5;
if (texCoord1.x>1){
texCoord1.x=texCoord1.x-1;
}
#endif
#ifdef SEPARATE_TEXCOORD
texCoord2 = inTexCoord2;
#endif
#ifdef HAS_VERTEXCOLOR
vertColor = inColor;
#endif
vec4 modelSpacePos = vec4(inPosition, 1.0);
#ifdef NUM_BONES
Skinning_Compute(modelSpacePos);
#endif
gl_Position = g_WorldViewProjectionMatrix * modelSpacePos;
}
Then use this as a material instead of unshaded.j3md
Material sphere1Mat = new Material(assetManager, "Materials/TextureSplitting.j3md");
Again there is a nasty break around the back where the true texture roles over between 0 and 1 which we could handle explicitly if we wanted but we'd have to make sure there were 2 vertexs at the split point one with texture coordinate 0 and one with texture coordinate 1.
Conclusion
Techniques 1 or 2 are the ones you should use. I include techniques 3 and 4 simply to show that you can do this using the actual texture coordinates but that you shouldn't.

How to avoid camera flipping on quaternion rotation?

I have a camera that orbits around a fixed point using quaternions. The problem is that as the camera rotates around the x-axis and passes over a pole, that the camera will flip and produce a mirrored image. This makes sense because the camera is facing the opposite way but the up vector of the camera hasn't changed. Clearly, a new up vector needs to be calculated from the look vector and the right vector but I can't seem to get it to work. Note: this uses http://commons.apache.org/math/api-2.2/org/apache/commons/math/geometry/Rotation.html to represent quaternions.
Anyway, I'm using the following basic procedure to rotate the camera.
The rotation quaternion is initialised to the identity [1, 0, 0, 0]:
private Rotation total = Rotation.IDENTITY;
And the up vector of the camera is initialised as:
private Vector3D up = new Vector3D(0, 1, 0);
Rotation is done by storing the current rotation of the camera as a quaternion and then applying any subsequent rotations to this quaternion, the combined quaternion (total) is then used to rotate the position of the camera. The following code describes this procedure:
/**
* Rotates the camera by combining the current rotation (total) with any new axis/angle representation of a new rotation (newAxis, rotation).
*/
public void rotateCamera() {
if (rotation != 0) {
//Construct quaternion from the new rotation:
Rotation local = new Rotation(Math.cos(rotation/2), Math.sin(rotation/2) * newAxis.getX(), Math.sin(rotation/2) * newAxis.getY(), Math.sin(rotation/2) * newAxis.getZ(), true);
//Generate new camera rotation quaternion from current rotation quaternion and new rotation quaternion:
total = total.applyTo(local);
//Rotate the position of the camera using the camera rotation quaternion:
cam = rotateVector(local, cam);
//rotation is complete so set the next rotation to 0
rotation = 0;
}
}
/**
* Rotate a vector around a quaternion rotation.
*
* #param rotation The quaternion rotation.
* #param vector A vector to be rotated.
* #return The rotated vector.
*/
public Vector3D rotateVector(Rotation rotation, Vector3D vector) {
//set world centre to origin, i.e. (width/2, height/2, 0) to (0, 0, 0)
vector = new Vector3D(vector.getX() - width/2, vector.getY() - height/2, vector.getZ());
//rotate vector
vector = rotation.applyTo(vector);
//set vector in world coordinates, i.e. (0, 0, 0) to (width/2, height/2, 0)
return new Vector3D(vector.getX() + width/2, vector.getY() + height/2, vector.getZ());
}
The fields newAxis and rotation which store the axis/angle of any new rotation are generated by key presses as follows:
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
camera.setAxis(new Vector3D(1, 0, 0));
camera.setRotation(0.1);
}
if (e.getKeyCode() == KeyEvent.VK_A) {
camera.setAxis(new Vector3D(0, 1, 0));
camera.setRotation(0.1);
}
if (e.getKeyCode() == KeyEvent.VK_S) {
camera.setAxis(new Vector3D(1, 0, 0));
camera.setRotation(-0.1);
}
if (e.getKeyCode() == KeyEvent.VK_D) {
camera.setAxis(new Vector3D(0, 1, 0));
camera.setRotation(-0.1);
}
}
During each render loop the rotateCamera() method is called and then the following code sets the camera:
glu.gluLookAt(camera.getCam().getX(), camera.getCam().getY(), camera.getCam().getZ(), camera.getView().getX(), camera.getView().getY(), camera.getView().getZ(), 0, 1, 0);
You're doing something weird. A unit quaternion represents an entire orientation. You wouldn't normally use an 'up' vector with it. But... it looks like you'd get the effect you want by just using a constant 'up' vector [0,1,0] instead of getting it from the quaternion.
It really sounds like you don't need quaternions. What you want is a constant 'up' vector of [0,1,0]. Then you want an 'at' point that is always the point you're orbiting. Then you want an 'eye' point that can be rotated (with respect to your orbit point) around the y-axis or around the axis defined by the cross-product between your 'up' vector and the vector between your orbit point and the 'eye' point.

JOGL objects "Disappearing" when moving around a scene

I'm trying to implement a basic physics engine in Java and I'm using the JOGL bindings so I can visualize the results. I can create and rotate shapes easily enough, but have run into problems whilst manipulating the viewport and whilst moving the shapes.
I don't think a clipping issue - I've tried using the gluPerspective method with a massive range (0.0001f - 10000f) with no success. When I move the camera further away from my objects or move the objects themselves, they disappear.
Tutorials about JOGL are few and far between and many also use different versions of OpenGL, so I turn to the only friend I have left: the wonderful users of stack overflow. :)
Flattery aside, the code follows:
public class JoglEventListener implements GLEventListener, KeyListener, MouseListener, MouseMotionListener {
// keep pointer to associated canvas so we can refresh the screen (equivalent to glutPostRedisplay())
public GLCanvas canvas;
public Particle triforce;
public float x;
// constructor
public JoglEventListener(GLCanvas canvas) {
this.canvas = canvas;
}
#Override
public void display(GLAutoDrawable drawable) {
update();
render(drawable);
}
#Override
public void init(GLAutoDrawable drawable) {
triforce = new Particle();
x = 0;
}
private void update() {
triforce.integrate(0.0001);
x = x + 0.25f;
}
private void render(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
GLU glu = new GLU();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
//gl.glFrustum (.5f, -.5f, -.5f * 1080, .5f * 960, 1.f, 500.f);
glu.gluPerspective(0, 1, 0.1f, 100f);
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glHint(GL2.GL_CLIP_VOLUME_CLIPPING_HINT_EXT,GL2.GL_FASTEST);
glu.gluLookAt(0, 0, 1.5, 0, 0, -10, 0, 1, 0);
//gl.glRotatef(90, 0f , 1f , 0f );
//Draw some scale lines
gl.glBegin(GL.GL_LINES);
gl.glColor3f(0.75f, 0.75f, 0.75f);
for (int i = 0; i < 20; i += 1)
{
gl.glVertex3f(-5.0f, 0.0f, i + 0.5f);
gl.glVertex3f(5.0f, 0.0f, i + 0.5f);
}
gl.glEnd();
//gl.glRotatef(x, 1f , 1f , 1f );
gl.glPushMatrix();
gl.glTranslated(triforce.position.x, triforce.position.y, triforce.position.z);
gl.glBegin(GL.GL_TRIANGLE_STRIP);
gl.glColor3f(1f, 0f, 0f);
gl.glVertex3d(0, 0, -2);
gl.glColor3f(0f, 1f, 0f);
gl.glVertex3d(0, 0.25d, -2);
gl.glColor3f(0f, 0f, 1f);
gl.glVertex3d(0.25d, 0, -2);
gl.glColor3f(1f, 1f, 0f);
gl.glVertex3d(0.25d, 0.25d, -2.25d);
gl.glEnd();
gl.glPopMatrix();
gl.glFlush();
}
// (empty overridden methods omitted)
public Particle () {
setMass(200d);
velocity = new Vector3(0d, 30d, 40d);
acceleration = new Vector3(0d, -20d, 0d);
position = new Vector3(0d, 0d, 0d);
damping = 0.99d;
}
public void integrate (double duration) {
if (inverseMass <= 0.0d) {
return;
}
assert (duration > 0.0);
position.addScaledVector(velocity, duration);
Vector3 resultingAcc = new Vector3(acceleration.x, acceleration.y, acceleration.z);
velocity.addScaledVector(resultingAcc, duration);
velocity.multEquals(Math.pow(damping, duration));
//clearAccumulator();
}
public void setMass(double mass)
{
assert(mass != 0);
inverseMass = (1.0d)/mass;
}
Before movement / starting position:
The shape drifts upward and is obscured from the right and top, becoming invisible:
Any help would be greatly appreciated! Thanks!
The massive view range can be a problem. The coordinates of the objects are only so precise, and with a huge view range, things that should be near each other are determined to be at the same point. This can cause an object that should be in front of another to disappear behind it. Try using a smaller view range.
I had the same problem. Objects disappearing, while some stay in the scene. After removing:
gl.glEnable(GL2.GL_CULL_FACE);
everything was working just fine ! Of course this is JOGL code, in C, the command would be without all those objects. Just to make this answer clear for everyone.
In the render function, change the value of last parameter of gluPerspective from 100f to 1000f. It will solve your problem.
gl.gluPerspective(0, 1, 0.1f, 100f);
to
gl.gluPerspective(0, 1, 0.1f, 500f);
And I think in your code you have done a mistake in the above line writing glu.gluperspective
I think it is gl.gluPerspective.
In the end, I was never able to track down the issue, and started again from scratch. I didn't run into any further clipping issues on my new build.
My best guess as to my initial failure is an improperly used glHint or glClear call, or perhaps some problem with the version of JOGL I was referencing.

Matrix transformations in OpenGL

I'm building a 2D physics engine in Java using OpenGL (from LWJGL) to display the objects. The problem I am having is that the transformation matrices I apply to the frame seem to be getting applied in a different order to what it says that are.
/**
* Render the current frame
*/
private void render() {
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, Display.getDisplayMode().getWidth(), 0, Display
.getDisplayMode().getHeight(), -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);
GL11.glPushMatrix();
GL11.glTranslatef(Display.getDisplayMode().getWidth() / 2, Display
.getDisplayMode().getHeight() / 2, 0.0f);
renderFrameObjects();
GL11.glPopMatrix();
}
public void renderFrameObjects() {
Vector<ReactiveObject> objects = frame.getObjects();
for (int i = 0; i < objects.size(); i++) {
ReactiveObject currentObject = objects.get(i);
Mesh2D mesh = currentObject.getMesh();
GL11.glRotatef((float)(currentObject.getR() / Math.PI * 180), 0, 0, 1.0f);
GL11.glTranslated(currentObject.getX(), currentObject.getY(), 0);
GL11.glBegin(GL11.GL_POLYGON);
for (int j = 0; j < mesh.size(); j++) {
GL11.glVertex2d(mesh.get(j).x, mesh.get(j).y);
}
GL11.glEnd();
GL11.glTranslated(-currentObject.getX(), -currentObject.getY(), 0);
GL11.glRotatef((float)(-currentObject.getR() / Math.PI * 180), 0, 0, 1.0f);
}
}
In renderFrameObjects() I apply a rotation, a translation, draw the object (mesh coordinates are relative to the object's x, y), reverse the translation, and reverse the rotation. Yet the effect it gives when an object rotates (on collision) is similar to when one would apply a translation then a rotation (ie. rotates around a point at a radius). I can't seem to be able to figure this one out having tried various combinations of transformations.
Any help would be appreciated.
That is beacause they are applied to the local coordinate system of the object, not the object itself.
So the rotate rotates the coordinate system and the translation is applied within that rotated coordinate system.
BTW: Don't undo your matrix changes by applying negative transformations. Roundoff error's will accumulate and it probably is also less efficient then using glPushMatrix and glPopMatrix

Categories

Resources