Access struct directly of c++ from java code - javacpp

I am new to javacpp i know java have not much experience in c++. This might be one of very simple question but i am struggling with this. How to access any variable type value written in header of c++ into java code using javacpp. Let us consider example:
C++ Code example:
There is function written in C++ which return the frame of video below is the code for it and expects an Struct argument to be passed.
unsigned char *
Videodecode::getframe_data (void *ptr)
{
GstSample *sample;
GstBuffer *buffer;
GstMapInfo map;
GstCaps *caps;
GstStructure *str;
gint width, height;
gstData *dataa = (gstData *) ptr;
sample = gst_app_sink_pull_sample ((GstAppSink*)dataa->sink);
if (sample != NULL) {
buffer = gst_sample_get_buffer (sample);
gst_buffer_map (buffer, &map, GST_MAP_READ);
if (map.data != NULL) {
caps = gst_sample_get_caps (sample);
if (caps != NULL);
str = gst_caps_get_structure (caps, 0);
if (!gst_structure_get_int (str, "width", &width) ||
!gst_structure_get_int (str, "height", &height)) {
g_print ("No width/height available\n");
}
display_data = map.data;
//displayImg = Mat (Size (width, height ), CV_8UC3, map.data);
// cvtColor (displayImg, displayImg, COLOR_YUV2BGR_YUY2);
gst_buffer_unmap (buffer, &map);
gst_buffer_unref (buffer);
} else
gst_sample_unref (sample);
}
else {
//cout << "gstImageBuffer is NULL" << endl;
return NULL;
}
//return displayImg.data;
return display_data;
}
The structure which need to be passed as argument is below
typedef struct gstData_t
{
GstElement *pipeline;
GstElement *source;
GstElement *demux;
GstElement *parser;
GstElement *decoder;
GstElement *convert;
GstElement *capsfilter;
GstElement *sink;
GstElement *typefind;
} gstData;
Corresponding java code written to access it is below:
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.bytedeco.javacpp.FunctionPointer;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.Pointer;
import org.bytedeco.javacpp.annotation.Name;
import org.bytedeco.javacpp.annotation.NoOffset;
import org.bytedeco.javacpp.annotation.Platform;
import org.bytedeco.javacpp.annotation.Raw;
import org.bytedeco.javacpp.tools.Builder;
import org.bytedeco.javacpp.tools.ParserException;
#Platform(include = {"Videodecode.h",
},
includepath = {"/usr/include/gstreamer-1.0/","/usr/include/glib-2.0/","/usr/lib/x86_64-linux-gnu/glib-2.0/include/"},
//linkpath = {"/home/ign/git/JavaCppExample/src/main/resources/de/oltzen/javacppexample/"},
link = {"Videodecode"})
public class Videodecode {
NativeVideodecode nda;
static {
Class c = Videodecode.class;
Builder builder = null;
try {
builder = new Builder().classesOrPackages(c.getName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoClassDefFoundError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
File[] outputFiles = builder.build();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Loader.load(c);
// Loader.load();
}
public Videodecode() {
nda = new NativeVideodecode();
}
public Videodecode(String filename) {
nda = new NativeVideodecode(filename);
}
public boolean filePathCpp(String str){
return nda.filePathCpp(str);
}
public boolean settingValCpp(String str){
return nda.settingValCpp(str);
}
public boolean process_event (int event) {
return nda.process_event(event);
}
public java.nio.ByteBuffer test1122 (String buffer) {
return nda.test1122(buffer);
}
public java.nio.ByteBuffer test112233 (String buffer) {
return nda.test1122(buffer);
}
public java.nio.ByteBuffer getframe_data(java.nio.ByteBuffer buffer){
return nda.getframe_data(buffer);
}
public Pointer gstData(){
return nda.gstData();
}
#Name("Videodecode")
public static class NativeVideodecode extends Pointer {
static {
Loader.load();
}
public NativeVideodecode() {
allocate();
}
public NativeVideodecode(String filename) {
System.out.println("filename "+filename);
allocate(filename);
}
public NativeVideodecode(Pointer p) {
super(p);
}
private native void allocate(String filename);
private native void allocate();
private native boolean filePathCpp(String str);
private native boolean settingValCpp(String str);
private native boolean process_event(int event);
private native java.nio.ByteBuffer test1122(String buffer);
private native java.nio.ByteBuffer test112233(String buffer);
// private native boolean test1122(byte[] buffer);
private native java.nio.ByteBuffer getframe_data (java.nio.ByteBuffer buffer);
#NoOffset private native Pointer gstData();
}
}
Problems being faced by me :
How to access Struct from C++ and pass it as an argument using java.
How to access frame data which is unsigned char*.
Approach which i tried to perform this.
To access Struct, i tried using offsetof but not sure how to use it in javacpp.
To access frame data i tried using java.nio.ByteBuffer but seems its not working properly.
While trying to compile code using mvn clean install below error is getting triggered.
[INFO] --- javacpp:1.3:build (javacpp.compiler) # projecustom ---
[INFO] Detected platform "linux-x86_64"
[INFO] Building for platform "linux-x86_64"
[WARNING] Could not load platform properties for class com.proje.decoder.connectorJavaCpp
[WARNING] Could not load platform properties for class com.proje.decoder.test1234
[INFO] Generating /home/ign/eclipse-workspace/projecustom/target/classes/com/proje/decoder/jniVideodecode.cpp
[INFO] Compiling /home/ign/eclipse-workspace/projecustom/target/classes/com/proje/decoder/linux-x86_64/libjniVideodecode.so
[INFO] g++ -I/usr/include/gstreamer-1.0/ -I/usr/include/glib-2.0/ -I/usr/lib/x86_64-linux-gnu/glib-2.0/include/ -I/usr/lib/jvm/java-8-openjdk-amd64/include -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux /home/ign/eclipse-workspace/projecustom/target/classes/com/proje/decoder/jniVideodecode.cpp -march=x86-64 -m64 -O3 -s -Wl,-rpath,$ORIGIN/ -Wl,-z,noexecstack -Wl,-Bsymbolic -Wall -fPIC -shared -o libjniVideodecode.so -lVideodecode
/home/ign/eclipse-workspace/projecustom/target/classes/com/proje/decoder/jniVideodecode.cpp: In function ‘_jobject* Java_com_proje_decoder_Videodecode_00024NativeVideodecode_gstData(JNIEnv*, jobject)’:
/home/ign/eclipse-workspace/projecustom/target/classes/com/proje/decoder/jniVideodecode.cpp:1532:21: error: ‘class Videodecode’ has no member named ‘gstData’
rptr = ptr->gstData();
edit:
let me try to take one simple example :
C++ Code:
#include <stdio.h>
struct test
{
int a;
std::string b;
};
class Foo {
public:
int n;
int m=70;
test tst;
// tst.a=10;
// tst.b="hi";
Foo(int n) : n(n) { }
virtual ~Foo() { }
virtual void bar() {
printf("Callback in C++ (n == %d)\n", n);
}
};
void callback(Foo *foo) {
foo->bar();
}
is it possible to write modify java code below to access a and b variables of struct
package com.ign.examples;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
#Platform(include="Foo.h")
public class VirtualFoo1 {
static { Loader.load(); }
public static class Foo extends Pointer {
static { Loader.load(); }
public Foo(int n) { allocate(n); }
private native void allocate(int n);
#NoOffset public native int n(); public native Foo n(int n);
#Virtual public native void bar();
public native int m(); public native void m(int m);
// public native #Cast("int") int a(); public native Foo a(int a);
public native Pointer tst(); public native void tst(Pointer tst);
}
public static native void callback(Foo foo);
public static void main(String[] args) {
Foo foo = new Foo(13);
System.out.println(foo.m());
}
}

Related

Undefined Reference errors when using IL2CPP in Unity

after switching unity scripting to IL2CPP scripting my android build is gettting a lot of undefined reference errors. A lot of them reference to IOS ARKit related stuff. Can i use #if !UNITY_IOS statements to remove them from my android build ? and where can i put these #if statements ?
errors are realated to Bulk_Assembly-CSharp_8.cpp.. i tried putting #if statements in it for platform specific build but does not seem to make a difference
if !UNITY_IOS
public class ARFaceAnchor
{
private UnityARFaceAnchorData faceAnchorData;
private static Dictionary<string, float> blendshapesDictionary;
public ARFaceAnchor (UnityARFaceAnchorData ufad)
{
faceAnchorData = ufad;
if (blendshapesDictionary == null) {
blendshapesDictionary = new Dictionary<string, float> ();
}
}
public string identifierStr { get { return faceAnchorData.identifierStr; } }
public Matrix4x4 transform {
get {
Matrix4x4 matrix = new Matrix4x4 ();
matrix.SetColumn (0, faceAnchorData.transform.column0);
matrix.SetColumn (1, faceAnchorData.transform.column1);
matrix.SetColumn (2, faceAnchorData.transform.column2);
matrix.SetColumn (3, faceAnchorData.transform.column3);
return matrix;
}
}
public ARFaceGeometry faceGeometry { get { return new ARFaceGeometry (faceAnchorData.faceGeometry); } }
public Dictionary<string, float> blendShapes { get { return GetBlendShapesFromNative(faceAnchorData.blendShapes); } }
delegate void DictionaryVisitorHandler(IntPtr keyPtr, float value);
[DllImport("__Internal")]
private static extern void GetBlendShapesInfo(IntPtr ptrDic, DictionaryVisitorHandler handler);
Dictionary<string, float> GetBlendShapesFromNative(IntPtr blendShapesPtr)
{
blendshapesDictionary.Clear ();
GetBlendShapesInfo (blendShapesPtr, AddElementToManagedDictionary);
return blendshapesDictionary;
}
[MonoPInvokeCallback(typeof(DictionaryVisitorHandler))]
static void AddElementToManagedDictionary(IntPtr keyPtr, float value)
{
string key = Marshal.PtrToStringAuto(keyPtr);
blendshapesDictionary.Add(key, value);
}
}
endif
If you want to remove from Android build, use
#if !UNITY_ANDROID
// your code here
#endif
Will be more helpful if you can post your error message is pertaining to which line.
Thanks Darren,
i must have got it all wrong. so
if !UNITY_ANDROID means if NOT Android ?

AbstractStringBuilder.ensureCapacityInternal get NullPointerException in storm bolt

online system, the storm Bolt get NullPointerException,though I think I check it before line 61; It gets NullPointerException once in a while;
import ***.KeyUtils;
import ***.redis.PipelineHelper;
import ***.redis.PipelinedCacheClusterClient;
import **.redis.R2mClusterClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
/**
* RedisBolt batch operate
*/
public class RedisBolt implements IRichBolt {
static final long serialVersionUID = 737015318988609460L;
private static ApplicationContext applicationContext;
private static long logEmitNumber = 0;
private static StringBuffer totalCmds = new StringBuffer();
private Logger logger = LoggerFactory.getLogger(getClass());
private OutputCollector _collector;
private R2mClusterClient r2mClusterClient;
#Override
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
_collector = outputCollector;
if (applicationContext == null) {
applicationContext = new ClassPathXmlApplicationContext("spring/spring-config-redisbolt.xml");
}
if (r2mClusterClient == null) {
r2mClusterClient = (R2mClusterClient) applicationContext.getBean("r2mClusterClient");
}
}
#Override
public void execute(Tuple tuple) {
String log = tuple.getString(0);
String lastCommands = tuple.getString(1);
try {
//log count
if (StringUtils.isNotEmpty(log)) {
logEmitNumber++;
}
if (StringUtils.isNotEmpty(lastCommands)) {
if(totalCmds==null){
totalCmds = new StringBuffer();
}
totalCmds.append(lastCommands);//line 61
}
//日志数量控制
int numberLimit = 1;
String flow_log_limit = r2mClusterClient.get(KeyUtils.KEY_PIPELINE_LIMIT);
if (StringUtils.isNotEmpty(flow_log_limit)) {
try {
numberLimit = Integer.parseInt(flow_log_limit);
} catch (Exception e) {
numberLimit = 1;
logger.error("error", e);
}
}
if (logEmitNumber >= numberLimit) {
StringBuffer _totalCmds = new StringBuffer(totalCmds);
try {
//pipeline submit
PipelinedCacheClusterClient pip = r2mClusterClient.pipelined();
String[] commandArray = _totalCmds.toString().split(KeyUtils.REDIS_CMD_SPILT);
PipelineHelper.cmd(pip, commandArray);
pip.sync();
pip.close();
totalCmds = new StringBuffer();
} catch (Exception e) {
logger.error("error", e);
}
logEmitNumber = 0;
}
} catch (Exception e) {
logger.error(new StringBuffer("====RedisBolt error for log=[ ").append(log).append("] \n commands=[").append(lastCommands).append("]").toString(), e);
_collector.reportError(e);
_collector.fail(tuple);
}
_collector.ack(tuple);
}
#Override
public void cleanup() {
}
#Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
}
#Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
exception info:
java.lang.NullPointerException at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:113) at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:415) at java.lang.StringBuffer.append(StringBuffer.java:237) at com.jd.jr.dataeye.storm.bolt.RedisBolt.execute(RedisBolt.java:61) at org.apache.storm.daemon.executor$fn__5044$tuple_action_fn__5046.invoke(executor.clj:727) at org.apache.storm.daemon.executor$mk_task_receiver$fn__4965.invoke(executor.clj:459) at org.apache.storm.disruptor$clojure_handler$reify__4480.onEvent(disruptor.clj:40) at org.apache.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:472) at org.apache.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:451) at org.apache.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:73) at org.apache.storm.daemon.executor$fn__5044$fn__5057$fn__5110.invoke(executor.clj:846) at org.apache.storm.util$async_loop$fn__557.invoke(util.clj:484) at clojure.lang.AFn.run(AFn.java:22) at java.lang.Thread.run(Thread.java:745)
can anyone give me some advice to find the reason.
That is really odd thing to happen. Please read the code for two classes.
https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/lang/AbstractStringBuilder.java
https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/lang/StringBuffer.java
AbstractStringBuilder has constructor with no args which doesn't allocate the field 'value', which makes accessing the 'value' field being NPE. Any constructors in StringBuffer use that constructor. So maybe some odd thing happens in serialization/deserialization and unfortunately 'value' field in AbstractStringBuilder is being null.
Maybe initializing totalCmds in prepare() would be better, and also you need to consider synchronization (thread-safety) between bolts. prepare() can be called per bolt instance so fields are thread-safe, but class fields are not thread-safe.
I think I find the problem maybe;
the key point is
"StringBuffer _totalCmds = new StringBuffer(totalCmds);" and " totalCmds.append(lastCommands);//line 61"
when new a object, It takes serval steps:
(1) allocate memory and return reference
(2) initialize
if append after (1) and before (2) then the StringBuffer.java extends AbstractStringBuilder.java
/**
* The value is used for character storage.
*/
char[] value;
value is not initialized;so this will get null:
#Override
public synchronized void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > value.length) {
expandCapacity(minimumCapacity);
}
}
this blot has a another question, some data maybe lost under a multithreaded environment

