EzDevInfo.com

lwjgl

LWJGL 2.X - The Lightweight Java Game Library. LWJGL - Lightweight Java Game Library

How can I check if an object(s) are in front of the camera?

I have got some trees, which are greatly lagging the game, so I would like to check if the trees are in front of the camera or not. A swaggy picture

I have had some help from the Mathematics forum, and also had a look at This link to help me convert pitch/yaw to the directional vector needed.

But for some reason, whenever I move the camera to the left, the trees become visible, wheras whenever I move it to the right, they become unvisible (So if camera is pointing at +1 on the Z axis, it seems to be rendering the trees, but -1 on the Z axis and it seems to not render them). GIF of trees being dumb (See http://i.gyazo.com/cdd05dc3f5dbdc07577c6e41fab3a549 for a less-jumpy .mp4)

I am using the following code to check if an object is in front of the camera or not:

Ship you = shipsID.get(UID);
int dis = 300;
Vector3f X = new Vector3f(camera.x(), camera.y(), camera.z());
float x = (float) (Math.cos(Math.toRadians(camera.yaw()))*Math.cos(Math.toRadians(camera.pitch())));
float y = (float) (Math.sin(Math.toRadians(camera.yaw()))*Math.cos(Math.toRadians(camera.pitch())));
float z = (float) Math.sin(Math.toRadians(camera.pitch()));
Vector3f V = new Vector3f(x, y, z);

for (Tree tree : trees){
    Vector3f Y = new Vector3f(tree.location.x, tree.location.y, tree.location.z);
    Vector3f YMinusX = Y.negate(X);//new Vector3f(Y.x - X.x, Y.y - X.y, Y.z - X.z);
    float dot = Vector3f.dot(YMinusX, V);
    if (dot > 0){
        tree.render();
    }
}

Is anyone able to tell me what I have done wrong here? I can't work out if it's the math.. Or the code.. Or what?

Camera translation code:

 public void applyTranslations() {
    glPushAttrib(GL_TRANSFORM_BIT);
    glMatrixMode(GL_MODELVIEW);
    glRotatef(pitch, 1, 0, 0);
    glRotatef(yaw, 0, 1, 0);
    lastYaw = yaw;
    glRotatef(roll, 0, 0, 1);
    glTranslatef(-x, -y, -z);
    glPopAttrib();
}

UPDATE:

It appears to be where the camera is looking. For example, if I look to -Z, nothing happens, but if I look to +Z, they all render. The if (dot > 0) code appears to somehow being +Z rather than +TheCameraRotation.


Source: (StackOverflow)

Horrible performance loss when using Opengl FBO

I have successfully implemented a simple 2-d game using lwjgl (opengl) where objects fade away as they get further away from the player. This fading was initially implemented by computing distance to origin of each object from the player and using this to scale the objects alpha/opacity.

However when using larger objects, this approach appears a bit too rough. My solution was to implement alpha/opacity scaling for every pixel in the object. Not only would this look better, but it would also move computation time from CPU to GPU.

I figured I could implement it using an FBO and a temporary texture.
By drawing to the FBO and masking it with a precomputed distance map (a texture) using a special blend mode, I intended to achieve the effect. The algorithm is like so:

0) Initialize opengl and setup FBO
1) Render background to standard buffer
2) Switch to custom FBO and clear it
3) Render objects (to FBO)
4) Mask FBO using distance-texture
5) Switch to standard buffer
6) Render FBO temporary texture (to standard buffer)
7) Render hud elements

A bit of extra info:

  • The temporary texture has the same size as the window (and thus standard buffer)
  • Step 4 uses a special blend mode to achieve the desired effect:
    GL11.glBlendFunc( GL11.GL_ZERO, GL11.GL_SRC_ALPHA );
  • My temporary texture is created with min/mag filters: GL11.GL_NEAREST
  • The data is allocated using: org.lwjgl.BufferUtils.createByteBuffer(4 * width * height);
  • The texture is initialized using: GL11.glTexImage2D( GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, dataBuffer);
  • There are no GL errors in my code.

This does indeed achieve the desired results. However when I did a bit of performance testing I found that my FBO approach cripples performance. I tested by requesting 1000 successive renders and measuring the time. The results were as following:

In 512x512 resolution:

  • Normal: ~1.7s
  • FBO: ~2.5s
  • (FBO -step 6: ~1.7s)
  • (FBO -step 4: ~1.7s)

In 1680x1050 resolution:

  • Normal: ~1.7s
  • FBO: ~7s
  • (FBO -step 6: ~3.5s)
  • (FBO -step 4: ~6.0s)

As you can see, this scales really badly. To make it even worse, I'm intending to do a second pass of this type. The machine I tested on is supposed to be high end in terms of my target audience, so I can expect people to have far below 60 fps with this approach, which is hardly acceptable for a game this simple.

What can I do to salvage my performance?


Source: (StackOverflow)

Advertisements

Getting 'java.lang.UnsatisfiedLinkError': no lwjgl in java.library.path [duplicate]

This question already has an answer here:

This is different from this question because it does not deal with linking a jar to the natives, it deals with linking the file still within the IDE to the natives.

I have been trying to write a simple program using LWJGL. When I add the library to Eclipse (Kepler 4.3.1 on Windows 7 64bit) and write a program, it does not show red squigglies under the the things which use LWJGL. However, trying to run it gives me the following stacktrace:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at org.lwjgl.Sys$1.run(Sys.java:73)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
    at org.lwjgl.Sys.loadLibrary(Sys.java:95)
    at org.lwjgl.Sys.<clinit>(Sys.java:112)
    at org.lwjgl.opengl.Display.<clinit>(Display.java:135)
    at DisplayExample.start(DisplayExample.java:8)
    at DisplayExample.main(DisplayExample.java:23)

