Add missing lwjgl.util subpackages

Closes #92
This commit is contained in:
Raven Szewczyk committed 2024-02-14 21:12:44 +00:00
1 parent e15dbe1209
commit fc73dc2cc2
22 files changed
+4367

No files matched your search

@@ -50,6 +50,16 @@ public class PointerBuffer extends org.lwjgl.PointerBuffer {
super(ver3.address(), getContainer(ver3), ver3.position(), ver3.position(), ver3.limit(), ver3.capacity());
}
public PointerBuffer(ByteBuffer buffer) {
this(
org.lwjgl.system.MemoryUtil.memAddress(buffer),
buffer,
0,
buffer.position(),
buffer.limit(),
buffer.capacity());
}
/**
* Allocates a new pointer buffer.
*
@@ -85,4 +95,8 @@ public class PointerBuffer extends org.lwjgl.PointerBuffer {
public static PointerBuffer create(ByteBuffer source) {
return new PointerBuffer(org.lwjgl.PointerBuffer.create(source));
}
public static int getPointerSize() {
return org.lwjgl.PointerBuffer.POINTER_SIZE;
}
}
@@ -0,0 +1,326 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.input;
import org.lwjgl.input.Controller;
/**
* Adapter for the Controller interface. It can be used as placeholder
* Controller, which doesn't do anything (eg if Controllers.create() fails and
* you don't want to take care of that).
*
* @author Onyx, Aho and all the other aliases...
*/
public class ControllerAdapter implements Controller {
/**
* Get the name assigned to this controller.
*
* @return The name assigned to this controller
*/
public String getName() {
return "Dummy Controller";
}
/**
* Get the index of this controller in the collection
*
* @return The index of this controller in the collection
*/
public int getIndex() {
return 0; // -1 maybe?
}
/**
* Retrieve the number of buttons available on this controller
*
* @return The number of butotns available on this controller
*/
public int getButtonCount() {
return 0;
}
/**
* Get the name of the specified button. Be warned, often this is as
* exciting as "Button X"
*
* @param index The index of the button whose name should be retrieved
* @return The name of the button requested
*/
public String getButtonName(int index) {
return "button n/a";
}
/**
* Check if a button is currently pressed
*
* @param index The button to check
* @return True if the button is currently pressed
*/
public boolean isButtonPressed(int index) {
return false;
}
/**
* Poll the controller for new data. This will also update events
*/
public void poll() {}
/**
* Get the X-Axis value of the POV on this controller
*
* @return The X-Axis value of the POV on this controller
*/
public float getPovX() {
return 0f;
}
/**
* Get the Y-Axis value of the POV on this controller
*
* @return The Y-Axis value of the POV on this controller
*/
public float getPovY() {
return 0f;
}
/**
* Get the dead zone for a specified axis
*
* @param index The index of the axis for which to retrieve the dead zone
* @return The dead zone for the specified axis
*/
public float getDeadZone(int index) {
return 0f;
}
/**
* Set the dead zone for the specified axis
*
* @param index The index of hte axis for which to set the dead zone
* @param zone The dead zone to use for the specified axis
*/
public void setDeadZone(int index, float zone) {}
/**
* Retrieve the number of axes available on this controller.
*
* @return The number of axes available on this controller.
*/
public int getAxisCount() {
return 0;
}
/**
* Get the name that's given to the specified axis
*
* @param index The index of the axis whose name should be retrieved
* @return The name of the specified axis.
*/
public String getAxisName(int index) {
return "axis n/a";
}
/**
* Retrieve the value thats currently available on a specified axis. The
* value will always be between 1.0 and -1.0 and will calibrate as values
* are passed read. It may be useful to get the player to wiggle the
* joystick from side to side to get the calibration right.
*
* @param index The index of axis to be read
* @return The value from the specified axis.
*/
public float getAxisValue(int index) {
return 0f;
}
/**
* Get the value from the X axis if there is one. If no X axis is defined a
* zero value will be returned.
*
* @return The value from the X axis
*/
public float getXAxisValue() {
return 0f;
}
/**
* Get the dead zone for the X axis.
*
* @return The dead zone for the X axis
*/
public float getXAxisDeadZone() {
return 0f;
}
/**
* Set the dead zone for the X axis
*
* @param zone The dead zone to use for the X axis
*/
public void setXAxisDeadZone(float zone) {}
/**
* Get the value from the Y axis if there is one. If no Y axis is defined a
* zero value will be returned.
*
* @return The value from the Y axis
*/
public float getYAxisValue() {
return 0f;
}
/**
* Get the dead zone for the Y axis.
*
* @return The dead zone for the Y axis
*/
public float getYAxisDeadZone() {
return 0f;
}
/**
* Set the dead zone for the Y axis
*
* @param zone The dead zone to use for the Y axis
*/
public void setYAxisDeadZone(float zone) {}
/**
* Get the value from the Z axis if there is one. If no Z axis is defined a
* zero value will be returned.
*
* @return The value from the Z axis
*/
public float getZAxisValue() {
return 0f;
}
/**
* Get the dead zone for the Z axis.
*
* @return The dead zone for the Z axis
*/
public float getZAxisDeadZone() {
return 0f;
}
/**
* Set the dead zone for the Z axis
*
* @param zone The dead zone to use for the Z axis
*/
public void setZAxisDeadZone(float zone) {}
/**
* Get the value from the RX axis if there is one. If no RX axis is defined
* a zero value will be returned.
*
* @return The value from the RX axis
*/
public float getRXAxisValue() {
return 0f;
}
/**
* Get the dead zone for the RX axis.
*
* @return The dead zone for the RX axis
*/
public float getRXAxisDeadZone() {
return 0f;
}
/**
* Set the dead zone for the RX axis
*
* @param zone The dead zone to use for the RX axis
*/
public void setRXAxisDeadZone(float zone) {}
/**
* Get the value from the RY axis if there is one. If no RY axis is defined
* a zero value will be returned.
*
* @return The value from the RY axis
*/
public float getRYAxisValue() {
return 0f;
}
/**
* Get the dead zone for the RY axis.
*
* @return The dead zone for the RY axis
*/
public float getRYAxisDeadZone() {
return 0f;
}
/**
* Set the dead zone for the RY axis
*
* @param zone The dead zone to use for the RY axis
*/
public void setRYAxisDeadZone(float zone) {}
/**
* Get the value from the RZ axis if there is one. If no RZ axis is defined
* a zero value will be returned.
*
* @return The value from the RZ axis
*/
public float getRZAxisValue() {
return 0f;
}
/**
* Get the dead zone for the RZ axis.
*
* @return The dead zone for the RZ axis
*/
public float getRZAxisDeadZone() {
return 0f;
}
/**
* Set the dead zone for the RZ axis
*
* @param zone The dead zone to use for the RZ axis
*/
public void setRZAxisDeadZone(float zone) {}
public int getRumblerCount() {
return 0;
}
public String getRumblerName(int index) {
return "rumber n/a";
}
public void setRumblerStrength(int index, float strength) {}
}
@@ -0,0 +1,290 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.jinput;
import net.java.games.input.Component;
import org.lwjgl.input.Keyboard;
/**
* @author elias
*/
final class KeyMap {
public static Component.Identifier.Key map(int lwjgl_key_code) {
switch (lwjgl_key_code) {
case Keyboard.KEY_ESCAPE:
return Component.Identifier.Key.ESCAPE;
case Keyboard.KEY_1:
return Component.Identifier.Key._1;
case Keyboard.KEY_2:
return Component.Identifier.Key._2;
case Keyboard.KEY_3:
return Component.Identifier.Key._3;
case Keyboard.KEY_4:
return Component.Identifier.Key._4;
case Keyboard.KEY_5:
return Component.Identifier.Key._5;
case Keyboard.KEY_6:
return Component.Identifier.Key._6;
case Keyboard.KEY_7:
return Component.Identifier.Key._7;
case Keyboard.KEY_8:
return Component.Identifier.Key._8;
case Keyboard.KEY_9:
return Component.Identifier.Key._9;
case Keyboard.KEY_0:
return Component.Identifier.Key._0;
case Keyboard.KEY_MINUS:
return Component.Identifier.Key.MINUS;
case Keyboard.KEY_EQUALS:
return Component.Identifier.Key.EQUALS;
case Keyboard.KEY_BACK:
return Component.Identifier.Key.BACK;
case Keyboard.KEY_TAB:
return Component.Identifier.Key.TAB;
case Keyboard.KEY_Q:
return Component.Identifier.Key.Q;
case Keyboard.KEY_W:
return Component.Identifier.Key.W;
case Keyboard.KEY_E:
return Component.Identifier.Key.E;
case Keyboard.KEY_R:
return Component.Identifier.Key.R;
case Keyboard.KEY_T:
return Component.Identifier.Key.T;
case Keyboard.KEY_Y:
return Component.Identifier.Key.Y;
case Keyboard.KEY_U:
return Component.Identifier.Key.U;
case Keyboard.KEY_I:
return Component.Identifier.Key.I;
case Keyboard.KEY_O:
return Component.Identifier.Key.O;
case Keyboard.KEY_P:
return Component.Identifier.Key.P;
case Keyboard.KEY_LBRACKET:
return Component.Identifier.Key.LBRACKET;
case Keyboard.KEY_RBRACKET:
return Component.Identifier.Key.RBRACKET;
case Keyboard.KEY_RETURN:
return Component.Identifier.Key.RETURN;
case Keyboard.KEY_LCONTROL:
return Component.Identifier.Key.LCONTROL;
case Keyboard.KEY_A:
return Component.Identifier.Key.A;
case Keyboard.KEY_S:
return Component.Identifier.Key.S;
case Keyboard.KEY_D:
return Component.Identifier.Key.D;
case Keyboard.KEY_F:
return Component.Identifier.Key.F;
case Keyboard.KEY_G:
return Component.Identifier.Key.G;
case Keyboard.KEY_H:
return Component.Identifier.Key.H;
case Keyboard.KEY_J:
return Component.Identifier.Key.J;
case Keyboard.KEY_K:
return Component.Identifier.Key.K;
case Keyboard.KEY_L:
return Component.Identifier.Key.L;
case Keyboard.KEY_SEMICOLON:
return Component.Identifier.Key.SEMICOLON;
case Keyboard.KEY_APOSTROPHE:
return Component.Identifier.Key.APOSTROPHE;
case Keyboard.KEY_GRAVE:
return Component.Identifier.Key.GRAVE;
case Keyboard.KEY_LSHIFT:
return Component.Identifier.Key.LSHIFT;
case Keyboard.KEY_BACKSLASH:
return Component.Identifier.Key.BACKSLASH;
case Keyboard.KEY_Z:
return Component.Identifier.Key.Z;
case Keyboard.KEY_X:
return Component.Identifier.Key.X;
case Keyboard.KEY_C:
return Component.Identifier.Key.C;
case Keyboard.KEY_V:
return Component.Identifier.Key.V;
case Keyboard.KEY_B:
return Component.Identifier.Key.B;
case Keyboard.KEY_N:
return Component.Identifier.Key.N;
case Keyboard.KEY_M:
return Component.Identifier.Key.M;
case Keyboard.KEY_COMMA:
return Component.Identifier.Key.COMMA;
case Keyboard.KEY_PERIOD:
return Component.Identifier.Key.PERIOD;
case Keyboard.KEY_SLASH:
return Component.Identifier.Key.SLASH;
case Keyboard.KEY_RSHIFT:
return Component.Identifier.Key.RSHIFT;
case Keyboard.KEY_MULTIPLY:
return Component.Identifier.Key.MULTIPLY;
case Keyboard.KEY_LMENU:
return Component.Identifier.Key.LALT;
case Keyboard.KEY_SPACE:
return Component.Identifier.Key.SPACE;
case Keyboard.KEY_CAPITAL:
return Component.Identifier.Key.CAPITAL;
case Keyboard.KEY_F1:
return Component.Identifier.Key.F1;
case Keyboard.KEY_F2:
return Component.Identifier.Key.F2;
case Keyboard.KEY_F3:
return Component.Identifier.Key.F3;
case Keyboard.KEY_F4:
return Component.Identifier.Key.F4;
case Keyboard.KEY_F5:
return Component.Identifier.Key.F5;
case Keyboard.KEY_F6:
return Component.Identifier.Key.F6;
case Keyboard.KEY_F7:
return Component.Identifier.Key.F7;
case Keyboard.KEY_F8:
return Component.Identifier.Key.F8;
case Keyboard.KEY_F9:
return Component.Identifier.Key.F9;
case Keyboard.KEY_F10:
return Component.Identifier.Key.F10;
case Keyboard.KEY_NUMLOCK:
return Component.Identifier.Key.NUMLOCK;
case Keyboard.KEY_SCROLL:
return Component.Identifier.Key.SCROLL;
case Keyboard.KEY_NUMPAD7:
return Component.Identifier.Key.NUMPAD7;
case Keyboard.KEY_NUMPAD8:
return Component.Identifier.Key.NUMPAD8;
case Keyboard.KEY_NUMPAD9:
return Component.Identifier.Key.NUMPAD9;
case Keyboard.KEY_SUBTRACT:
return Component.Identifier.Key.SUBTRACT;
case Keyboard.KEY_NUMPAD4:
return Component.Identifier.Key.NUMPAD4;
case Keyboard.KEY_NUMPAD5:
return Component.Identifier.Key.NUMPAD5;
case Keyboard.KEY_NUMPAD6:
return Component.Identifier.Key.NUMPAD6;
case Keyboard.KEY_ADD:
return Component.Identifier.Key.ADD;
case Keyboard.KEY_NUMPAD1:
return Component.Identifier.Key.NUMPAD1;
case Keyboard.KEY_NUMPAD2:
return Component.Identifier.Key.NUMPAD2;
case Keyboard.KEY_NUMPAD3:
return Component.Identifier.Key.NUMPAD3;
case Keyboard.KEY_NUMPAD0:
return Component.Identifier.Key.NUMPAD0;
case Keyboard.KEY_DECIMAL:
return Component.Identifier.Key.DECIMAL;
case Keyboard.KEY_F11:
return Component.Identifier.Key.F11;
case Keyboard.KEY_F12:
return Component.Identifier.Key.F12;
case Keyboard.KEY_F13:
return Component.Identifier.Key.F13;
case Keyboard.KEY_F14:
return Component.Identifier.Key.F14;
case Keyboard.KEY_F15:
return Component.Identifier.Key.F15;
case Keyboard.KEY_KANA:
return Component.Identifier.Key.KANA;
case Keyboard.KEY_CONVERT:
return Component.Identifier.Key.CONVERT;
case Keyboard.KEY_NOCONVERT:
return Component.Identifier.Key.NOCONVERT;
case Keyboard.KEY_YEN:
return Component.Identifier.Key.YEN;
case Keyboard.KEY_NUMPADEQUALS:
return Component.Identifier.Key.NUMPADEQUAL;
case Keyboard.KEY_CIRCUMFLEX:
return Component.Identifier.Key.CIRCUMFLEX;
case Keyboard.KEY_AT:
return Component.Identifier.Key.AT;
case Keyboard.KEY_COLON:
return Component.Identifier.Key.COLON;
case Keyboard.KEY_UNDERLINE:
return Component.Identifier.Key.UNDERLINE;
case Keyboard.KEY_KANJI:
return Component.Identifier.Key.KANJI;
case Keyboard.KEY_STOP:
return Component.Identifier.Key.STOP;
case Keyboard.KEY_AX:
return Component.Identifier.Key.AX;
case Keyboard.KEY_UNLABELED:
return Component.Identifier.Key.UNLABELED;
case Keyboard.KEY_NUMPADENTER:
return Component.Identifier.Key.NUMPADENTER;
case Keyboard.KEY_RCONTROL:
return Component.Identifier.Key.RCONTROL;
case Keyboard.KEY_NUMPADCOMMA:
return Component.Identifier.Key.NUMPADCOMMA;
case Keyboard.KEY_DIVIDE:
return Component.Identifier.Key.DIVIDE;
case Keyboard.KEY_SYSRQ:
return Component.Identifier.Key.SYSRQ;
case Keyboard.KEY_RMENU:
return Component.Identifier.Key.RALT;
case Keyboard.KEY_PAUSE:
return Component.Identifier.Key.PAUSE;
case Keyboard.KEY_HOME:
return Component.Identifier.Key.HOME;
case Keyboard.KEY_UP:
return Component.Identifier.Key.UP;
case Keyboard.KEY_PRIOR:
return Component.Identifier.Key.PAGEUP;
case Keyboard.KEY_LEFT:
return Component.Identifier.Key.LEFT;
case Keyboard.KEY_RIGHT:
return Component.Identifier.Key.RIGHT;
case Keyboard.KEY_END:
return Component.Identifier.Key.END;
case Keyboard.KEY_DOWN:
return Component.Identifier.Key.DOWN;
case Keyboard.KEY_NEXT:
return Component.Identifier.Key.PAGEDOWN;
case Keyboard.KEY_INSERT:
return Component.Identifier.Key.INSERT;
case Keyboard.KEY_DELETE:
return Component.Identifier.Key.DELETE;
case Keyboard.KEY_LMETA:
return Component.Identifier.Key.LWIN;
case Keyboard.KEY_RMETA:
return Component.Identifier.Key.RWIN;
case Keyboard.KEY_APPS:
return Component.Identifier.Key.APPS;
case Keyboard.KEY_POWER:
return Component.Identifier.Key.POWER;
case Keyboard.KEY_SLEEP:
return Component.Identifier.Key.SLEEP;
default:
return Component.Identifier.Key.UNKNOWN;
}
}
}
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.jinput;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import net.java.games.util.plugins.Plugin;
/**
* @author elias
*/
public class LWJGLEnvironmentPlugin extends ControllerEnvironment implements Plugin {
private final Controller[] controllers;
public LWJGLEnvironmentPlugin() {
this.controllers = new Controller[] { new LWJGLKeyboard(), new LWJGLMouse() };
}
public Controller[] getControllers() {
return controllers;
}
public boolean isSupported() {
return true;
}
}
@@ -0,0 +1,119 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.jinput;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import net.java.games.input.AbstractComponent;
import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.Event;
import net.java.games.input.Keyboard;
import net.java.games.input.Rumbler;
/**
* @author elias
*/
final class LWJGLKeyboard extends Keyboard {
LWJGLKeyboard() {
super("LWJGLKeyboard", createComponents(), new Controller[] {}, new Rumbler[] {});
}
private static Component[] createComponents() {
List<Key> components = new ArrayList<Key>();
Field[] vkey_fields = org.lwjglx.input.Keyboard.class.getFields();
for (Field vkey_field : vkey_fields) {
try {
if (Modifier.isStatic(vkey_field.getModifiers()) && vkey_field.getType() == int.class
&& vkey_field.getName()
.startsWith("KEY_")) {
int vkey_code = vkey_field.getInt(null);
Component.Identifier.Key key_id = KeyMap.map(vkey_code);
if (key_id != Component.Identifier.Key.UNKNOWN) components.add(new Key(key_id, vkey_code));
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return components.toArray(new Component[components.size()]);
}
public synchronized void pollDevice() throws IOException {
if (!org.lwjglx.input.Keyboard.isCreated()) return;
org.lwjglx.input.Keyboard.poll();
for (Component component : getComponents()) {
Key key = (Key) component;
key.update();
}
}
protected synchronized boolean getNextDeviceEvent(Event event) throws IOException {
if (!org.lwjglx.input.Keyboard.isCreated()) return false;
if (!org.lwjglx.input.Keyboard.next()) return false;
int lwjgl_key = org.lwjglx.input.Keyboard.getEventKey();
if (lwjgl_key == org.lwjglx.input.Keyboard.KEY_NONE) return false;
Component.Identifier.Key key_id = KeyMap.map(lwjgl_key);
if (key_id == null) return false;
Component key = getComponent(key_id);
if (key == null) return false;
float value = org.lwjglx.input.Keyboard.getEventKeyState() ? 1 : 0;
event.set(key, value, org.lwjglx.input.Keyboard.getEventNanoseconds());
return true;
}
private static final class Key extends AbstractComponent {
private final int lwjgl_key;
private float value;
Key(Identifier.Key key_id, int lwjgl_key) {
super(key_id.getName(), key_id);
this.lwjgl_key = lwjgl_key;
}
public void update() {
this.value = org.lwjglx.input.Keyboard.isKeyDown(lwjgl_key) ? 1 : 0;
}
protected float poll() {
return value;
}
public boolean isRelative() {
return false;
}
public boolean isAnalog() {
return false;
}
}
}
@@ -0,0 +1,182 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.jinput;
import java.io.IOException;
import net.java.games.input.AbstractComponent;
import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.Event;
import net.java.games.input.Mouse;
import net.java.games.input.Rumbler;
/**
* @author elias
*/
final class LWJGLMouse extends Mouse {
private static final int EVENT_X = 1;
private static final int EVENT_Y = 2;
private static final int EVENT_WHEEL = 3;
private static final int EVENT_BUTTON = 4;
private static final int EVENT_DONE = 5;
private int event_state = EVENT_DONE;
LWJGLMouse() {
super("LWJGLMouse", createComponents(), new Controller[] {}, new Rumbler[] {});
}
private static Component[] createComponents() {
return new Component[] { new Axis(Component.Identifier.Axis.X), new Axis(Component.Identifier.Axis.Y),
new Axis(Component.Identifier.Axis.Z), new Button(Component.Identifier.Button.LEFT),
new Button(Component.Identifier.Button.MIDDLE), new Button(Component.Identifier.Button.RIGHT) };
}
public synchronized void pollDevice() throws IOException {
if (!org.lwjglx.input.Mouse.isCreated()) return;
org.lwjglx.input.Mouse.poll();
for (int i = 0; i < 3; i++) setButtonState(i);
}
private Button map(int lwjgl_button) {
switch (lwjgl_button) {
case 0:
return (Button) getLeft();
case 1:
return (Button) getRight();
case 2:
return (Button) getMiddle();
default:
return null;
}
}
private void setButtonState(int lwjgl_button) {
Button button = map(lwjgl_button);
if (button != null) button.setValue(org.lwjglx.input.Mouse.isButtonDown(lwjgl_button) ? 1 : 0);
}
protected synchronized boolean getNextDeviceEvent(Event event) throws IOException {
if (!org.lwjglx.input.Mouse.isCreated()) return false;
while (true) {
long nanos = org.lwjglx.input.Mouse.getEventNanoseconds();
switch (event_state) {
case EVENT_X:
event_state = EVENT_Y;
int dx = org.lwjglx.input.Mouse.getEventDX();
if (dx != 0) {
event.set(getX(), dx, nanos);
return true;
}
break;
case EVENT_Y:
event_state = EVENT_WHEEL;
/*
* We must negate the y coord since lwjgl uses the
* OpenGL coordinate system
*/
int dy = -org.lwjglx.input.Mouse.getEventDY();
if (dy != 0) {
event.set(getY(), dy, nanos);
return true;
}
break;
case EVENT_WHEEL:
event_state = EVENT_BUTTON;
int dwheel = org.lwjglx.input.Mouse.getEventDWheel();
if (dwheel != 0) {
event.set(getWheel(), dwheel, nanos);
return true;
}
break;
case EVENT_BUTTON:
event_state = EVENT_DONE;
int lwjgl_button = org.lwjglx.input.Mouse.getEventButton();
if (lwjgl_button != -1) {
Button button = map(lwjgl_button);
if (button != null) {
event.set(button, org.lwjglx.input.Mouse.getEventButtonState() ? 1f : 0f, nanos);
return true;
}
}
break;
case EVENT_DONE:
if (!org.lwjglx.input.Mouse.next()) return false;
event_state = EVENT_X;
break;
default:
break;
}
}
}
static final class Axis extends AbstractComponent {
Axis(Identifier.Axis axis_id) {
super(axis_id.getName(), axis_id);
}
public boolean isRelative() {
return true;
}
protected float poll() throws IOException {
return 0;
}
public boolean isAnalog() {
return true;
}
}
static final class Button extends AbstractComponent {
private float value;
Button(Identifier.Button button_id) {
super(button_id.getName(), button_id);
}
void setValue(float value) {
this.value = value;
}
protected float poll() throws IOException {
return value;
}
public boolean isRelative() {
return false;
}
public boolean isAnalog() {
return false;
}
}
}
@@ -0,0 +1,61 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* When this annotation is used on a field, automatic cache-line-sized padding
* will be inserted around the field. This is useful in multi-threaded algorithms
* to avoid cache line false sharing. The annotation defaults to padding after
* the field, but can be changed to before or both before and after. It can be
* applied to both mapped object fields and POJO primitive fields.
*
* @author Spasi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CacheLinePad {
/**
* When true, cache-line padding will be inserted before the field.
*
* @return true if cache-line padding will be inserted before the field
*/
boolean before() default false;
/**
* When true, cache-line padding will be inserted after the field.
*
* @return true if cache-line padding will be inserted after the field
*/
boolean after() default true;
}
@@ -0,0 +1,146 @@
package org.lwjglx.util.mapped;
import static org.lwjglx.util.mapped.MappedHelper.ivget;
import static org.lwjglx.util.mapped.MappedHelper.ivput;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.MemoryUtil;
/**
* This micro-benchmark tries to detect the CPU's cache line size. This is
* done by exploiting cache line false sharing in multi-threaded code:
* When 2 threads simultaneously access the same cache line (and at least
* 1 access is a write), performance drops considerably. We detect this
* performance drop while decreasing the memory padding in every test step.
*
* @author Spasi
*/
final class CacheLineSize {
private CacheLineSize() {}
static int getCacheLineSize() {
final int THREADS = 2;
final int REPEATS = 100000 * THREADS;
final int LOCAL_REPEATS = REPEATS / THREADS;
// Detection will start from CacheLineMaxSize bytes.
final int MAX_SIZE = LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineMaxSize", 1024) / 4; // in
// #
// of
// integers
// Detection will stop when the execution time increases by more than CacheLineTimeThreshold %.
final double TIME_THRESHOLD = 1.0
+ LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineTimeThreshold", 50) / 100.0;
final ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
final ExecutorCompletionService<Long> completionService = new ExecutorCompletionService<Long>(executorService);
try {
// We need to use a NIO buffer in order to guarantee memory alignment.
final IntBuffer memory = getMemory(MAX_SIZE);
// -- WARMUP --
final int WARMUP = 10;
for (int i = 0; i < WARMUP; i++) doTest(THREADS, LOCAL_REPEATS, 0, memory, completionService);
// -- CACHE LINE SIZE DETECTION --
long totalTime = 0;
int count = 0;
int cacheLineSize = 64; // fallback to the most common size these days
boolean found = false;
for (int i = MAX_SIZE; i >= 1; i >>= 1) {
final long time = doTest(THREADS, LOCAL_REPEATS, i, memory, completionService);
if (totalTime > 0) { // Ignore first run
final long avgTime = totalTime / count;
if ((double) time / (double) avgTime > TIME_THRESHOLD) { // Try to detect a noticeable jump in
// execution time
cacheLineSize = (i << 1) * 4;
found = true;
break;
}
}
totalTime += time;
count++;
}
if (LWJGLUtil.DEBUG) {
if (found) LWJGLUtil.log("Cache line size detected: " + cacheLineSize + " bytes");
else LWJGLUtil.log("Failed to detect cache line size, assuming " + cacheLineSize + " bytes");
}
return cacheLineSize;
} finally {
executorService.shutdown();
}
}
public static void main(String[] args) {
CacheUtil.getCacheLineSize();
}
static long memoryLoop(final int index, final int repeats, final IntBuffer memory, final int padding) {
final long address = MemoryUtil.getAddress(memory) + (index * padding * 4);
final long time = System.nanoTime();
for (int i = 0; i < repeats; i++) {
// Use volatile access to avoid server VM optimizations.
ivput(ivget(address) + 1, address);
}
return System.nanoTime() - time;
}
private static IntBuffer getMemory(final int START_SIZE) {
final int PAGE_SIZE = MappedObjectUnsafe.INSTANCE.pageSize();
final ByteBuffer buffer = ByteBuffer.allocateDirect((START_SIZE * 4) + PAGE_SIZE)
.order(ByteOrder.nativeOrder());
// Align to page and, consequently, to cache line. Otherwise results will be inconsistent.
if (MemoryUtil.getAddress(buffer) % PAGE_SIZE != 0) {
// Round up to page boundary
buffer.position(PAGE_SIZE - (int) (MemoryUtil.getAddress(buffer) & (PAGE_SIZE - 1)));
}
return buffer.asIntBuffer();
}
private static long doTest(final int threads, final int repeats, final int padding, final IntBuffer memory,
final ExecutorCompletionService<Long> completionService) {
for (int i = 0; i < threads; i++) submitTest(completionService, i, repeats, memory, padding);
return waitForResults(threads, completionService);
}
private static void submitTest(final ExecutorCompletionService<Long> completionService, final int index,
final int repeats, final IntBuffer memory, final int padding) {
completionService.submit(new Callable<Long>() {
public Long call() throws Exception {
return memoryLoop(index, repeats, memory, padding);
}
});
}
private static long waitForResults(final int count, final ExecutorCompletionService<Long> completionService) {
try {
long totalTime = 0;
for (int i = 0; i < count; i++) totalTime += completionService.take()
.get();
return totalTime;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,195 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.MemoryUtil;
import org.lwjglx.PointerBuffer;
/**
* This class provides utility methods for allocating cache-line-aligned
* NIO buffers. The CPU cache line size is detected using a micro-benchmark
* that exploits the performation degredation that occurs when different
* threads write to different locations of the same cache line. The detection
* should be reasonably robust on both the server and client VM, but there
* are a few system properties that can be used to tune it.
*
* @author Spasi
*/
public final class CacheUtil {
private static final int CACHE_LINE_SIZE;
static {
final Integer size = LWJGLUtil.getPrivilegedInteger("org.lwjglx.util.mapped.CacheLineSize"); // forces a
// specific cache
// line size
if (size != null) {
if (size < 1) throw new IllegalStateException("Invalid CacheLineSize specified: " + size);
CACHE_LINE_SIZE = size;
} else if (Runtime.getRuntime()
.availableProcessors() == 1) { // We cannot use false sharing to detect it
/*
* Spasi:
* I have implemented a single-threaded benchmark for this, but it requires
* lots of memory allocations and could not tune it for both the client and
* server VM. It's not a big deal anyway, 64 bytes should be ok for any
* single-core CPU.
*/
if (LWJGLUtil.DEBUG)
LWJGLUtil.log("Cannot detect cache line size on single-core CPUs, assuming 64 bytes.");
CACHE_LINE_SIZE = 64;
} else CACHE_LINE_SIZE = CacheLineSize.getCacheLineSize();
}
private CacheUtil() {}
/**
* Returns the CPU cache line size, in number of bytes.
*
* @return the cache line size
*/
public static int getCacheLineSize() {
return CACHE_LINE_SIZE;
}
/**
* Construct a direct, native-ordered and cache-line-aligned bytebuffer with the specified size.
*
* @param size The size, in bytes
*
* @return a ByteBuffer
*/
public static ByteBuffer createByteBuffer(int size) {
ByteBuffer buffer = ByteBuffer.allocateDirect(size + CACHE_LINE_SIZE);
// Align to cache line.
if (MemoryUtil.getAddress(buffer) % CACHE_LINE_SIZE != 0) {
// Round up to cache line boundary
buffer.position(CACHE_LINE_SIZE - (int) (MemoryUtil.getAddress(buffer) & (CACHE_LINE_SIZE - 1)));
}
buffer.limit(buffer.position() + size);
return buffer.slice()
.order(ByteOrder.nativeOrder());
}
/**
* Construct a direct, native-ordered and cache-line-aligned shortbuffer with the specified number
* of elements.
*
* @param size The size, in shorts
*
* @return a ShortBuffer
*/
public static ShortBuffer createShortBuffer(int size) {
return createByteBuffer(size << 1).asShortBuffer();
}
/**
* Construct a direct, native-ordered and cache-line-aligned charbuffer with the specified number
* of elements.
*
* @param size The size, in chars
*
* @return an CharBuffer
*/
public static CharBuffer createCharBuffer(int size) {
return createByteBuffer(size << 1).asCharBuffer();
}
/**
* Construct a direct, native-ordered and cache-line-aligned intbuffer with the specified number
* of elements.
*
* @param size The size, in ints
*
* @return an IntBuffer
*/
public static IntBuffer createIntBuffer(int size) {
return createByteBuffer(size << 2).asIntBuffer();
}
/**
* Construct a direct, native-ordered and cache-line-aligned longbuffer with the specified number
* of elements.
*
* @param size The size, in longs
*
* @return an LongBuffer
*/
public static LongBuffer createLongBuffer(int size) {
return createByteBuffer(size << 3).asLongBuffer();
}
/**
* Construct a direct, native-ordered and cache-line-aligned floatbuffer with the specified number
* of elements.
*
* @param size The size, in floats
*
* @return a FloatBuffer
*/
public static FloatBuffer createFloatBuffer(int size) {
return createByteBuffer(size << 2).asFloatBuffer();
}
/**
* Construct a direct, native-ordered and cache-line-aligned doublebuffer with the specified number
* of elements.
*
* @param size The size, in floats
*
* @return a FloatBuffer
*/
public static DoubleBuffer createDoubleBuffer(int size) {
return createByteBuffer(size << 3).asDoubleBuffer();
}
/**
* Construct a cache-line-aligned PointerBuffer with the specified number
* of elements.
*
* @param size The size, in memory addresses
*
* @return a PointerBuffer
*/
public static PointerBuffer createPointerBuffer(int size) {
return new PointerBuffer(createByteBuffer(size * PointerBuffer.getPointerSize()));
}
}
@@ -0,0 +1,60 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be used on fields of {@link MappedObject} subclasses,
* to manually specify byte offsets and lengths. This is useful when the
* mapped fields require custom alignment. {@link java.nio.ByteBuffer}
* fields are required to have this annotation with a hardcoded byte length.
*
* @author Riven
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MappedField {
/**
* Specifies the field byte offset within the mapped object.
*
* @return the field byte offset
*/
long byteOffset() default -1;
/**
* Specifies the field byte length. Required for {@link java.nio.ByteBuffer} fields.
*
* @return the field byte length
*/
long byteLength() default -1;
}
@@ -0,0 +1,66 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.util.Iterator;
/**
* Iterable implementation for {@link MappedObject}.
*
* @author Riven
*/
final class MappedForeach<T extends MappedObject> implements Iterable<T> {
final T mapped;
final int elementCount;
MappedForeach(T mapped, int elementCount) {
this.mapped = mapped;
this.elementCount = elementCount;
}
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index;
public boolean hasNext() {
return this.index < (MappedForeach.this.elementCount);
}
public T next() {
mapped.setViewAddress(mapped.getViewAddress(this.index++));
return mapped;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
@@ -0,0 +1,385 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import static org.lwjglx.util.mapped.MappedObjectUnsafe.*;
import java.nio.ByteBuffer;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.MemoryUtil;
/**
* [INTERNAL USE ONLY]
* <p/>
* Helper class used by the bytecode transformer.
*
* @author Riven
*/
public class MappedHelper {
public static void setup(MappedObject mo, ByteBuffer buffer, int align, int sizeof) {
if (LWJGLUtil.CHECKS && mo.baseAddress != 0L)
throw new IllegalStateException("this method should not be called by user-code");
if (LWJGLUtil.CHECKS && !buffer.isDirect()) throw new IllegalArgumentException("bytebuffer must be direct");
mo.preventGC = buffer;
if (LWJGLUtil.CHECKS && align <= 0) throw new IllegalArgumentException("invalid alignment");
if (LWJGLUtil.CHECKS && (sizeof <= 0 || sizeof % align != 0))
throw new IllegalStateException("sizeof not a multiple of alignment");
long addr = MemoryUtil.getAddress(buffer);
if (LWJGLUtil.CHECKS && addr % align != 0)
throw new IllegalStateException("buffer address not aligned on " + align + " bytes");
mo.baseAddress = mo.viewAddress = addr;
}
public static void checkAddress(long viewAddress, MappedObject mapped) {
mapped.checkAddress(viewAddress);
}
public static void put_views(MappedSet2 set, int view) {
set.view(view);
}
public static void put_views(MappedSet3 set, int view) {
set.view(view);
}
public static void put_views(MappedSet4 set, int view) {
set.view(view);
}
public static void put_view(MappedObject mapped, int view, int sizeof) {
mapped.setViewAddress(mapped.baseAddress + view * sizeof);
}
public static int get_view(MappedObject mapped, int sizeof) {
return (int) (mapped.viewAddress - mapped.baseAddress) / sizeof;
}
public static void put_view_shift(MappedObject mapped, int view, int sizeof_shift) {
mapped.setViewAddress(mapped.baseAddress + (view << sizeof_shift));
}
public static int get_view_shift(MappedObject mapped, int sizeof_shift) {
return ((int) (mapped.viewAddress - mapped.baseAddress)) >> sizeof_shift;
}
public static void put_view_next(MappedObject mapped, int sizeof) {
mapped.setViewAddress(mapped.viewAddress + sizeof);
}
public static MappedObject dup(MappedObject src, MappedObject dst) {
dst.baseAddress = src.baseAddress;
dst.viewAddress = src.viewAddress;
dst.preventGC = src.preventGC;
return dst;
}
public static MappedObject slice(MappedObject src, MappedObject dst) {
dst.baseAddress = src.viewAddress; // !
dst.viewAddress = src.viewAddress;
dst.preventGC = src.preventGC;
return dst;
}
public static void copy(MappedObject src, MappedObject dst, int bytes) {
if (MappedObject.CHECKS) {
src.checkRange(bytes);
dst.checkRange(bytes);
}
INSTANCE.copyMemory(src.viewAddress, dst.viewAddress, bytes);
}
public static ByteBuffer newBuffer(long address, int capacity) {
return MappedObjectUnsafe.newBuffer(address, capacity);
}
// ---- primitive fields read/write
// byte
public static void bput(byte value, long addr) {
INSTANCE.putByte(addr, value);
}
public static void bput(MappedObject mapped, byte value, int fieldOffset) {
INSTANCE.putByte(mapped.viewAddress + fieldOffset, value);
}
public static byte bget(long addr) {
return INSTANCE.getByte(addr);
}
public static byte bget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getByte(mapped.viewAddress + fieldOffset);
}
public static void bvput(byte value, long addr) {
INSTANCE.putByteVolatile(null, addr, value);
}
public static void bvput(MappedObject mapped, byte value, int fieldOffset) {
INSTANCE.putByteVolatile(null, mapped.viewAddress + fieldOffset, value);
}
public static byte bvget(long addr) {
return INSTANCE.getByteVolatile(null, addr);
}
public static byte bvget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getByteVolatile(null, mapped.viewAddress + fieldOffset);
}
// short
public static void sput(short value, long addr) {
INSTANCE.putShort(addr, value);
}
public static void sput(MappedObject mapped, short value, int fieldOffset) {
INSTANCE.putShort(mapped.viewAddress + fieldOffset, value);
}
public static short sget(long addr) {
return INSTANCE.getShort(addr);
}
public static short sget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getShort(mapped.viewAddress + fieldOffset);
}
public static void svput(short value, long addr) {
INSTANCE.putShortVolatile(null, addr, value);
}
public static void svput(MappedObject mapped, short value, int fieldOffset) {
INSTANCE.putShortVolatile(null, mapped.viewAddress + fieldOffset, value);
}
public static short svget(long addr) {
return INSTANCE.getShortVolatile(null, addr);
}
public static short svget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getShortVolatile(null, mapped.viewAddress + fieldOffset);
}
// char
public static void cput(char value, long addr) {
INSTANCE.putChar(addr, value);
}
public static void cput(MappedObject mapped, char value, int fieldOffset) {
INSTANCE.putChar(mapped.viewAddress + fieldOffset, value);
}
public static char cget(long addr) {
return INSTANCE.getChar(addr);
}
public static char cget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getChar(mapped.viewAddress + fieldOffset);
}
public static void cvput(char value, long addr) {
INSTANCE.putCharVolatile(null, addr, value);
}
public static void cvput(MappedObject mapped, char value, int fieldOffset) {
INSTANCE.putCharVolatile(null, mapped.viewAddress + fieldOffset, value);
}
public static char cvget(long addr) {
return INSTANCE.getCharVolatile(null, addr);
}
public static char cvget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getCharVolatile(null, mapped.viewAddress + fieldOffset);
}
// int
public static void iput(int value, long addr) {
INSTANCE.putInt(addr, value);
}
public static void iput(MappedObject mapped, int value, int fieldOffset) {
INSTANCE.putInt(mapped.viewAddress + fieldOffset, value);
}
public static int iget(long address) {
return INSTANCE.getInt(address);
}
public static int iget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getInt(mapped.viewAddress + fieldOffset);
}
public static void ivput(int value, long addr) {
INSTANCE.putIntVolatile(null, addr, value);
}
public static void ivput(MappedObject mapped, int value, int fieldOffset) {
INSTANCE.putIntVolatile(null, mapped.viewAddress + fieldOffset, value);
}
public static int ivget(long address) {
return INSTANCE.getIntVolatile(null, address);
}
public static int ivget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getIntVolatile(null, mapped.viewAddress + fieldOffset);
}
// float
public static void fput(float value, long addr) {
INSTANCE.putFloat(addr, value);
}
public static void fput(MappedObject mapped, float value, int fieldOffset) {
INSTANCE.putFloat(mapped.viewAddress + fieldOffset, value);
}
public static float fget(long addr) {
return INSTANCE.getFloat(addr);
}
public static float fget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getFloat(mapped.viewAddress + fieldOffset);
}
public static void fvput(float value, long addr) {
INSTANCE.putFloatVolatile(null, addr, value);
}
public static void fvput(MappedObject mapped, float value, int fieldOffset) {
INSTANCE.putFloatVolatile(null, mapped.viewAddress + fieldOffset, value);
}
public static float fvget(long addr) {
return INSTANCE.getFloatVolatile(null, addr);
}
public static float fvget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getFloatVolatile(null, mapped.viewAddress + fieldOffset);
}
// long
public static void jput(long value, long addr) {
INSTANCE.putLong(addr, value);
}
public static void jput(MappedObject mapped, long value, int fieldOffset) {
INSTANCE.putLong(mapped.viewAddress + fieldOffset, value);
}
public static long jget(long addr) {
return INSTANCE.getLong(addr);
}
public static long jget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getLong(mapped.viewAddress + fieldOffset);
}
public static void jvput(long value, long addr) {
INSTANCE.putLongVolatile(null, addr, value);
}
public static void jvput(MappedObject mapped, long value, int fieldOffset) {
INSTANCE.putLongVolatile(null, mapped.viewAddress + fieldOffset, value);
}
public static long jvget(long addr) {
return INSTANCE.getLongVolatile(null, addr);
}
public static long jvget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getLongVolatile(null, mapped.viewAddress + fieldOffset);
}
// address
public static void aput(long value, long addr) {
INSTANCE.putAddress(addr, value);
}
public static void aput(MappedObject mapped, long value, int fieldOffset) {
INSTANCE.putAddress(mapped.viewAddress + fieldOffset, value);
}
public static long aget(long addr) {
return INSTANCE.getAddress(addr);
}
public static long aget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getAddress(mapped.viewAddress + fieldOffset);
}
// double
public static void dput(double value, long addr) {
INSTANCE.putDouble(addr, value);
}
public static void dput(MappedObject mapped, double value, int fieldOffset) {
INSTANCE.putDouble(mapped.viewAddress + fieldOffset, value);
}
public static double dget(long addr) {
return INSTANCE.getDouble(addr);
}
public static double dget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getDouble(mapped.viewAddress + fieldOffset);
}
public static void dvput(double value, long addr) {
INSTANCE.putDoubleVolatile(null, addr, value);
}
public static void dvput(MappedObject mapped, double value, int fieldOffset) {
INSTANCE.putDoubleVolatile(null, mapped.viewAddress + fieldOffset, value);
}
public static double dvget(long addr) {
return INSTANCE.getDoubleVolatile(null, addr);
}
public static double dvget(MappedObject mapped, int fieldOffset) {
return INSTANCE.getDoubleVolatile(null, mapped.viewAddress + fieldOffset);
}
}
@@ -0,0 +1,286 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import org.lwjglx.LWJGLUtil;
import org.lwjglx.MemoryUtil;
/**
* Base superclass of all mapped objects. Classes that require
* data mapping should extend this class and registered with
* {@link MappedObjectTransformer#register(Class)}.
* <p/>
* Subclasses may only specify the default constructor. Any code
* inside that constructor is optional, but will not run when the
* view is instantiated, see {@link #runViewConstructor()}.
* <p/>
* Bounds checking may be enabled through a JVM system property: org.lwjglx.util.mapped.Checks=true
*
* @author Riven
*/
public abstract class MappedObject {
static final boolean CHECKS = LWJGLUtil.getPrivilegedBoolean("org.lwjglx.util.mapped.Checks");
protected MappedObject() {
//
}
/** The mapped object base memory address, in bytes. Read-only. */
public long baseAddress;
/** The mapped object view memory address, in bytes. Read-only. */
public long viewAddress;
/** The mapped buffer. */
ByteBuffer preventGC;
/**
* Holds the value of sizeof of the sub-type of this MappedObject<br>
* <br>
* The behavior of this (transformed) method does not follow the normal Java behavior.<br>
* <code>Vec2.SIZEOF</code> will yield 8 (2 floats)<br>
* <code>Vec3.SIZEOF</code> will yield 12 (3 floats)<br>
* This (required) notation might cause compiler warnings, which can be suppressed
* with @SuppressWarnings("static-access").<br>
* Using Java 5.0's static-import on this method will break functionality.
*/
public static int SIZEOF = -1; // any method that calls these field will have its call-site modified ('final' per
// subtype)
/**
* The mapped object view offset, in elements. Read/write.
* This is a virtual field, used as a convenient getter/setter for {@see viewAddress}.
*/
public int view;
protected final long getViewAddress(final int view) {
// No call-site modification for this, we override in every subclass instead,
// so that we can use it in MappedForeach.
throw new InternalError("type not registered");
}
public final void setViewAddress(final long address) {
if (CHECKS) checkAddress(address);
this.viewAddress = address;
}
final void checkAddress(final long address) {
final long base = MemoryUtil.getAddress0(preventGC);
final int offset = (int) (address - base);
if (address < base || preventGC.capacity() < (offset + getSizeof()))
throw new IndexOutOfBoundsException(Integer.toString(offset / getSizeof()));
}
final void checkRange(final int bytes) {
if (bytes < 0) throw new IllegalArgumentException();
if (preventGC.capacity() < (viewAddress - MemoryUtil.getAddress0(preventGC) + bytes))
throw new BufferOverflowException();
}
/** The mapped object memory alignment, in bytes. Read-only. */
/**
* Returns the mapped object memory alignment, in bytes.
*
* @return the memory alignment
*/
public final int getAlign() {
// No call-site modification for this, we override in every subclass instead.
throw new InternalError("type not registered");
}
/**
* Returns the mapped object memory sizeof, in bytes.
*
* @return the sizeof value
*/
public final int getSizeof() {
// No call-site modification for this, we override in every subclass instead.
throw new InternalError("type not registered");
}
/**
* Returns the number of mapped objects that fit in the mapped buffer.
*
* @return the mapped object capacity
*/
public final int capacity() {
// No call-site modification for this, we override in every subclass instead.
throw new InternalError("type not registered");
}
/**
* Creates a MappedObject instance, mapping the memory region of the specified direct ByteBuffer.
* <p/>
* The behavior of this (transformed) method does not follow the normal Java behavior.<br>
* <code>Vec2.map(buffer)</code> will return a mapped Vec2 instance.<br>
* <code>Vec3.map(buffer)</code> will return a mapped Vec3 instance.<br>
* This (required) notation might cause compiler warnings, which can be suppressed
* with @SuppressWarnings("static-access").<br>
* Using Java 5.0's static-import on this method will break functionality.
*/
@SuppressWarnings("unused")
public static <T extends MappedObject> T map(ByteBuffer bb) {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Creates a MappedObject instance, mapping the memory region specified. This is useful for mapping
* arbitrary regions in memory, e.g. OpenCL CLMem objects, without creating a ByteBuffer first.
* <p/>
* The behavior of this (transformed) method does not follow the normal Java behavior.<br>
* <code>Vec2.map(buffer)</code> will return a mapped Vec2 instance.<br>
* <code>Vec3.map(buffer)</code> will return a mapped Vec3 instance.<br>
* This (required) notation might cause compiler warnings, which can be suppressed
* with @SuppressWarnings("static-access").<br>
* Using Java 5.0's static-import on this method will break functionality.
*/
@SuppressWarnings("unused")
public static <T extends MappedObject> T map(long address, int capacity) {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Creates a MappedObject instance, mapping the memory region of an allocated direct ByteBuffer with a capacity of
* <code>elementCount*SIZEOF</code>
* <p/>
* The behavior of this (transformed) method does not follow the normal Java behavior.<br>
* <code>Vec2.malloc(int)</code> will return a mapped Vec2 instance.<br>
* <code>Vec3.malloc(int)</code> will return a mapped Vec3 instance.<br>
* This (required) notation might cause compiler warnings, which can be suppressed
* with @SuppressWarnings("static-access").<br>
* Using Java 5.0's static-import on this method will break functionality.
*/
@SuppressWarnings("unused")
public static <T extends MappedObject> T malloc(int elementCount) {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Creates an identical new MappedObject instance, comparable to the
* contract of {@link ByteBuffer#duplicate}. This is useful when more than one
* views of the mapped object are required at the same time, e.g. in
* multithreaded access.
*/
public final <T extends MappedObject> T dup() {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Creates a new MappedObject instance, with a base offset equal to
* the offset of the current view, comparable to the contract of {@link ByteBuffer#slice}.
*/
public final <T extends MappedObject> T slice() {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Any code in the default constructor will not run automatically. This method
* can be used to execute that code on the current view.
*/
public final void runViewConstructor() {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/** Moves the current view to the next element. */
public final void next() {
// No call-site modification for this, we override in every subclass instead,
// so that we can use it in MappedSetX.
throw new InternalError("type not registered");
}
/**
* Copies and amount of <code>SIZEOF - padding</code> bytes, from the current
* mapped object, to the specified mapped object.
*/
@SuppressWarnings("unused")
public final <T extends MappedObject> void copyTo(T target) {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Copies and amount of <code>SIZEOF * instances</code> bytes, from the
* current mapped object, to the specified mapped object. Note that
* this includes any padding bytes that are part of SIZEOF.
*/
@SuppressWarnings("unused")
public final <T extends MappedObject> void copyRange(T target, int instances) {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Creates an {@link Iterable} <MappedObject> that will step through
* <code>capacity()</code> views, leaving the <code>view</code> at
* the last valid value.<br>
* <p/>
* For convenience you are encouraged to static-import this specific method:
* <code>import static org.lwjglx.util.mapped.MappedObject.foreach;</code>
*/
public static <T extends MappedObject> Iterable<T> foreach(T mapped) {
return foreach(mapped, mapped.capacity());
}
/**
* Creates an {@link Iterable} <MappedObject> that will step through
* <code>elementCount</code> views, leaving the <code>view</code> at
* the last valid value.<br>
* <p/>
* For convenience you are encouraged to static-import this specific method:
* <code>import static org.lwjglx.util.mapped.MappedObject.foreach;</code>
*/
public static <T extends MappedObject> Iterable<T> foreach(T mapped, int elementCount) {
return new MappedForeach<T>(mapped, elementCount);
}
@SuppressWarnings("unused")
public final <T extends MappedObject> T[] asArray() {
// any method that calls this method will have its call-site modified
throw new InternalError("type not registered");
}
/**
* Returns the {@link ByteBuffer} that backs this mapped object.
*
* @return the backing buffer
*/
public final ByteBuffer backingByteBuffer() {
return this.preventGC;
}
}
@@ -0,0 +1,185 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import org.lwjglx.LWJGLUtil;
/**
* This classloader is responsible for applying the bytecode transformation to mapped objects.
* The transformation can either be applied using a Java agent, or with the convenient {@link #fork} method.
*
* @author Riven
*/
public class MappedObjectClassLoader extends URLClassLoader {
static final String MAPPEDOBJECT_PACKAGE_PREFIX = MappedObjectClassLoader.class.getPackage()
.getName() + ".";
static boolean FORKED;
/**
* Forks the specified class containing a main method, passing the specified arguments. See
* org.lwjglx.test.mapped.TestMappedObject for example usage.
*
* @param mainClass the class containing the main method
* @param args the arguments to pass
*
* @return true if the fork was successful.
*/
public static boolean fork(Class<?> mainClass, String[] args) {
if (FORKED) {
return false;
}
FORKED = true;
try {
MappedObjectClassLoader loader = new MappedObjectClassLoader(mainClass);
loader.loadMappedObject();
Class<?> replacedMainClass = loader.loadClass(mainClass.getName());
Method mainMethod = replacedMainClass.getMethod("main", String[].class);
mainMethod.invoke(null, new Object[] { args });
} catch (InvocationTargetException exc) {
Thread.currentThread()
.getUncaughtExceptionHandler()
.uncaughtException(Thread.currentThread(), exc.getCause());
} catch (Throwable cause) {
throw new Error("failed to fork", cause);
}
return true;
}
private MappedObjectClassLoader(Class<?> mainClass) {
super(((URLClassLoader) mainClass.getClassLoader()).getURLs());
}
protected synchronized Class<?> loadMappedObject() throws ClassNotFoundException {
final String name = MappedObject.class.getName();
String className = name.replace('.', '/');
byte[] bytecode = readStream(this.getResourceAsStream(className.concat(".class")));
long t0 = System.nanoTime();
bytecode = MappedObjectTransformer.transformMappedObject(bytecode);
long t1 = System.nanoTime();
total_time_transforming += (t1 - t0);
if (MappedObjectTransformer.PRINT_ACTIVITY) printActivity(className, t0, t1);
Class<?> clazz = super.defineClass(name, bytecode, 0, bytecode.length);
resolveClass(clazz);
return clazz;
}
private static long total_time_transforming;
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (name.startsWith("java.") || name.startsWith("javax.")
|| name.startsWith("sun.")
|| name.startsWith("sunw.")
|| name.startsWith("org.objectweb.asm.")) return super.loadClass(name, resolve);
final String className = name.replace('.', '/');
final boolean inThisPackage = name.startsWith(MAPPEDOBJECT_PACKAGE_PREFIX);
if (inThisPackage && (name.equals(MappedObjectClassLoader.class.getName())
|| name.equals((MappedObjectTransformer.class.getName()))
|| name.equals((CacheUtil.class.getName())))) return super.loadClass(name, resolve);
byte[] bytecode = readStream(this.getResourceAsStream(className.concat(".class")));
// Classes in this package do not get transformed, but need to go through here because we have transformed
// MappedObject.
if (!(inThisPackage && name.substring(MAPPEDOBJECT_PACKAGE_PREFIX.length())
.indexOf('.') == -1)) {
long t0 = System.nanoTime();
final byte[] newBytecode = MappedObjectTransformer.transformMappedAPI(className, bytecode);
long t1 = System.nanoTime();
total_time_transforming += (t1 - t0);
if (bytecode != newBytecode) {
bytecode = newBytecode;
if (MappedObjectTransformer.PRINT_ACTIVITY) printActivity(className, t0, t1);
}
}
Class<?> clazz = super.defineClass(name, bytecode, 0, bytecode.length);
if (resolve) resolveClass(clazz);
return clazz;
}
private static void printActivity(final String className, final long t0, final long t1) {
final StringBuilder msg = new StringBuilder(MappedObjectClassLoader.class.getSimpleName() + ": " + className);
if (MappedObjectTransformer.PRINT_TIMING) msg.append(
"\n\ttransforming took " + (t1 - t0) / 1000
+ " micros (total: "
+ (total_time_transforming / 1000 / 1000)
+ "ms)");
LWJGLUtil.log(msg);
}
private static byte[] readStream(InputStream in) {
byte[] bytecode = new byte[256];
int len = 0;
try {
while (true) {
if (bytecode.length == len) bytecode = copyOf(bytecode, len * 2);
int got = in.read(bytecode, len, bytecode.length - len);
if (got == -1) break;
len += got;
}
} catch (IOException exc) {
// stop!
} finally {
try {
in.close();
} catch (IOException exc) {
// ignore...
}
}
return copyOf(bytecode, len);
}
private static byte[] copyOf(byte[] original, int newLength) {
byte[] copy = new byte[newLength];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,103 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import sun.misc.Unsafe;
/**
* [INTERNAL USE ONLY]
*
* @author Riven
*/
final class MappedObjectUnsafe {
static final Unsafe INSTANCE = getUnsafeInstance();
private static final long BUFFER_ADDRESS_OFFSET = getObjectFieldOffset(ByteBuffer.class, "address");
private static final long BUFFER_CAPACITY_OFFSET = getObjectFieldOffset(ByteBuffer.class, "capacity");
private static final ByteBuffer global = ByteBuffer.allocateDirect(4 * 1024);
static ByteBuffer newBuffer(long address, int capacity) {
if (address <= 0L || capacity < 0) throw new IllegalStateException("you almost crashed the jvm");
ByteBuffer buffer = global.duplicate()
.order(ByteOrder.nativeOrder());
INSTANCE.putLong(buffer, BUFFER_ADDRESS_OFFSET, address);
INSTANCE.putInt(buffer, BUFFER_CAPACITY_OFFSET, capacity);
buffer.position(0);
buffer.limit(capacity);
return buffer;
}
private static long getObjectFieldOffset(Class<?> type, String fieldName) {
while (type != null) {
try {
return INSTANCE.objectFieldOffset(type.getDeclaredField(fieldName));
} catch (Throwable t) {
type = type.getSuperclass();
}
}
throw new UnsupportedOperationException();
}
private static Unsafe getUnsafeInstance() {
final Field[] fields = Unsafe.class.getDeclaredFields();
/*
* Different runtimes use different names for the Unsafe singleton,
* so we cannot use .getDeclaredField and we scan instead. For example:
* Oracle: theUnsafe
* PERC : m_unsafe_instance
* Android: THE_ONE
*/
for (Field field : fields) {
if (!field.getType()
.equals(Unsafe.class)) continue;
final int modifiers = field.getModifiers();
if (!(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers))) continue;
field.setAccessible(true);
try {
return (Unsafe) field.get(null);
} catch (IllegalAccessException e) {
// ignore
}
break;
}
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
/**
* Factory for mapped sets. A mapped set can be used as a Structure of Arrays by
* linking together the view of two or more mapped objects. Changing the view
* of the mapped set, changes the corresponding view of all the mapped objects in
* the set.
*/
public class MappedSet {
/**
* Creates a <code>MappedSet</code> by linking the specified <code>MappedObject</code>s.
*
* @return the mapped set.
*/
public static MappedSet2 create(MappedObject a, MappedObject b) {
return new MappedSet2(a, b);
}
/**
* Creates a <code>MappedSet</code> by linking the specified <code>MappedObject</code>s.
*
* @return the mapped set.
*/
public static MappedSet3 create(MappedObject a, MappedObject b, MappedObject c) {
return new MappedSet3(a, b, c);
}
/**
* Creates a <code>MappedSet</code> by linking the specified <code>MappedObject</code>s.
*
* @return the mapped set.
*/
public static MappedSet4 create(MappedObject a, MappedObject b, MappedObject c, MappedObject d) {
return new MappedSet4(a, b, c, d);
}
}
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
/** <code>MappedSet</code> implementation for two <code>MappedObject</code>s. */
public class MappedSet2 {
private final MappedObject a, b;
MappedSet2(MappedObject a, MappedObject b) {
this.a = a;
this.b = b;
}
public int view;
void view(int view) {
a.setViewAddress(a.getViewAddress(view));
b.setViewAddress(b.getViewAddress(view));
}
public void next() {
this.a.next();
this.b.next();
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
/** <code>MappedSet</code> implementation for three <code>MappedObject</code>s. */
public class MappedSet3 {
private final MappedObject a, b, c;
MappedSet3(MappedObject a, MappedObject b, MappedObject c) {
this.a = a;
this.b = b;
this.c = c;
}
public int view;
void view(int view) {
a.setViewAddress(a.getViewAddress(view));
b.setViewAddress(b.getViewAddress(view));
c.setViewAddress(c.getViewAddress(view));
}
public void next() {
this.a.next();
this.b.next();
this.c.next();
}
}
@@ -0,0 +1,56 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
/** <code>MappedSet</code> implementation for four <code>MappedObject</code>s. */
public class MappedSet4 {
private final MappedObject a, b, c, d;
MappedSet4(MappedObject a, MappedObject b, MappedObject c, MappedObject d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public int view;
void view(int view) {
a.setViewAddress(a.getViewAddress(view));
b.setViewAddress(b.getViewAddress(view));
c.setViewAddress(c.getViewAddress(view));
d.setViewAddress(d.getViewAddress(view));
}
public void next() {
this.a.next();
this.b.next();
this.c.next();
this.d.next();
}
}
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation marks a class as a mapped object, which will go under bytecode
* transformation at runtime. Mapped objects cannot be instantiated directly; a data
* buffer must be mapped first and the mapped object instance will then be used as a
* view on top of the buffer. Instead of a separate instance per "element" in the buffer,
* only a single instance is used to manage everything. See {@link MappedObject}
* for API details and org.lwjgl.test.mapped.TestMappedObject for examples.
* <p/>
* The instance fields of the annotated class should only be limited to primitive types or
* {@link java.nio.ByteBuffer}. Static fields are supported and they can have any type.
* <p/>
* The purpose of mapped objects is to reduce the memory requirements required for the type
* of data that are often used in OpenGL/OpenCL programming, while at the same time enabling
* clean Java code. There are also performance benefits related to not having to copy data
* between buffers and Java objects and the removal of bounds checking when accessing
* buffer data.
*
* @author Riven
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MappedType {
/**
* The number of bytes to add to the total byte size.
* SIZEOF will be calculated as <code>SIZEOF = max(field_offset + field_length) + padding</code>.
* <p/>
* Cannot be used with {@link #cacheLinePadding()}.
*
* @return the padding amount
*/
int padding() default 0;
/**
* When true, SIZEOF will be increased (if necessary) so that it's a multiple of the CPU cache line size.
* Additionally, {@link MappedObject#malloc(int)} on the mapped object type will automatically use
* {@link CacheUtil#createByteBuffer(int)} instead of the unaligned
* {@link org.lwjgl.BufferUtils#createByteBuffer(int)}.
* <p/>
* Cannot be used with {@link #padding()}.
*
* @return if cache-line padding should be applied
*
* @see CacheUtil
*/
boolean cacheLinePadding() default false;
/**
* The mapped data memory alignment, in bytes.
*
* @return the memory alignment
*/
int align() default 4;
/**
* When autoGenerateOffsets is true, byte offsets of the mapped fields will
* be generated automatically. This is convenient for packed data. For manually
* aligned data, autoGenerateOffsets must be set to false and the user needs
* to manually specify byte offsets using the {@link MappedField} annotation.
*
* @return true if automatic byte offset generation is required.
*/
boolean autoGenerateOffsets() default true;
}
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2002-2011 LWJGL Project
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjglx.util.mapped;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be used on long fields of {@link MappedObject} subclasses,
* to specify that the long value should be interpreted as a pointer. This
* will determine the actual byte size of the field at runtime (4 or 8 bytes).
*
* @author Spasi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Pointer {
}