MFC DLL: class object value is not persisting throughout the exported call

I have written MFC dll having 3 methods are exported. I have declared class object as global and initialized it in first method then second and third method use and process it.
Issue is that class obeject's value is not getting persisting throughout the file. when second or third method gets call from C# client application, class
object value is getting NULL.
Could anybody tell me why this is happening! I have tried this same scnaerio in another application but this issue is not reproduced.
Code:
Interface File:
#include "StdAfx.h"
#define DLLEXPORT __declspec(dllexport)
using namespace nsAnalyzer;
static CWindowsAnalyzer *pWindowsAnalyzer = NULL;
extern "C" DLLEXPORT void Init( const wchar_t *sCurrentUserDataDir,
const wchar_t *sMachineName,
const wchar_t *sMacId )
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
try
{
nsAnalyzer::CWindowsAnalyzer *pWindowsAnalyzer = new CWindowsAnalyzer( CString(sCurrentUserDataDir),
CString(sMachineName),
CString(sMacId) );
if(pWindowsAnalyzer)
{
pWindowsAnalyzer->Init();
}
}
catch(const std::exception& e)
{
cout<<"Error: Exception occured in Init: "<<e.what()<<endl;
}
}
extern "C" DLLEXPORT bool Analyze()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
bool bResult = false;
try
{
if(pWindowsAnalyzer->ConsolidateRawActivities())
{
cout<<"ConsolidateRawActivities succeed"<<endl;
bResult = true;
}
else
{
cout<<"ConsolidateRawActivities failed"<<endl;
bResult = false;
}
}
catch(const std::exception& e)
{
cout<<"Error: Exception occured in Analyze: "<<e.what()<<endl;
}
return bResult;
}
extern "C" DLLEXPORT void Dispose()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
try
{
// Disponse windows analyzer
if(pWindowsAnalyzer)
{
delete pWindowsAnalyzer;
}
// Dispose Logger
CLogger::DisposeInstance();
}
catch(const std::exception& e)
{
cout<<"Error: Exception occured in Dispose: "<<e.what()<<endl;
}
}