(Yes, that is the example they give first, but I wanted to run it to make sure everything was installled properly)

My question is, how do I fix this error? Note that, even when running in Eclipse, it still fails. If I run something else which does not use LWJGL it works, too. I just downloaded it from the internet - it only had one version, so I assume it was the correct one. From what I can see, none of the other question askers have the same error as me - but if you could point me to informative questions that would be helpful too.


Source: (StackOverflow)

GLSL #version gives syntax error (LWJGL on Mac)

Specifying the GLSL version gives a syntax error when using LWJGL. I haven't tried to reproduce this issue outside LWJGL. This is happening on multiple Macs running Lion.

I've gotten both vertex and fragment shaders to work without using #version. But I'm about to use the texture function, which seems to require a #version directive.

Here's the simplest failing example:

#version 120

void main() {
  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

Compiling this fragment shader and calling glGetShaderInfoLog gives this error:

ERROR: 0:1: '' : syntax error #version

Replacing 120 with anything else, such as 110, also gives an error. Curiously, though, if I use 130 or higher, it gives the same error plus a complaint about the version not beig supported. (i know my system doesn't have GLSL 1.3, but it's still weird that this error displays when the compiler is acting like it doesn't understand the version tag.)

I'm on a Mac with an ATI Radeon HD 4670. GL_VERSION is 2.1 ATI-7.12.9 and GL_SHADING_LANGUAGE_VERSION is 1.20.

Given that, I don't see any reason why GLSL 1.20 should be unavailable. And it's really weird to me that it's saying #version is a syntax error, as opposed to saying something about an unsupported GLSL version.


Source: (StackOverflow)

Libgdx not using Opengl ES 2.0

Preferably, I'd like to use OpenGL ES 2.0 for a new 3d game I started making. Anyway, I've been developing it on an Ubuntu PC (not top-of-the-line but decent) I bought in 2010.

Gdx.graphics.isGL20Available() returns false, and I'm quite sure my drivers support 3.3.0. Here is what I'm receiving from glxinfo:

name of display: :0.0
display: :0  screen: 0
direct rendering: Yes
server glx vendor string: NVIDIA Corporation
server glx version string: 1.4
server glx extensions:
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_SGIX_fbconfig, 
GLX_SGIX_pbuffer, GLX_SGI_video_sync, GLX_SGI_swap_control, 
GLX_EXT_swap_control, GLX_EXT_texture_from_pixmap, GLX_ARB_create_context, 
GLX_ARB_create_context_profile, GLX_EXT_create_context_es2_profile, 
GLX_ARB_create_context_robustness, GLX_ARB_multisample, 
GLX_NV_float_buffer, GLX_ARB_fbconfig_float, GLX_EXT_framebuffer_sRGB
client glx vendor string: NVIDIA Corporation
client glx version string: 1.4
client glx extensions:
GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_visual_info, 
GLX_EXT_visual_rating, GLX_EXT_import_context, GLX_SGI_video_sync, 
GLX_NV_swap_group, GLX_NV_video_out, GLX_SGIX_fbconfig, GLX_SGIX_pbuffer, 
GLX_SGI_swap_control, GLX_EXT_swap_control, GLX_ARB_create_context, 
GLX_ARB_create_context_profile, GLX_NV_float_buffer, 
GLX_ARB_fbconfig_float, GLX_EXT_fbconfig_packed_float, 
GLX_EXT_texture_from_pixmap, GLX_EXT_framebuffer_sRGB, 
GLX_NV_present_video, GLX_NV_copy_image, GLX_NV_multisample_coverage, 
GLX_NV_video_capture, GLX_EXT_create_context_es2_profile, 
GLX_ARB_create_context_robustness
GLX version: 1.4
GLX extensions:
GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_SGIX_fbconfig, 
GLX_SGIX_pbuffer, GLX_SGI_video_sync, GLX_SGI_swap_control, 
GLX_EXT_swap_control, GLX_EXT_texture_from_pixmap, GLX_ARB_create_context, 
GLX_ARB_create_context_profile, GLX_EXT_create_context_es2_profile, 
GLX_ARB_create_context_robustness, GLX_ARB_multisample, 
GLX_NV_float_buffer, GLX_ARB_fbconfig_float, GLX_EXT_framebuffer_sRGB, 
GLX_ARB_get_proc_address
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: GeForce GT 220/PCI/SSE2
OpenGL version string: 3.3.0 NVIDIA 260.19.06
OpenGL shading language version string: 3.30 NVIDIA via Cg compiler
OpenGL extensions:
GL_ARB_blend_func_extended, GL_ARB_color_buffer_float, 
GL_ARB_compatibility, GL_ARB_copy_buffer, GL_ARB_depth_buffer_float, 
GL_ARB_depth_clamp, GL_ARB_depth_texture, GL_ARB_draw_buffers, 
GL_ARB_draw_buffers_blend, GL_ARB_draw_elements_base_vertex, 
GL_ARB_draw_instanced, GL_ARB_ES2_compatibility, 
GL_ARB_explicit_attrib_location, GL_ARB_fragment_coord_conventions, 
GL_ARB_fragment_program, GL_ARB_fragment_program_shadow, 
GL_ARB_fragment_shader, GL_ARB_framebuffer_object, 
GL_ARB_framebuffer_sRGB, GL_ARB_geometry_shader4, 
GL_ARB_get_program_binary, GL_ARB_half_float_pixel, 
GL_ARB_half_float_vertex, GL_ARB_imaging, GL_ARB_instanced_arrays, 
GL_ARB_map_buffer_range, GL_ARB_multisample, GL_ARB_multitexture, 
GL_ARB_occlusion_query, GL_ARB_occlusion_query2, 
GL_ARB_pixel_buffer_object, GL_ARB_point_parameters, GL_ARB_point_sprite, 
GL_ARB_provoking_vertex, GL_ARB_robustness, GL_ARB_sample_shading, 
GL_ARB_sampler_objects, GL_ARB_seamless_cube_map, 
GL_ARB_separate_shader_objects, GL_ARB_shader_bit_encoding, 
GL_ARB_shader_objects, GL_ARB_shading_language_100, GL_ARB_shadow, 
GL_ARB_sync, GL_ARB_texture_border_clamp, GL_ARB_texture_buffer_object, 
GL_ARB_texture_compression, GL_ARB_texture_compression_rgtc, 
GL_ARB_texture_cube_map, GL_ARB_texture_cube_map_array, 
GL_ARB_texture_env_add, GL_ARB_texture_env_combine, 
GL_ARB_texture_env_crossbar, GL_ARB_texture_env_dot3, 
GL_ARB_texture_float, GL_ARB_texture_gather, 
GL_ARB_texture_mirrored_repeat, GL_ARB_texture_multisample, 
GL_ARB_texture_non_power_of_two, GL_ARB_texture_query_lod, 
GL_ARB_texture_rectangle, GL_ARB_texture_rg, GL_ARB_texture_rgb10_a2ui, 
GL_ARB_texture_swizzle, GL_ARB_timer_query, GL_ARB_transform_feedback2, 
GL_ARB_transpose_matrix, GL_ARB_uniform_buffer_object, 
GL_ARB_vertex_array_bgra, GL_ARB_vertex_array_object, 
GL_ARB_vertex_buffer_object, GL_ARB_vertex_program, GL_ARB_vertex_shader, 
GL_ARB_vertex_type_2_10_10_10_rev, GL_ARB_viewport_array, 
GL_ARB_window_pos, GL_ATI_draw_buffers, GL_ATI_texture_float, 
GL_ATI_texture_mirror_once, GL_S3_s3tc, GL_EXT_texture_env_add, 
GL_EXT_abgr, GL_EXT_bgra, GL_EXT_bindable_uniform, GL_EXT_blend_color, 
GL_EXT_blend_equation_separate, GL_EXT_blend_func_separate, 
GL_EXT_blend_minmax, GL_EXT_blend_subtract, GL_EXT_compiled_vertex_array, 
GL_EXT_Cg_shader, GL_EXT_depth_bounds_test, GL_EXT_direct_state_access, 
GL_EXT_draw_buffers2, GL_EXT_draw_instanced, GL_EXT_draw_range_elements, 
GL_EXT_fog_coord, GL_EXT_framebuffer_blit, GL_EXT_framebuffer_multisample, 
GL_EXTX_framebuffer_mixed_formats, GL_EXT_framebuffer_object, 
GL_EXT_framebuffer_sRGB, GL_EXT_geometry_shader4, 
GL_EXT_gpu_program_parameters, GL_EXT_gpu_shader4, 
GL_EXT_multi_draw_arrays, GL_EXT_packed_depth_stencil, 
GL_EXT_packed_float, GL_EXT_packed_pixels, GL_EXT_pixel_buffer_object, 
GL_EXT_point_parameters, GL_EXT_provoking_vertex, GL_EXT_rescale_normal, 
GL_EXT_secondary_color, GL_EXT_separate_shader_objects, 
GL_EXT_separate_specular_color, GL_EXT_shadow_funcs, 
GL_EXT_stencil_two_side, GL_EXT_stencil_wrap, GL_EXT_texture3D, 
GL_EXT_texture_array, GL_EXT_texture_buffer_object, 
GL_EXT_texture_compression_latc, GL_EXT_texture_compression_rgtc, 
GL_EXT_texture_compression_s3tc, GL_EXT_texture_cube_map, 
GL_EXT_texture_edge_clamp, GL_EXT_texture_env_combine, 
GL_EXT_texture_env_dot3, GL_EXT_texture_filter_anisotropic, 
GL_EXT_texture_integer, GL_EXT_texture_lod, GL_EXT_texture_lod_bias, 
GL_EXT_texture_mirror_clamp, GL_EXT_texture_object, 
GL_EXT_texture_shared_exponent, GL_EXT_texture_sRGB, 
GL_EXT_texture_swizzle, GL_EXT_timer_query, GL_EXT_transform_feedback2, 
GL_EXT_vertex_array, GL_EXT_vertex_array_bgra, GL_IBM_rasterpos_clip, 
GL_IBM_texture_mirrored_repeat, GL_KTX_buffer_region, GL_NV_blend_square, 
GL_NV_conditional_render, GL_NV_copy_depth_to_color, GL_NV_copy_image, 
GL_NV_depth_buffer_float, GL_NV_depth_clamp, GL_NV_explicit_multisample, 
GL_NV_fence, GL_NV_float_buffer, GL_NV_fog_distance, 
GL_NV_fragment_program, GL_NV_fragment_program_option, 
GL_NV_fragment_program2, GL_NV_framebuffer_multisample_coverage, 
GL_NV_geometry_shader4, GL_NV_gpu_program4, GL_NV_gpu_program4_1, 
GL_NV_half_float, GL_NV_light_max_exponent, GL_NV_multisample_coverage, 
GL_NV_multisample_filter_hint, GL_NV_occlusion_query, 
GL_NV_packed_depth_stencil, GL_NV_parameter_buffer_object, 
GL_NV_parameter_buffer_object2, GL_NV_pixel_data_range, 
GL_NV_point_sprite, GL_NV_primitive_restart, GL_NV_register_combiners, 
GL_NV_register_combiners2, GL_NV_shader_buffer_load, 
GL_NV_texgen_reflection, GL_NV_texture_barrier, 
GL_NV_texture_compression_vtc, GL_NV_texture_env_combine4, 
GL_NV_texture_expand_normal, GL_NV_texture_multisample, 
GL_NV_texture_rectangle, GL_NV_texture_shader, GL_NV_texture_shader2, 
GL_NV_texture_shader3, GL_NV_transform_feedback, 
GL_NV_transform_feedback2, GL_NV_vdpau_interop, GL_NV_vertex_array_range, 
GL_NV_vertex_array_range2, GL_NV_vertex_buffer_unified_memory, 
GL_NV_vertex_program, GL_NV_vertex_program1_1, GL_NV_vertex_program2, 
GL_NV_vertex_program2_option, GL_NV_vertex_program3, 
GL_NVX_conditional_render, GL_NVX_gpu_memory_info, 
GL_SGIS_generate_mipmap, GL_SGIS_texture_lod, GL_SGIX_depth_texture, 
GL_SGIX_shadow, GL_SUN_slice_accum

And a lot more that does not have to do with the version string and/or extensions. I have all the extensions needed for Opengl ES 2.0 and my driver is updated to 3.3.0 (OpenGL 3.0->2.0 ES approximately). Is it because my software rasterizer is old? If so, there are probably others in the same situation (I don't even think there are that many Windows installations which are updated past 1.1), and I'd like to support them too. What is the best possible solution?


Source: (StackOverflow)

Schrodinger's bug, BufferedWriter doesnt write into TXT unless manually checked

I am a rookie programmer-wanna-be and came across this problem I couldnt find the answer for.
I use Eclipse, and for the porgram I use slick and lwjgl-2.9.3
The following code is in a state, inside the public void update(...)

I have the problem with this part of the code:
(the file.txt exists and have no capitals in its name, giveToFile is a String) (no exceptions throwen)

try{
    BufferedWriter bw = new BufferedWriter(new FileWriter("src/file.txt"));
    bw.write(giveToFile);
    bw.close();
}catch(IOException e){
    e.printStackTrace();
}

( EDIT:

try{
    bw = new BufferedWriter(new FileWriter("src/file.txt"));
    bw.write(giveToFile);
    bw.flush();
}catch(IOException e){
    e.printStackTrace();
}finally {
    if (bw != null){
        try {
           bw.close();
       }catch (Throwable t){
           t.printStackTrace();
       }
   }
}  

produced the same bug)

I placed a System.out.print at the end of the try block, and it run normally, and run only once. I also used a g.drawString and the giveToFile always gives the intended String. I executed the following two experiments. (The program is a game-ish thing, you get a score at the end based on your performace and it places it into the highscores then rewrites the TXT file.) (I suggest to read TLDR before.)

Experiment 1 (file.txt : "0 0 0 0 0") (successful):

  1. I run the program and earn 15 points.
    - string loaded from the txt: "0 0 0 0 0"
    - giveToFile (string): "15 0 0 0 0"
  2. I doubleclick the TXT file inside Eclipse at the left side (package explorer), it opens in a new tab and I see inside the txt: "15 0 0 0 0", I close the tab
  3. I run the program again and earn 30 ponts.
    - string leaded from text: "15 0 0 0 0"
    - giveToFile (String): "30 15 0 0 0"
  4. I doubleclick the TXT file inside Eclipse at the left side (package explorer), it opens in a new tab and I see inside the txt: "30 15 0 0 0", I close the tab
  5. I run the program one last time and earn 0 points.
    - string loeaded from txt: "30 15 0 0 0"
    - giveToFile (string): "30 15 0 0 0"

Experiment 2 (file.txt : "0 0 0 0 0") (faliure):

  1. I run the program and earn 15 points.
    - string loaded from the txt: "0 0 0 0 0"
    - giveToFile (string): "15 0 0 0 0"
  2. I doubleclick the TXT file inside Eclipse at the left side (package explorer), it opens in a new tab and I see inside the txt: "15 0 0 0 0", I close the tab
  3. I run the program again and earn 30 ponts.
    - string leaded from text: "15 0 0 0 0"
    - giveToFile (String): "30 15 0 0 0"
  4. I dont doubleclick the TXT file, I dont open it in a new tab, and I dont check it.
  5. I run the program one last time and earn 0 points.
    - string loeaded from txt: "15 0 0 0 0"
    - giveToFile (string): "15 0 0 0 0"

TLRD: the program doesnt write into the TXT file unless I check it manually

there is a bug, and there isnt, depends on if I check the txt file, or not

sorry for the long question and sorry if it is something super simple, but I am a beginner and couldn't find any solution on the internet, thanks for the help in advance

EDIT:

I use this to close the program: (xpos and ypos are the mouse coordinates) (basically a primitive exit button)

if((xpos>= 200 && xpos <= 400) && (ypos>=100 && ypos <=200)){
    if(Mouse.isButtonDown(0)){
        System.exit(0);
    }
}  

I got this: (no expceptions)

Thu Apr 30 16:44:14 CEST 2015 INFO:Slick Build #237
Thu Apr 30 16:44:14 CEST 2015 INFO:LWJGL Version: 2.9.3
Thu Apr 30 16:44:14 CEST 2015 INFO:OriginalDisplayMode: 1366 x 768 x 32 @60Hz
Thu Apr 30 16:44:14 CEST 2015 INFO:TargetDisplayMode: 600 x 600 x 0 @0Hz
Thu Apr 30 16:44:15 CEST 2015 INFO:Starting display 600x600
Thu Apr 30 16:44:15 CEST 2015 INFO:Use Java PNG Loader = true
Thu Apr 30 16:44:15 CEST 2015 INFO:Controllers not available

This part reads the file, no other part does anythign with the file, and the reader works fine:

try{
    InputStream is = getClass().getResourceAsStream("/file.txt");
    Scanner fileIn = new Scanner(is);
    for(int i=0; i<SCOREMAX; i++){
        scoreInt[i] = fileIn.nextInt();
    }
    fileIn.close();
}catch (Exception e) {
    e.printStackTrace();
}  

it is inside the public void init and SCOREMAX's type is public static final int


Source: (StackOverflow)

Reliable sound API in Java for simple digital samples playback

Is there a good recipe to get decent, reliable digital sampled sound playback in Java?

My list of requests is pretty short:

  • Load digitized samples in memory (for example, from resouces bundled in jar) from something like .wav files
  • Play them in non-blocking manner
  • When I play several samples simultaneously and they intersect in time, they should get properly mixed

It would be nice to have the following, but in fact I can live without it:

  • Playing from .ogg or similar compressed format (without implementing a CPU-hungry decoder in Java, obviously)
  • Playing back the same sample again while it is still playing should not stop previous playback of a given sample, but second copy should start and get properly mixed with the first one

I've tried the infamous Java Sound API, but found out that it is utterly unreliable and seem to be unable to satisfy even my minimal wish list. The problems I get:

  • On Linux with ALSA dmix (OpenJDK 6), having any other application using audio while initializing Java Sound API just makes all the sound from Java app disappear without any errors / warnings.

  • On Linux (OpenJDK 6), listing MixerInfos and trying to get a Clip object using any of them throws the following exception when trying to load a wav file:

    java.lang.IllegalArgumentException: Line unsupported: interface Clip supporting format PCM_SIGNED unknown sample rate, 16 bit, stereo, 4 bytes/frame, big-endian
    

    Thus, AudioSystem.getClip(anySortOfMixer) doesn't seem to work at all. Only AudioSystem.getClip() works.

  • Loading files with different sample rate / bits / format using Clip fails with LineUnavailableException. It seems that first invocation of clip.open sets up sound system to a particular sound options, following invocations to load a file with slightly different sample rate (for example, first one was 44100, second one is 48000)

  • On Linux (OpenJDK 6) initializing several different Clips and trying to play them makes only last loaded Clip audible - no errors/warnings are given, but only using play on last Clip loaded makes any sound at all - all others are silent:

    Clip loadSound(String name) {
        URL url = this.getClass().getResource("/" + name + ".wav");
        Clip clip = AudioSystem.getClip();
        AudioInputStream ais = AudioSystem.getAudioInputStream(url);
        clip.open(ais);
        return clip;
    }
    
    void playSound(Clip) {
        if (clip.isRunning())
            clip.stop();
        clip.setFramePosition(0);
        clip.start();
    }
    ...
    Clip c1 = loadSound("foo");
    Clip c2 = loadSound("bar");
    ...
    playSound(c1); // silence
    ...
    playSound(c2); // audible
    

    Everything's fine with this code on Windows - all Clips are audible, play and mix properly. Haven't tested it on Mac.

  • Supported file formats (analyzed with AudioSystem.getAudioFileTypes) returns wav / au / aif on both Linux/OpenJDK6 and Windows/Oracle JDK 7, so no oggs or even mp3s :(

  • There seem to be no easy way to make two copies of the same Clip sound simultaneously without loading 2nd copy as a distinct Clip.

So, the question is - is there a good solution / workaround to remedy all this stuff and make it more reliable? Would switching to some other sound system (such as LWJGL OpenAL or paulscode.com sound system) help? Or is it possible to wrap Java Sound API in some safe-guards and it will work properly?

I've made a little application that tests all of the above, but it's a bit long, so I thought I'd publish it as a gist, but, unfortunately, GitHub is having some network issues right now. So, I guess, I will publish it a bit later.


Source: (StackOverflow)

When I run the .jar, I get a "No lwjgl in java.library.path" error

I'm making a basic game in Java using the LWJGL Library via Netbeans.

I've created a library with the lwjgl, lwjgl_util, and jinput .jar's, and I added -Djava.library.path=C:\LWJGL\native\windows to the "Run" category in the project's properties.

When I run the file in Netbeans, it runs perfectly with no issue. But when I run the .jar via double-clicking the file, nothing pops up (not even the momentary cmd error window, as far as I can tell). And when I run the file via command line, I get:

C:\Users\200160765>java -jar "C:\Users\200160765\Documents\NetBeansProjects\Game
\dist\Game.jar"
Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.libr
ary.path
        at java.lang.ClassLoader.loadLibrary(Unknown Source)
        at java.lang.Runtime.loadLibrary0(Unknown Source)
        at java.lang.System.loadLibrary(Unknown Source)
        at org.lwjgl.Sys$1.run(Sys.java:73)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
        at org.lwjgl.Sys.loadLibrary(Sys.java:82)
        at org.lwjgl.Sys.<clinit>(Sys.java:99)
        at org.lwjgl.opengl.Display.<clinit>(Display.java:130)
        at game.Draw.createWindow(Draw.java:198)
        at game.Draw.init(Draw.java:214)
        at game.Draw.run(Draw.java:56)
        at game.Main.main(Main.java:9)

I've tried moving the DLL's and .jar library files around to the 'lib' folder in the same directory as Game.jar, and moving them to the same directory as Game.jar, but I get the same error. Could someone help me as to why I can't seem to get this working outside of netbeans?


Source: (StackOverflow)

No OpenGL context found in the current thread, how do I fix this error?

I'm working on a card game, and currently have a good foundation but I'm running into an error when I run it in eclipse. I'm also using slick 2d.

Here is the error from the console.

Exception in thread "main" java.lang.RuntimeException: No OpenGL context found in the current thread. at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124) at org.lwjgl.opengl.GL11.glGetError(GL11.java:1277) at org.newdawn.slick.opengl.renderer.ImmediateModeOGLRenderer.glGetError(ImmediateModeOGLRenderer.java:387) at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:337) at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:275) at org.newdawn.slick.Image.(Image.java:270) at org.newdawn.slick.Image.(Image.java:244) at org.newdawn.slick.Image.(Image.java:232) at org.newdawn.slick.Image.(Image.java:198) at Cards.Card.(Card.java:18)

Code where I believe the source of the error to be occuring(Card class)

package Cards;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Card
{
    final int numCards = 52;
    Image[] card = new Image [numCards];
    Card (int c)
    {
        String fileLocation = new String ();
        for (int i = 1 ; i <= 52 ; i++)
        {
            fileLocation = "res/cards/" + i + ".png";
            try 
            {

                card [i] = new Image (fileLocation); //line
            }
            catch (SlickException e)
            {
                e.printStackTrace ();
            }
        }
    }
    public Image getImage (int cardlocation)
    {
        return card [cardlocation];
    }
}

Has anybody seem this kind of problem before? How can I solve it?


Source: (StackOverflow)

gluProject Converting 3D coordinates to 2D coordinates does not convert the 2D Y Coordinate correctly

After two hours of googling (here, here, here, here, and here, and a ton others which I am not bothered to find), I thought I had finally learnt the theory of turning 3D coordinates to 2D coordinates. But it isn't working. The idea is to translate the 3D coordinates of a ship to 2D coordinates on the screen to render the username of the player controlling that ship.

However, the text is rendering in the wrong location: enter image description here

The text is "Test || 2DXCoordinate || 2DZCoordinate".

Here is my getScreenCoords() - Which converts the 3D coordinates to 2D.

public static int[] getScreenCoords(double x, double y, double z) {
    FloatBuffer screenCoords = BufferUtils.createFloatBuffer(4);
    IntBuffer viewport = BufferUtils.createIntBuffer(16);
    FloatBuffer modelView = BufferUtils.createFloatBuffer(16);
    FloatBuffer projection = BufferUtils.createFloatBuffer(16);
    GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, modelView);
    GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projection);
    GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);
    boolean result = GLU.gluProject((float) x, (float) y, (float) z, modelView, projection, viewport, screenCoords);
    if (result) {
        return new int[] { (int) screenCoords.get(0), (int) screenCoords.get(1) };
    }
    return null;
}

screenCoords.get(0) is returning a perfect X coordinate. However, screenCoords.get(1) is going higher or lower depending on how far away I am from the ship. After many hours of debugging, I have narrowed it down to this line being incorrect:

GLU.gluProject((float) x, (float) y, (float) z, modelView, projection, viewport, screenCoords);

However, I have no idea what is wrong. The X coordinate of the ship is fine.... Why not the Y?

According to BDL's answer, I am supplying the "wrong matrix" to gluProject(). But I don't see how that is possible, since I call the method right after I render my ship (Which is obviously in whatever matrix draws the ship).

I just can't fathom what is wrong.

Note: BDL's answer is perfectly adequate except that it does not explain why the Y coordinates are incorrect.

Note: This question used to be much longer and much more vague. I have posted my narrowed-down question above after hours of debugging.


Source: (StackOverflow)

Why does NetBeans declare low memory when I run an LWJGL-based Java app several times?

Currently experimenting with OpenGL in Java. After running the following test code several cycles within NetBeans, I receive a low memory error and the program terminates. The issue occurs some time after having run the application through a few successful cycles.

Why does this happen and how can it be fixed?

Code:

package test3d;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.input.Keyboard;

class ColoredTriangle {
    public void start() {
        try {
            Display.setFullscreen(true);
            DisplayMode dm = new DisplayMode(34,34);
           // Display.setDisplayMode(new DisplayMode(DisplayMode.get));
            Display.create();
        } catch (LWJGLException e) {
            e.printStackTrace();
            System.exit(0);
        }

         // Init OpenGL
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(-3, 3, -2.4, 2.4, -1, 1);
        GL11.glRotatef(0.0f,5.0f,1.0f,0.0f); 
        //GL11.glOrtho(0, 640, 480, 0, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        boolean quit = false;

        while (!quit) {         
            // Clear the screen.
            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
            //GL11.glFrontFace(GL11.GL_CCW);
            // Begin drawing
            GL11.glBegin(GL11.GL_QUADS);
            GL11.glColor3f(1.0f,0.0f,0.0f); //Red   

     /*
                GL11.glVertex3f(0.0f,0.0f, 0.0f);

                GL11.glVertex3f(0.0f,1.0f, 0.0f);

                GL11.glVertex3f(1.0f,1.0f, 0.0f);

                GL11.glVertex3f(1.0f,0.0f, 0.0f); //*/


                 GL11.glVertex3f(1.0f,0.0f, -1f);

                GL11.glVertex3f(1.0f,1.0f, -1f);

                GL11.glVertex3f(2.0f,1.0f, -1f);

                GL11.glVertex3f(2.0f,0.0f, -1f);

              GL11.glEnd();  



            Display.update();

            if (Display.isCloseRequested() || Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
                quit = true;
        }

        Display.destroy();
        System.exit(0);
    }
}
class Test3d
{
    public static void main(String args[]) {
        ColoredTriangle ct = new ColoredTriangle();
        ct.start();
    }

}

Source: (StackOverflow)

Basic LWJGL triangle w/ OpenGL

I'm trying to get a simple triangle drawn in Java using LWJGL.

I'm trying to get a simple triangle up, each with a corner of one specific color. Right now it is just giving me a blank screen.

Here is my code:

package com.ex;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.input.Keyboard;

public class ColoredTriangle {
    public void start() {
        try {
            Display.setDisplayMode(new DisplayMode(640, 480));
            Display.create();
        } catch (LWJGLException e) {
            e.printStackTrace();
            System.exit(0);
        }

        // Init OpenGL
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(0, 640, 480, 0, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        boolean quit = false;

        while (!quit) {         
            // Clear the screen.
            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

            // Begin drawing
            GL11.glBegin(GL11.GL_TRIANGLES);
                // Top & Red
                GL11.glColor3f(1.0f, 0.0f, 0.0f);
                GL11.glVertex2f(0.0f, 1.0f);

                // Right & Green
                GL11.glColor3f(0.0f, 1.0f, 0.0f);
                GL11.glVertex2f(1.0f, 1.0f);

                // Left & Blue
                GL11.glColor3f(0.0f, 0.0f, 1.0f);
                GL11.glVertex2f(1.0f, -1.0f);
            GL11.glEnd();

            Display.update();

            if (Display.isCloseRequested() || Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
                quit = true;
        }

        Display.destroy();
    }

    public static void main(String args[]) {
        ColoredTriangle ct = new ColoredTriangle();
        ct.start();
    }

}

Source: (StackOverflow)

LWJGL - Problems implementing 'roll' in a 6DOF Camera using quaternions and a translation matrix

I've spent a couple weeks on this issue and can't seem to find a proper solution and need some advice.

I'm working on creating a Camera class using LWJGL/Java, and am using Quaternions to handle bearing (yaw), pitch and roll rotations. I'd like this camera to handle all 6 degrees of movement in 3D space, and roll. Bearing, Pitch and Roll are all quaternions. I multiply them into a 'change' quaternion, and create a translation matrix from that. I put that in a float buffer, and multiply the modelview matrix by my buffer containing the rotation matrix.

I can get the bearing and pitch rotations to work properly, but when I implement roll, I'm running into issues. Mainly, rotating around the Z-axis (rolling) doesn't seem to work. When ever I "roll" the camera, it seems to roll around the global Z axis instead of the local camera direction axis. I can usually get 2 of the 3 to work depending on the order I multiply the quaternions, but I can't get them working together.

Since they all work independently, I'm assuming there's something wrong with my orientation method where I combine them and build a rotation matrix. I'm having problems pasting the whole class in, so here are the methods and declarations relating to rotation:

private final static float DEGTORAD = (float)(Math.PI/180);    

//Eye - position of the camera in the 3D world.
private Vector3f eye;

//Camera axis vectors, calculated each time reorient() is called.
//Initialized to global x, y, and z axis initially.
private Vector3f up;
private Vector3f right;
private Vector3f direction;

//Angles of rotation (in degrees)    
private float pitchAngle;
private float bearingAngle;
private float rollAngle;

private Quaternion pitch;
private Quaternion bearing;
private Quaternion roll;

private FloatBuffer viewMatrixBuffer = BufferUtils.createFloatBuffer(16);
private Quaternion currentOrientation;

...

/**
 * Change the bearing (yaw)
 * @param bearing delta in degrees
 */
public void bearing(float bearingDelta){
    bearingAngle += bearingDelta;
    if(bearingAngle > 360){
        bearingAngle -= 360;
    }else if(bearingAngle < 0){
        bearingAngle += 360;
    }
    bearing.setFromAxisAngle(new Vector4f(0f, 1f, 0f, bearingAngle * DEGTORAD));
    bearing.normalise();
}

/**
 * Change the pitch
 * @param pitch delta in degrees
 */
public void pitch(float pitchDelta){
    pitchAngle += pitchDelta;
    if(pitchAngle > 360){
        pitchAngle -= 360;
    }else if(pitchAngle < 0){
        pitchAngle += 360;
    }
    pitch.setFromAxisAngle(new Vector4f(1f, 0f, 0f, pitchAngle * DEGTORAD));
    pitch.normalise();
}

/**
 * @param initialRoll
 */
public void roll(float initialRoll) {
    rollAngle += initialRoll;
    if(rollAngle > 360){
        rollAngle -= 360;
    }else if(rollAngle < 0){
        rollAngle += 360;
    }
    roll.setFromAxisAngle(new Vector4f(0, 0, 1, rollAngle * DEGTORAD));
    roll.normalise();
}

/**
 * Change direction to focus on a certain point in the world
 * @param eye
 */
public void lookThrough(){
    reorient();
    GL11.glMultMatrix(viewMatrixBuffer);
}    

public void reorient(){
    //Multiply in order: bearing, pitch, roll.  Non-commutative!
    Quaternion change = new Quaternion();
    Quaternion.mul(bearing, pitch, change);
    Quaternion.mul(roll, change, change);
    // orient the camera...
    Matrix4f rotationMatrix = getRotationMatrix(change);

    //Get the looking direction
    direction.x = rotationMatrix.m20;
    direction.y = rotationMatrix.m21;
    direction.z = rotationMatrix.m22;

    //Set the position
    rotationMatrix.m30 = eye.x;
    rotationMatrix.m31 = eye.y;
    rotationMatrix.m32 = eye.z;
    rotationMatrix.m33 = 1;

    rotationMatrix.invert();
    rotationMatrix.store(viewMatrixBuffer);

    viewMatrixBuffer.rewind();

    Vector3f.cross(new Vector3f(0,1,0), direction, null).normalise(right);
    Vector3f.cross(right, direction, null).normalise(up);               
}

Vector3f, Quaternion, and Matrix4f are all LWJGL classes, not custom made.

So my question is, given 3 Quaternions representing Bearing, Pitch and Roll, how do I modify the ModelView matrix to accurately represent these rotations?

EDIT: I feel that this is very close. See the Gist link in RiverC's comment. After rotating so many degrees, the view jumps around a lot before coming back to normal when rolling. The gist of it is there, but it's still slightly off.


Source: (StackOverflow)

Java bitmap font: blitting 1-bit image with different colors

I'd like to implement a simple bitmap font drawing in Java AWT-based application. Application draws on a Graphics object, where I'd like to implement a simple algorithm:

1) Load a file (probably using ImageIO.read(new File(fileName))), which is 1-bit PNG that looks something like that:

8*8 bitmap font

I.e. it's 16*16 (or 16*many, if I'd like to support Unicode) matrix of 8*8 characters. Black corresponds to background color, white corresponds to foreground.

2) Draw strings character-by-character, blitting relevant parts of this bitmap to target Graphics. So far I've only succeeded with something like that:

    int posX = ch % 16;
    int posY = ch / 16;

    int fontX = posX * CHAR_WIDTH;
    int fontY = posY * CHAR_HEIGHT;

    g.drawImage(
            font,
            dx, dy, dx + CHAR_WIDTH, dy + CHAR_HEIGHT,
            fontX, fontY, fontX + CHAR_WIDTH, fontY + CHAR_HEIGHT,
            null
    );