Why is my Udp.send using Akka.io always getting timeout?

Executing this code always results in timeout error and never sending UDP packet.
Why?
I need to write somthing more because stackoverflow won't let me to send the question... ;-), but I think the question is very simple and the code is all needed.
package controllers;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.dispatch.Recover;
import akka.io.Tcp;
import akka.io.Udp;
import akka.io.UdpMessage;
import akka.japi.Procedure;
import akka.util.ByteString;
import java.net.InetSocketAddress;
import static akka.pattern.Patterns.ask;
import play.libs.Akka;
import play.mvc.Result;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.mvc.*;
public class Application extends Controller {
static ActorRef myActor = Akka.system().actorOf(Props.create(Listener.class));
public static Result index() {
return async(
Akka.asPromise(
//Promise.wrap(
ask(
myActor,
UdpMessage.send(ByteString.fromString("esto es una prueba"), new InetSocketAddress("172.80.1.81", 21001)),
1000
)
// .recover(
// new Recover<Object>() {
// #Override
// public Object recover(Throwable t) throws Throwable {
// if( t instanceof AskTimeoutException ) {
// Logger.error("Got exception: ", t);
// return internalServerError("Timeout");
// }
// else {
// Logger.error("Got exception: ", t);
// return internalServerError("Got Exception: " + t.getMessage());
// }
// }
// })
).map(
new Function<Object,Result>() {
public Result apply(Object response) {
return ok(response.toString());
}
}
)
);
}
//http://doc.akka.io/docs/akka/2.2-M2/java/io.html
//https://gist.github.com/kafecho/5353393
//how to terminate actor on shutdown http://stackoverflow.com/questions/10875101/how-to-stop-an-akka-thread-on-shutdown
public static class Listener extends UntypedActor {
final ActorRef nextActor;
public Listener() {
this(null);
}
public Listener(ActorRef nextActor) {
this.nextActor = nextActor;
// request creation of a bound listen socket
final ActorRef mgr = Udp.get(getContext().system()).getManager();
mgr.tell(UdpMessage.bind(getSelf(), new InetSocketAddress("localhost",
31001)), getSelf());
}
#Override
public void onReceive(Object msg) {
if (msg instanceof Udp.Bound) {
final Udp.Bound b = (Udp.Bound) msg;
getContext().become(ready(getSender()));
} else
unhandled(msg);
}
private Procedure<Object> ready(final ActorRef socket) {
return new Procedure<Object>() {
#Override
public void apply(Object msg) throws Exception {
if (msg instanceof Udp.Received) {
final Udp.Received r = (Udp.Received) msg;
// echo server example: send back the data
socket.tell(UdpMessage.send(r.data(), r.sender()),
getSelf());
// or do some processing and forward it on
final Object processed = new Object();//TODO parse data etc., e.g. using PipelineStage
if(nextActor!=null){
nextActor.tell(processed, getSelf());
}
} else if (msg.equals(UdpMessage.unbind())) {
socket.tell(msg, getSelf());
} else if (msg instanceof Udp.Unbound) {
getContext().stop(getSelf());
} else if (msg instanceof Udp.Send){
socket.tell(msg, getSelf());
} else
unhandled(msg);
}
};
}
}
}