It works, but, alas, it blits the text as is, i.e. I can't substitute black and white with desired foreground and background colors, and I can't even make background transparent.

So, the question is: is there a simple (and fast!) way in Java to blit part of one 1-bit bitmap to another, colorizing it in process of blitting (i.e. replacing all 0 pixels with one given color and all 1 pixels with another)?

I've researched into a couple of solutions, all of them look suboptimal to me:

  • Using a custom colorizing BufferedImageOp, as outlined in this solution - it should work, but it seems that it would be very inefficient to recolorize a bitmap before every blit operation.
  • Using multiple 32-bit RGBA PNG, with alpha channel set to 0 for black pixels and to maximum for foreground. Every desired foreground color should get its own pre-rendered bitmap. This way I can make background transparent and draw it as a rectangle separately before blitting and then select one bitmap with my font, pre-colorized with desired color and draw a portion of it over that rectangle. Seems like a huge overkill to me - and what makes this option even worse - it limits number of foreground colors to a relatively small amount (i.e. I can realistically load up and hold like hundreds or thousands of bitmaps, not millions)
  • Bundling and loading a custom font, as outlined in this solution could work, but as far as I see in Font#createFont documentation, AWT's Font seems to work only with vector-based fonts, not with bitmap-based.

May be there's already any libraries that implement such functionality? Or it's time for me to switch to some sort of more advanced graphics library, something like lwjgl?

Benchmarking results

I've tested a couple of algorithms in a simple test: I have 2 strings, 71 characters each, and draw them continuously one after another, right on the same place:

    for (int i = 0; i < N; i++) {
        cv.putString(5, 5, STR, Color.RED, Color.BLUE);
        cv.putString(5, 5, STR2, Color.RED, Color.BLUE);
    }

Then I measure time taken and calculate speed: string per second and characters per second. So far, various implementation I've tested yield the following results:

  • bitmap font, 16*16 characters bitmap: 10991 strings / sec, 780391 chars / sec
  • bitmap font, pre-split images: 11048 strings / sec, 784443 chars / sec
  • g.drawString(): 8952 strings / sec, 635631 chars / sec
  • colored bitmap font, colorized using LookupOp and ByteLookupTable: 404 strings / sec, 28741 chars / sec

Source: (StackOverflow)

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I am trying to run the sample "Hello World" from the LWJGL website

From this link: LWJGL "Getting Started"

I'm trying to do this via the command line, just so I understand the "behind the scenes" a bit better.

I've managed to compile without any errors, but when I try to run the program I'm getting this error:

C:\JavaProjects\LearningLWJGL>java -classpath .;./lib/*.jar -Djava.library.path=C:\Windows\System32 HelloWorld
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/lwjgl/glfw/GLFWKeyCallback
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.privateGetMethodRecursive(Unknown Source)
    at java.lang.Class.getMethod0(Unknown Source)
    at java.lang.Class.getMethod(Unknown Source)
    at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.lwjgl.glfw.GLFWKeyCallback
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 7 more

Thanks for your time.


Source: (StackOverflow)