Problems with KeyListener and JOGL

I'm trying to bind a key to translate a GL_QUAD around the screen. I created a class, as I will attach below, that implements KeyListener, and within that I have a method that upon the keypress of 'd', adds 0.1 to the x coordinates of the quad vertices. Now, I have two questions relating to this.
Firstly, it doesn't seem to do anything. Upon the keypress, nothing happens to the object.
Is there a better way to achieve what I am trying to do? My end goal is to eventually end up with a sprite, that the camera is focused upon, that can move around a visually 2D game world.
Thanks for your time.
Code:
SpriteTest.java
package com.mangostudios.spritetest;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import com.jogamp.opengl.util.FPSAnimator;
public class SpriteTest
{
public static void main(String[] args) {
GLProfile glp = GLProfile.getDefault();
GLCapabilities caps = new GLCapabilities(glp);
GLCanvas canvas = new GLCanvas(caps);
Frame frame = new Frame("AWT Window Test");
frame.setSize(300, 300);
frame.add(canvas);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
canvas.addGLEventListener(new Renderer());
FPSAnimator animator = new FPSAnimator(canvas, 60);
//animator.add(canvas);
animator.start();
}
}
Renderer.java
package com.mangostudios.spritetest;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
public class Renderer implements GLEventListener {
InputListener input = new InputListener();
#Override
public void display(GLAutoDrawable drawable) {
update();
render(drawable);
}
#Override
public void dispose(GLAutoDrawable drawable) {
}
#Override
public void init(GLAutoDrawable drawable) {
}
#Override
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
}
private void update() {
}
private void render(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
// draw a triangle filling the window
gl.glBegin(GL2.GL_QUADS);
gl.glVertex2f( input.xTran, 0.1f);
gl.glVertex2f( input.xTran,-0.1f);
gl.glVertex2f( -input.xTran, -0.1f);
gl.glVertex2f( -input.xTran, 0.1f);
gl.glEnd();
}
}
InputListener.java
package com.mangostudios.spritetest;
import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;
public class InputListener implements KeyListener{
boolean loopBool = false;
float xTran = 0.1f;
float yTran = 0.1f;
#Override
public void keyPressed(KeyEvent d) {
loopBool = true;
while (loopBool = true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void keyReleased(KeyEvent d) {
}
}
At first, you never call addKeyListener(). Secondly, you shouldn't put an infinite loop into keyPressed(). Thirdly, you use a NEWT KeyListener whereas you use an AWT GLCanvas :s Rather use GLWindow with a NEWT KeyListener or use an AWT GLCanvas with an AWT KeyListener or use NewtCanvasAWT. Finally, before writing your own example, try mine on Wikipedia in order to understand why it works.