diff --git a/.classpath b/.classpath
index 10f8ce2..6f1d0cc 100644
--- a/.classpath
+++ b/.classpath
@@ -91,10 +91,5 @@
-
-
-
-
-
diff --git a/src/module-info.java b/src/module-info.java
index 97e4096..1c5b4fc 100644
--- a/src/module-info.java
+++ b/src/module-info.java
@@ -8,9 +8,9 @@ open module org.atriasoft.gale {
exports org.atriasoft.gale.context;
//exports org.atriasoft.gale.context.JOGL;
exports org.atriasoft.gale.context.LWJG_AWT;
- exports org.atriasoft.gale.event;
exports org.atriasoft.gale.key;
exports org.atriasoft.gale.resource;
+
requires transitive org.atriasoft.etk;
//requires transitive vecmath;
@@ -20,8 +20,8 @@ open module org.atriasoft.gale {
requires transitive org.lwjgl.glfw.natives;
requires transitive org.lwjgl.assimp;
requires transitive org.lwjgl.assimp.natives;
-// requires transitive org.lwjgl.openal;
-// requires transitive org.lwjgl.openal.natives;
+ // requires transitive org.lwjgl.openal;
+ // requires transitive org.lwjgl.openal.natives;
requires transitive org.lwjgl.stb;
requires transitive org.lwjgl.stb.natives;
requires transitive org.lwjgl.jawt;
@@ -29,9 +29,9 @@ open module org.atriasoft.gale {
requires transitive org.lwjgl.opengl;
requires transitive org.lwjgl.opengl.natives;
//requires org.lwjgl.openvr;
-
+
//requires transitive jogamp.fat;
-
+
requires transitive java.desktop;
requires transitive pngdecoder;
requires transitive lwjgl3.awt;
diff --git a/src/org/atriasoft/gale/Dimension.java b/src/org/atriasoft/gale/Dimension.java
new file mode 100644
index 0000000..24bade2
--- /dev/null
+++ b/src/org/atriasoft/gale/Dimension.java
@@ -0,0 +1,347 @@
+/** @file
+ * @author Edouard DUPIN
+ * @copyright 2011, Edouard DUPIN, all right reserved
+ * @license MPL v2.0 (see license file)
+ */
+package org.atriasoft.gale;
+
+import org.atriasoft.etk.math.Vector2f;
+import org.atriasoft.gale.internal.Log;
+
+/**
+ * @brief in the dimention class we store the data as the more usefull unit (pixel)
+ * but one case need to be dynamic the %, then when requested in % the register the % value
+ */
+public class Dimension {
+ private final static Vector2f ratio = new Vector2f(9999999, 888888);
+ private final static Vector2f invRatio = new Vector2f(1, 1);
+ private final static Dimension windowsSize = new Dimension(new Vector2f(9999999, 888888), Distance.PIXEL);
+
+ public final static float INCH_TO_MILLIMETER = 1.0f / 25.4f;
+ public final static float FOOT_TO_MILLIMETER = 1.0f / 304.8f;
+ public final static float METER_TO_MILLIMETER = 1.0f / 1000.0f;
+ public final static float CENTIMETER_TO_MILLIMETER = 1.0f / 10.0f;
+ public final static float KILOMETER_TO_MILLIMETER = 1.0f / 1000000.0f;
+ public final static float MILLIMETER_TO_INCH = 25.4f;
+ public final static float MILLIMETER_TO_FOOT = 304.8f;
+ public final static float MILLIMETER_TO_METER = 1000.0f;
+ public final static float MILLIMETER_TO_CENTIMETER = 10.0f;
+ public final static float MILLIMETER_TO_KILOMETER = 1000000.0f;
+ /**
+ * @brief basic init
+ */
+ static {
+ final Dimension conversion = new Dimension(new Vector2f(72, 72), Distance.INCH);
+ ratio.set(conversion.getMillimeter());
+ invRatio.setValue(1.0f / ratio.x, 1.0f / ratio.y);
+ windowsSize.set(new Vector2f(200, 200), Distance.PIXEL);
+ }
+
+ /**
+ * @brief get the Windows diagonal size in the request unit
+ * @param[in] type Unit type requested.
+ * @return the requested size
+ */
+ public static float getWindowsDiag(final Distance _type) {
+ final Vector2f size = getWindowsSize(_type);
+ return size.length();
+ }
+
+ /**
+ * @brief get the Windows size in the request unit
+ * @param[in] type Unit type requested.
+ * @return the requested size
+ */
+ public static Vector2f getWindowsSize(final Distance _type) {
+ return windowsSize.get(_type);
+ }
+
+ /**
+ * @brief set the Milimeter ratio for calculation
+ * @param[in] Ratio Milimeter ration for the screen calculation interpolation
+ * @param[in] type Unit type requested.
+ * @note: same as @ref setPixelPerInch (internal manage convertion)
+ */
+ public static void setPixelRatio(final Vector2f _ratio, final Distance _type) {
+ Log.info("Set a new screen ratio for the screen : ratio=" + _ratio + " type=" + _type);
+ final Dimension conversion = new Dimension(_ratio, _type);
+ Log.info(" == > " + conversion);
+ ratio.set(conversion.getMillimeter());
+ invRatio.setValue(1.0f / ratio.x, 1.0f / ratio.y);
+ Log.info("Set a new screen ratio for the screen : ratioMm=" + ratio);
+ }
+
+ /**
+ * @brief set the current Windows size
+ * @param[in] size size of the current windows in pixel.
+ */
+ public static void setPixelWindowsSize(final Vector2f _size) {
+ windowsSize.set(_size);
+ Log.verbose("Set a new Windows property size " + windowsSize + "px");
+ }
+
+ private Vector2f size = new Vector2f(0, 0);
+ private Distance type = Distance.PIXEL;
+
+ /**
+ * @brief Constructor (default :0,0 mode pixel)
+ */
+ public Dimension() {
+
+ }
+
+ /**
+ * @brief Constructor
+ * @param[in] _config dimension configuration.
+ */
+ public Dimension(final String _config) {
+ set(_config);
+ }
+
+ /**
+ * @brief Constructor
+ * @param[in] _size Requested dimension
+ * @param[in] _type Unit of the Dimension
+ */
+ public Dimension(final Vector2f _size) {
+ set(_size, Distance.PIXEL);
+ }
+
+ public Dimension(final Vector2f _size, final Distance _type) {
+ set(_size, _type);
+ }
+
+ /*****************************************************
+ * isEqual
+ *****************************************************/
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof Dimension)) {
+ return false;
+ }
+ final Dimension other = (Dimension) obj;
+ return this.size.equals(other.size) && this.type == other.type;
+ }
+
+ /**
+ * @brief get the current dimention in requested type
+ * @param[in] _type Type of unit requested.
+ * @return dimention requested.
+ */
+ public Vector2f get(final Distance _type) {
+ switch (_type) {
+ case POURCENT:
+ return getPourcent();
+ case PIXEL:
+ return getPixel();
+ case METER:
+ return getMeter();
+ case CENTIMETER:
+ return getCentimeter();
+ case MILLIMETER:
+ return getMillimeter();
+ case KILOMETER:
+ return getKilometer();
+ case INCH:
+ return getInch();
+ case FOOT:
+ return getFoot();
+ }
+ return new Vector2f(0, 0);
+ }
+
+ /**
+ * @brief get the current dimention in Centimeter
+ * @return dimention in Centimeter
+ */
+ public Vector2f getCentimeter() {
+ return getMillimeter().multiplyNew(MILLIMETER_TO_CENTIMETER);
+ }
+
+ /**
+ * @brief get the current dimention in Foot
+ * @return dimention in Foot
+ */
+ public Vector2f getFoot() {
+ return getMillimeter().multiplyNew(MILLIMETER_TO_FOOT);
+ }
+
+ /**
+ * @brief get the current dimention in Inch
+ * @return dimention in Inch
+ */
+ public Vector2f getInch() {
+ return getMillimeter().multiplyNew(MILLIMETER_TO_INCH);
+ }
+
+ /**
+ * @brief get the current dimention in Kilometer
+ * @return dimention in Kilometer
+ */
+ public Vector2f getKilometer() {
+ return getMillimeter().multiplyNew(MILLIMETER_TO_KILOMETER);
+ }
+
+ /**
+ * @brief get the current dimention in Meter
+ * @return dimention in Meter
+ */
+ public Vector2f getMeter() {
+ return getMillimeter().multiplyNew(MILLIMETER_TO_METER);
+ }
+
+ /**
+ * @brief get the current dimention in Millimeter
+ * @return dimention in Millimeter
+ */
+ public Vector2f getMillimeter() {
+ return new Vector2f(getPixel().x * invRatio.x, getPixel().y * invRatio.y);
+ }
+
+ /**
+ * @brief get the current dimention in pixel
+ * @return dimention in Pixel
+ */
+ public Vector2f getPixel() {
+ if (this.type != Distance.POURCENT) {
+ return this.size;
+ } else {
+ final Vector2f windDim = windowsSize.getPixel();
+ final Vector2f res = new Vector2f(windDim.x * this.size.x, windDim.y * this.size.y);
+ //GALE_DEBUG("Get % : " + m_data + " / " + windDim + " == > " + res);
+ return res;
+ }
+ }
+
+ /**
+ * @brief get the current dimention in Pourcent
+ * @return dimention in Pourcent
+ */
+ public Vector2f getPourcent() {
+ if (this.type != Distance.POURCENT) {
+ final Vector2f windDim = windowsSize.getPixel();
+ //GALE_DEBUG(" windows dimention : " /*+ windowsSize*/ + " == > " + windDim + "px"); // ==> infinite loop ...
+ //printf(" windows dimention : %f,%f", windDim.x(),windDim.y());
+ //printf(" data : %f,%f", m_data.x(),m_data.y());
+ return new Vector2f((this.size.x / windDim.x) * 100.0f, (this.size.y / windDim.y) * 100.0f);
+ }
+ return new Vector2f(this.size.x * 100.0f, this.size.y * 100.0f);
+ };
+
+ /**
+ * @breif get the dimension type
+ * @return the type
+ */
+ public Distance getType() {
+ return this.type;
+ }
+
+ /*****************************************************
+ * assigment
+ *****************************************************/
+ public Dimension set(final Dimension _obj) {
+ if (this != _obj) {
+ this.size = _obj.size;
+ this.type = _obj.type;
+ }
+ return this;
+ }
+
+ /**
+ * @brief set the current dimention in requested type
+ * @param[in] _config dimension configuration.
+ */
+ private void set(String _config) {
+ this.size.setValue(0, 0);
+ this.type = Distance.PIXEL;
+ Distance type = Distance.PIXEL;
+ if (_config.endsWith("%") == true) {
+ type = Distance.POURCENT;
+ _config = _config.substring(0, _config.length() - 1);
+ } else if (_config.endsWith("px") == true) {
+ type = Distance.PIXEL;
+ _config = _config.substring(0, _config.length() - 2);
+ } else if (_config.endsWith("ft") == true) {
+ type = Distance.FOOT;
+ _config = _config.substring(0, _config.length() - 2);
+ } else if (_config.endsWith("in") == true) {
+ type = Distance.INCH;
+ _config = _config.substring(0, _config.length() - 2);
+ } else if (_config.endsWith("km") == true) {
+ type = Distance.KILOMETER;
+ _config = _config.substring(0, _config.length() - 2);
+ } else if (_config.endsWith("mm") == true) {
+ type = Distance.MILLIMETER;
+ _config = _config.substring(0, _config.length() - 2);
+ } else if (_config.endsWith("cm") == true) {
+ type = Distance.CENTIMETER;
+ _config = _config.substring(0, _config.length() - 2);
+ } else if (_config.endsWith("m") == true) {
+ type = Distance.METER;
+ _config = _config.substring(0, _config.length() - 1);
+ } else {
+ Log.critical("Can not parse dimention : '" + _config + "'");
+ return;
+ }
+ final Vector2f tmp = Vector2f.valueOf(_config);
+ set(tmp, type);
+ Log.verbose(" config dimention : \"" + _config + "\" == > " + this);
+ }
+
+ public void set(final Vector2f _size) {
+ this.size = _size;
+ this.type = Distance.PIXEL;
+ }
+
+ /**
+ * @brief set the current dimention in requested type
+ * @param[in] _size Dimention to set
+ * @param[in] _type Type of unit requested.
+ */
+ public void set(final Vector2f _size, final Distance _type) {
+ this.size = _size;
+ this.type = _type;
+ }
+
+ /**
+ * @brief string cast :
+ */
+ @Override
+ public String toString() {
+ String str = get(getType()).toString();
+ switch (getType()) {
+ case POURCENT:
+ str += "%";
+ break;
+ case PIXEL:
+ str += "px";
+ break;
+ case METER:
+ str += "m";
+ break;
+ case CENTIMETER:
+ str += "cm";
+ break;
+ case MILLIMETER:
+ str += "mm";
+ break;
+ case KILOMETER:
+ str += "km";
+ break;
+ case INCH:
+ str += "in";
+ break;
+ case FOOT:
+ str += "ft";
+ break;
+ }
+ return str;
+ }
+
+}
diff --git a/src/org/atriasoft/gale/Distance.java b/src/org/atriasoft/gale/Distance.java
new file mode 100644
index 0000000..265de8d
--- /dev/null
+++ b/src/org/atriasoft/gale/Distance.java
@@ -0,0 +1,12 @@
+package org.atriasoft.gale;
+
+public enum Distance {
+ POURCENT,
+ PIXEL,
+ METER,
+ CENTIMETER,
+ MILLIMETER,
+ KILOMETER,
+ INCH,
+ FOOT;
+}
diff --git a/src/org/atriasoft/gale/backend3d/OpenGL.java b/src/org/atriasoft/gale/backend3d/OpenGL.java
index 9d0a143..cfcce02 100644
--- a/src/org/atriasoft/gale/backend3d/OpenGL.java
+++ b/src/org/atriasoft/gale/backend3d/OpenGL.java
@@ -3,12 +3,21 @@ package org.atriasoft.gale.backend3d;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
+import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.atriasoft.etk.Color;
+import org.atriasoft.etk.math.Matrix4f;
+import org.atriasoft.etk.math.Vector2f;
+import org.atriasoft.etk.math.Vector2i;
+import org.atriasoft.etk.math.Vector3f;
+import org.atriasoft.etk.math.Vector3i;
+import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
@@ -16,45 +25,18 @@ import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL40;
-import org.atriasoft.etk.math.Matrix4f;
-import org.atriasoft.etk.math.Vector2f;
-import org.atriasoft.etk.math.Vector2i;
-import org.atriasoft.etk.math.Vector3f;
-import org.atriasoft.etk.math.Vector3i;
-import org.atriasoft.etk.Color;
-import org.atriasoft.gale.internal.Log;
public class OpenGL {
- private OpenGL() {}
- static final boolean DEBUG = false; // TODO externalize this ...
- static final boolean CHECKERROROPENGL = false; // TODO externalize this ...
- static final boolean DIRECT_MODE = false; // TODO externalize this ...
-
- public static void checkGlError(String op) {
-// int localLine = Thread.currentThread().getStackTrace()[2].getLineNumber();
-// if (CHECKERROROPENGL == true) {
-// boolean hasError = false;
-// for (int error = GL11.glGetError(); error!=null; error = GL11.glGetError()) {
-// Log.error("after " + op + "():" + localLine + " glError(" + error + ")");
-// hasError = true;
-// }
-// if (hasError == true) {
-// Log.critical("plop");
-// }
-// for (GLint error = glGetError(); error; error = glGetError()) {
-// Log.error("after " + op + "() glError (" + error + ")");
-// }
-// }
+ public static enum ClearFlag {
+ clearFlag_colorBuffer, //!< Indicates the buffers currently enabled for color writing.
+ clearFlag_depthBuffer, //!< Indicates the depth buffer.
+ clearFlag_stencilBuffer //!< Indicates the stencil buffer.
}
-
- private static List matrixList = new ArrayList();
- private static Matrix4f matrixCamera = new Matrix4f();
- private static int programId = 0;
-
+
// We map all the flag, but not all is supported by all platform...
public static enum Flag {
flag_blend, //!< If enabled, blend the computed fragment color values with the values in the color buffers.
- //See glBlendFunc.
+ //See glBlendFunc.
flag_clipDistanceI, //!< If enabled, clip geometry against user-defined half space i.
flag_colorLogigOP, //!< If enabled, apply the currently selected logical operation to the computed fragment color and color buffer values. See glLogicOp.
flag_cullFace, //!< If enabled, cull polygons based on their winding in window coordinates. See glCullFace.
@@ -84,7 +66,8 @@ public class OpenGL {
flag_alphaTest, //!<
flag_fog,
flag_back
- };
+ }
+
public enum RenderMode {
point,
line,
@@ -96,33 +79,50 @@ public class OpenGL {
quad, //!< Not supported in OpenGL-ES2
quadStrip, //!< Not supported in OpenGL-ES2
polygon //!< Not supported in OpenGL-ES2
- };
-
- private static final Map CONVERT_RENDER_MODE = Map.of(
- RenderMode.point, GL11.GL_POINTS,
- RenderMode.line, GL11.GL_LINES,
- RenderMode.lineStrip, GL11.GL_LINE_STRIP,
- RenderMode.lineLoop, GL11.GL_LINE_LOOP,
- RenderMode.triangle, GL11.GL_TRIANGLES,
- RenderMode.triangleStrip, GL11.GL_TRIANGLE_STRIP,
- RenderMode.triangleFan, GL11.GL_TRIANGLE_FAN,
- RenderMode.quad, GL11.GL_QUADS,
- RenderMode.quadStrip, GL11.GL_QUAD_STRIP,
- RenderMode.polygon, GL11.GL_POLYGON
- );
- private static Map basicFlag;
+ }
+
+ /* Shader wrapping : */
+ public static enum ShaderType {
+ vertex,
+ fragment
+ }
+
public static class StateFlag {
public boolean current = false;
public boolean mustBeSet = false;
}
- private static boolean flagsStatesChange = false;
- private static Map flagsStates = new HashMap();
-
+
public enum Usage {
streamDraw,
staticDraw,
dynamicDraw
}
+
+ public static final int GL_RGB = GL11.GL_RGB;
+ public static final int GL_RGBA = GL11.GL_RGBA;
+
+ public static final int GL_UNSIGNED_BYTE = GL11.GL_UNSIGNED_BYTE;
+
+ public static final int GL_TEXTURE_2D = GL11.GL_TEXTURE_2D;
+
+ static final boolean DEBUG = false; // TODO externalize this ...
+
+ static final boolean CHECKERROROPENGL = false; // TODO externalize this ...
+
+ static final boolean DIRECT_MODE = false; // TODO externalize this ...;
+
+ private static List matrixList = new ArrayList<>();
+
+ private static Matrix4f matrixCamera = new Matrix4f();
+ private static int programId = 0;
+
+ private static final Map CONVERT_RENDER_MODE = Map.of(RenderMode.point, GL11.GL_POINTS, RenderMode.line, GL11.GL_LINES, RenderMode.lineStrip, GL11.GL_LINE_STRIP,
+ RenderMode.lineLoop, GL11.GL_LINE_LOOP, RenderMode.triangle, GL11.GL_TRIANGLES, RenderMode.triangleStrip, GL11.GL_TRIANGLE_STRIP, RenderMode.triangleFan, GL11.GL_TRIANGLE_FAN,
+ RenderMode.quad, GL11.GL_QUADS, RenderMode.quadStrip, GL11.GL_QUAD_STRIP, RenderMode.polygon, GL11.GL_POLYGON);
+ private static Map basicFlag;;
+
+ private static boolean flagsStatesChange = false;
+ private static Map flagsStates = new HashMap<>();
public static Map convertUsage;
static {
flagsStates.put(Flag.flag_blend, new StateFlag());
@@ -155,7 +155,7 @@ public class OpenGL {
flagsStates.put(Flag.flag_alphaTest, new StateFlag());
flagsStates.put(Flag.flag_fog, new StateFlag());
flagsStates.put(Flag.flag_back, new StateFlag());
- basicFlag = new HashMap();
+ basicFlag = new HashMap<>();
basicFlag.put(Flag.flag_blend, GL11.GL_BLEND);
// basicFlag.put(Flag.flag_clipDistanceI, GL_CLIP_DISTANCE0);
// basicFlag.put(Flag.flag_colorLogigOP, GL_COLOR_LOGIC_OP);
@@ -186,247 +186,165 @@ public class OpenGL {
// basicFlag.put(Flag.flag_alphaTest, GLALPHATEST);
// basicFlag.put(Flag.flag_fog, GLFOG);
basicFlag.put(Flag.flag_back, GL11.GL_BACK);
- convertUsage = new HashMap();
+ convertUsage = new HashMap<>();
convertUsage.put(Usage.streamDraw, GL20.GL_STREAM_DRAW);
convertUsage.put(Usage.staticDraw, GL20.GL_STATIC_DRAW);
convertUsage.put(Usage.dynamicDraw, GL20.GL_DYNAMIC_DRAW);
}
- private static void clearFlagState() {
- for (Map.Entry elem: flagsStates.entrySet()) {
- elem.getValue().current = false;
- elem.getValue().mustBeSet = false;
+ private static Map threadHasContext = new HashMap<>();
+
+ private static final Map BASIC_FLAG_CLEAR = Map.of(ClearFlag.clearFlag_colorBuffer, GL11.GL_COLOR_BUFFER_BIT, ClearFlag.clearFlag_depthBuffer, GL11.GL_DEPTH_BUFFER_BIT,
+ ClearFlag.clearFlag_stencilBuffer, GL11.GL_STENCIL_BUFFER_BIT);
+
+ /**
+ * @brief enable Texture on the system
+ * @param flagID The flag requested
+ */
+ public static void activeTexture(final int flagID) {
+ if (programId >= 0) {
+ GL13.glActiveTexture(flagID);
+ checkGlError("glActiveTexture");
+ } else if (DEBUG) {
+ Log.error("try to bind texture with no program set");
}
}
- public static void resetFlagState() {
- for (Map.Entry elem: flagsStates.entrySet()) {
- elem.getValue().mustBeSet = false;
- }
- flagsStatesChange = true;
+
+ public static boolean bindBuffer(final int bufferId) {
+ GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, bufferId);
+ checkGlError("glBindBuffer");
+ return true;
}
- private static Map threadHasContext = new HashMap();
- /**
- * @brief Get the current thread context status.
- * @return true The threflagsStates.putn acces to openGL.flagsStates.put(Flag.@return false The Thread Can not acces to OpenGL.
- */
- public static boolean hasContext() {
- long curentThreadId = Thread.currentThread().getId();
- if (threadHasContext.containsKey(curentThreadId) == false) {
- return false;
- }
- return threadHasContext.get(curentThreadId);
+
+ public static void bindTexture2D(final int texId) {
+ GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId);
}
- /**
- * @brief must be called by the thread that has openGl context to notify the system
- * @note Call @ref gale::openGL::threadHasNoMoreContext when ended
- */
- public static void threadHasContext() {
- long curentThreadId = Thread.currentThread().getId();
- threadHasContext.put(curentThreadId, true);
+
+ public static boolean bufferData(final Color[] data, final Usage usage) {
+ final FloatBuffer buffer = storeDataInFloatBuffer(data);
+ GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage));
+ checkGlError("glBufferData");
+ return true;
}
- /**
- * @brief At the end of the thread exection, set the thead has no more openGL cotext
- */
- public static void threadHasNoMoreContext() {
- long curentThreadId = Thread.currentThread().getId();
- threadHasContext.remove(curentThreadId);
+
+ public static boolean bufferData(final float[] data, final Usage usage) {
+ final FloatBuffer buffer = storeDataInFloatBuffer(data);
+ GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage));
+ checkGlError("glBufferData");
+ return true;
}
- /**
- * @brief Lock the openGL context for one user only == > better to keep flags and other things ...
- */
- public static void lock() {
- //mutexOpenGl().lock();
- matrixList.clear();
- Matrix4f tmpMat = Matrix4f.identity();
- matrixList.add(tmpMat);
- matrixCamera.setIdentity();
- clearFlagState();
- programId = -1;
+
+ public static boolean bufferData(final int[] data, final Usage usage) {
+ final IntBuffer buffer = storeDataInFloatBuffer(data);
+ GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage));
+ checkGlError("glBufferData");
+ return true;
}
- /**
- * @brief Un-lock the openGL context for an other user...
- */
- public static void unLock() {
- //mutexOpenGl().unLock();
+
+ public static boolean bufferData(final Vector2f[] data, final Usage usage) {
+ final FloatBuffer buffer = storeDataInFloatBuffer(data);
+ GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage));
+ checkGlError("glBufferData");
+ return true;
}
- /**
- * @brief When you will done an opengl rendering, you might call this reset matrix first. It remove all the stach of the matrix pushed.
- * @param newOne the default matrix that might be set for the graphic card for renderer. if too more pop will be done, this is the last that mmight survived
- */
- public static void setBasicMatrix( Matrix4f newOne) {
- if (matrixList.size()!=1) {
- Log.error("matrix is not corect size in the stack : " + matrixList.size());
- }
- matrixList.clear();
- matrixList.add(newOne);
+
+ public static boolean bufferData(final Vector3f[] data, final Usage usage) {
+ final FloatBuffer buffer = storeDataInFloatBuffer(data);
+ GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, convertUsage.get(usage));
+ checkGlError("glBufferData");
+ return true;
}
- /**
- * @brief this funtion configure the current use matrix for the renderer (call @ref Push before, and @ref Pop when no more needed).
- * @param newOne The new current matrix use for the render.
- * @note We did not use opengl standard system, due to the fact that is not supported in opengl ES-2
- */
- public static void setMatrix( Matrix4f newOne) {
- if (matrixList.size() == 0) {
- Log.error("set matrix list is not corect size in the stack : " + matrixList.size());
- matrixList.add(newOne);
- return;
- }
- matrixList.set(matrixList.size()-1, newOne);
+
+ public static void checkGlError(final String op) {
+ // int localLine = Thread.currentThread().getStackTrace()[2].getLineNumber();
+ // if (CHECKERROROPENGL == true) {
+ // boolean hasError = false;
+ // for (int error = GL11.glGetError(); error!=null; error = GL11.glGetError()) {
+ // Log.error("after " + op + "():" + localLine + " glError(" + error + ")");
+ // hasError = true;
+ // }
+ // if (hasError == true) {
+ // Log.critical("plop");
+ // }
+ // for (GLint error = glGetError(); error; error = glGetError()) {
+ // Log.error("after " + op + "() glError (" + error + ")");
+ // }
+ // }
}
- /**
- * @brief store current matrix in the matrix stack.
- */
- public static void push() {
- if (matrixList.size() == 0) {
- Log.error("set matrix list is not corect size in the stack : " + matrixList.size());
- matrixList.add(Matrix4f.identity());
- return;
- }
- Matrix4f tmp = matrixList.get(matrixList.size()-1);
- matrixList.add(tmp);
- }
- /**
- * @brief remove the current matrix and get the last one from the matrix stack.
- */
- public static void pop() {
- if (matrixList.size() <= 1) {
- Log.error("set matrix list is not corect size in the stack : " + matrixList.size());
- matrixList.clear();
- matrixList.add(Matrix4f.identity());
- matrixCamera.setIdentity();
- return;
- }
- matrixList.remove(matrixList.size()-1);
- matrixCamera.setIdentity();
- }
-
- /**
- * @brief get a reference on the current matrix destinate to opengl renderer.
- * @return The requested matrix.
- */
- public static Matrix4f getMatrix() {
- if (matrixList.size() == 0) {
- Log.error("set matrix list is not corect size in the stack : " + matrixList.size());
- matrixList.add(Matrix4f.identity());
- }
- return matrixList.get(matrixList.size()-1);
- }
- /**
- * @brief get a reference on the current matrix camera destinate to opengl renderer.
- * @return The requested matrix.
- */
- public static Matrix4f getCameraMatrix(){
- return matrixCamera;
- }
-
- /**
- * @brief set a reference on the current camera to opengl renderer.
- * @param newOne The requested matrix.
- */
- public static void setCameraMatrix( Matrix4f newOne){
- matrixCamera = newOne;
- }
- /**
- * @brief
- */
- public static void finish(){
- programId = -1;
- }
- /**
- * @brief
- */
- public static void flush(){
- programId = -1;
- GL11.glFlush();
- //checkGlError("glFlush");
- //Log.info("========================" );
- //Log.info("== FLUSH OPEN GL ==" );
- //Log.info("========================");
- }
-
- /**
- * @brief
- */
- public static void swap(){
-
- }
- public static void setViewPort( Vector2i start, Vector2i stop){
- //Log.info("setViewport " + start + " " + stop);
- GL11.glViewport(start.x, start.y, stop.x, stop.y);
- checkGlError("glViewport");
- }
- public static void setViewPort( Vector2f start, Vector2f stop){
- //Log.info("setViewport " + start + " " + stop);
- GL11.glViewport((int)start.x, (int)start.y, (int)stop.x, (int)stop.y);
- checkGlError("glViewport");
- }
-
- /**
- * @brief Specifies the clear color value When clear is requested
- * @param value to set [0..1]
- */
- public static void clearColor(Color color) {
- GL11.glClearColor(color.r, color.g, color.b, color.a);
- checkGlError("glClearColor");
- }
- /**
- * @brief Specifies the depth value used when the depth buffer is cleared. The initial value is 1.
- * @param value to set [0..1]
- */
- public static void clearDepth(float value) {
- GL11.glClearDepth(value);
- checkGlError("glClearDepth");
- }
- /**
- * @brief Specifies the index used by clear to clear the stencil buffer. s is masked with 2 m - 1 , where m is the number of bits in the stencil buffer.
- * @param value
- */
- public static void clearStencil(int value) {
- GL11.glClearStencil(value);
- checkGlError("glClearStencil");
- }
-
-
- public static enum ClearFlag {
- clearFlag_colorBuffer, //!< Indicates the buffers currently enabled for color writing.
- clearFlag_depthBuffer, //!< Indicates the depth buffer.
- clearFlag_stencilBuffer //!< Indicates the stencil buffer.
- }
- private static final Map BASIC_FLAG_CLEAR = Map.of(
- ClearFlag.clearFlag_colorBuffer, GL11.GL_COLOR_BUFFER_BIT,
- ClearFlag.clearFlag_depthBuffer, GL11.GL_DEPTH_BUFFER_BIT,
- ClearFlag.clearFlag_stencilBuffer, GL11.GL_STENCIL_BUFFER_BIT );
/**
* @brief clear sets the bitplane area of the window to values previously selected by clearColor, clearDepth, and clearStencil. Multiple color buffers can be cleared simultaneously by selecting more than one buffer at a time using drawBuffer.
* The pixel ownership test, the scissor test, dithering, and the buffer writemasks affect the operation of clear. The scissor box bounds the cleared region. Alpha function, blend function, logical operation, stenciling, texture mapping, and depth-buffering are ignored by clear.
* @param flags This is the bitwise OR of several values indicating which buffer is to be cleared.
*/
- public static void clear(ClearFlag flag){
+ public static void clear(final ClearFlag flag) {
GL11.glClear(BASIC_FLAG_CLEAR.get(flag));
checkGlError("glClear");
}
-
+
/**
- * @brief enable a flag on the system
- * @param flagID The flag requested
+ * @brief Specifies the clear color value When clear is requested
+ * @param value to set [0..1]
*/
- public static void enable(Flag flagID){
- //Log.info("Enable : " + flagID);
- if (DIRECT_MODE) {
- GL11.glEnable(basicFlag.get(flagID));
- checkGlError("glEnable");
- } else {
- //Log.debug("Enable FLAGS = " + this.flagsStates);
- flagsStates.get(flagID).mustBeSet = true;
- flagsStatesChange = true;
- //Log.debug(" == >" + this.flagsStates);
+ public static void clearColor(final Color color) {
+ GL11.glClearColor(color.r, color.g, color.b, color.a);
+ checkGlError("glClearColor");
+ }
+
+ /**
+ * @brief Specifies the depth value used when the depth buffer is cleared. The initial value is 1.
+ * @param value to set [0..1]
+ */
+ public static void clearDepth(final float value) {
+ GL11.glClearDepth(value);
+ checkGlError("glClearDepth");
+ }
+
+ private static void clearFlagState() {
+ for (final Map.Entry elem : flagsStates.entrySet()) {
+ elem.getValue().current = false;
+ elem.getValue().mustBeSet = false;
}
}
+
+ /**
+ * @brief Specifies the index used by clear to clear the stencil buffer. s is masked with 2 m - 1 , where m is the number of bits in the stencil buffer.
+ * @param value
+ */
+ public static void clearStencil(final int value) {
+ GL11.glClearStencil(value);
+ checkGlError("glClearStencil");
+ }
+
+ public static boolean deleteBuffers(final int[] buffers) {
+ if (buffers.length == 0) {
+ Log.warning("try to delete vector buffer with size 0");
+ return true;
+ }
+ // TODO Check if we are in the correct thread
+ GL20.glDeleteBuffers(buffers);
+ checkGlError("glDeleteBuffers");
+ for (int iii = 0; iii < buffers.length; iii++) {
+ buffers[iii] = -1;
+ }
+ return true;
+ }
+
+ /**
+ * @brief disable Texture on the system
+ * @param flagID The flag requested
+ */
+ // TODO rename Disable
+ public static void desActiveTexture(final int flagID) {
+ // if (this.programId >= 0) {
+ //
+ // }
+ }
+
/**
* @brief disable a flag on the system
* @param flagID The flag requested
*/
- public static void disable(Flag flagID) {
+ public static void disable(final Flag flagID) {
//Log.info("Disable : " + flagID);
if (DIRECT_MODE) {
GL11.glDisable(basicFlag.get(flagID));
@@ -438,96 +356,405 @@ public class OpenGL {
//Log.debug(" == >" + this.flagsStates);
}
}
- /**
- * @brieg update all the internal flag needed to be set from tre previous element set ...
- */
- public static void updateAllFlags() {
- if (DIRECT_MODE) {
- return;
- }
- // check if flags has change :
- if (flagsStatesChange == false) {
- return;
- }
- flagsStatesChange = false;
- for (Map.Entry elem: flagsStates.entrySet()) {
- StateFlag value = elem.getValue();
- if (value.current != value.mustBeSet) {
- value.current = value.mustBeSet;
- if (value.current == true) {
- GL11.glEnable(basicFlag.get(elem.getKey()));
- checkGlError("glEnable");
- //Log.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey()));
- } else {
- GL11.glDisable(basicFlag.get(elem.getKey()));
- checkGlError("glDisable");
- //Log.info(" disable : " + elem.getKey());
- }
- }
- }
- }
- /**
- * @brief enable Texture on the system
- * @param flagID The flag requested
- */
- public static void activeTexture(int flagID) {
- if (programId >= 0) {
- GL13.glActiveTexture(flagID);
- checkGlError("glActiveTexture");
- } else {
- if (DEBUG) {
- Log.error("try to bind texture with no program set");
- }
- }
- }
- /**
- * @brief disable Texture on the system
- * @param flagID The flag requested
- */
- // TODO rename Disable
- public static void desActiveTexture(int flagID) {
-// if (this.programId >= 0) {
-//
-// }
- }
-
+
/**
* @brief draw a specific array == > this enable mode difference ...
*/
- public static void drawArrays(RenderMode mode, int first, int count) {
+ public static void drawArrays(final RenderMode mode, final int first, final int count) {
if (programId >= 0) {
updateAllFlags();
GL20.glDrawArrays(CONVERT_RENDER_MODE.get(mode), first, count);
checkGlError("glDrawArrays");
}
}
-// public static void drawElements(RenderMode mode, List indices) {
-// if (this.programId >= 0) {
-// updateAllFlags();
-// //Log.debug("Request draw of " + indices.size() + "elements");
-// GL15.glDrawElements(convertRenderMode.get(mode), indices.size(), GL11.GL_UNSIGNED_INT);//, &indices[0]);
-// checkGlError("glDrawElements");
-// }
-// }
-// public static void drawElements16(RenderMode mode, List indices) {
-// if (this.programId >= 0) {
-// updateAllFlags();
-// GL20.glDrawElements(convertRenderMode.get(mode), indices.size(), GLUNSIGNEDSHORT, &indices[0]);
-// checkGlError("glDrawElements");
-// }
-// }
-// public static void drawElements8 (enum renderMode mode, List indices) {
-// if (this.programId >= 0) {
-// updateAllFlags();
-// GL20.glDrawElements(convertRenderMode[int(mode)], indices.size(), GLUNSIGNEDBYTE, &indices[0]);
-// checkGlError("glDrawElements");
-// }
-// }
+
+ public static void drawElements(final RenderMode mode, final int vertexCount) {
+ GL11.glDrawElements(CONVERT_RENDER_MODE.get(mode), vertexCount, GL11.GL_UNSIGNED_INT, 0);
+ }
+
+ /**
+ * @brief enable a flag on the system
+ * @param flagID The flag requested
+ */
+ public static void enable(final Flag flagID) {
+ //Log.info("Enable : " + flagID);
+ if (DIRECT_MODE) {
+ GL11.glEnable(basicFlag.get(flagID));
+ checkGlError("glEnable");
+ } else {
+ //Log.debug("Enable FLAGS = " + this.flagsStates);
+ flagsStates.get(flagID).mustBeSet = true;
+ flagsStatesChange = true;
+ //Log.debug(" == >" + this.flagsStates);
+ }
+ }
+
+ /**
+ * @brief
+ */
+ public static void finish() {
+ programId = -1;
+ }
+
+ /**
+ * @brief
+ */
+ public static void flush() {
+ programId = -1;
+ GL11.glFlush();
+ //checkGlError("glFlush");
+ //Log.info("========================" );
+ //Log.info("== FLUSH OPEN GL ==" );
+ //Log.info("========================");
+ }
+
+ public static int genBuffers() {
+ return GL15.glGenBuffers();
+ }
+
+ public static boolean genBuffers(final int[] buffers) {
+ if (buffers.length == 0) {
+ Log.warning("try to generate vector buffer with size 0");
+ return true;
+ }
+ Log.info("Create N=" + buffers.length + " Buffer");
+ GL20.glGenBuffers(buffers);
+ checkGlError("glGenBuffers");
+ boolean hasError = false;
+ for (int iii = 0; iii < buffers.length; iii++) {
+ if (buffers[iii] == 0) {
+ Log.error("[" + iii + "] error to create a buffer id=" + buffers[iii]);
+ hasError = true;
+ }
+ }
+ return hasError;
+ }
+
+ /**
+ * @brief get a reference on the current matrix camera destinate to opengl renderer.
+ * @return The requested matrix.
+ */
+ public static Matrix4f getCameraMatrix() {
+ return matrixCamera;
+ }
+
+ /**
+ * @brief get a reference on the current matrix destinate to opengl renderer.
+ * @return The requested matrix.
+ */
+ public static Matrix4f getMatrix() {
+ if (matrixList.size() == 0) {
+ Log.error("set matrix list is not corect size in the stack : " + matrixList.size());
+ matrixList.add(Matrix4f.identity());
+ }
+ return matrixList.get(matrixList.size() - 1);
+ }
+
+ public static void glDeleteTextures(final int textureId) {
+ GL11.glDeleteTextures(textureId);
+ }
+
+ public static int glGenTextures() {
+ return GL11.glGenTextures();
+ }
+
+ public static void glTexImage2D(final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int sizeObject, final byte[] data) {
+ final ByteBuffer dataBuffer = ByteBuffer.wrap(data);
+ GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, internalFormat, width, height, border, format, sizeObject, dataBuffer);
+ }
+
+ public static void glTexImage2D(final int level, final int internalFormat, final int width, final int height, final int border, final int format, final int sizeObject, final ByteBuffer data) {
+ GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, internalFormat, width, height, border, format, sizeObject, data);
+ }
+
+ public static void glTexSubImage2D(final int level, final int xOffset, final int yOffset, final int width, final int height, final int format, final int sizeObject, final byte[] data) {
+ final ByteBuffer dataBuffer = ByteBuffer.wrap(data);
+ GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, xOffset, yOffset, width, height, format, sizeObject, dataBuffer);
+ }
+
+ public static void glTexSubImage2D(final int level, final int xOffset, final int yOffset, final int width, final int height, final int format, final int sizeObject, final ByteBuffer data) {
+ GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, xOffset, yOffset, width, height, format, sizeObject, data);
+ }
+
+ /**
+ * @brief Get the current thread context status.
+ * @return true The threflagsStates.putn acces to openGL.flagsStates.put(Flag.@return false The Thread Can not acces to OpenGL.
+ */
+ public static boolean hasContext() {
+ final long curentThreadId = Thread.currentThread().getId();
+ if (threadHasContext.containsKey(curentThreadId) == false) {
+ return false;
+ }
+ return threadHasContext.get(curentThreadId);
+ }
+
+ /**
+ * @brief Lock the openGL context for one user only == > better to keep flags and other things ...
+ */
+ public static void lock() {
+ //mutexOpenGl().lock();
+ matrixList.clear();
+ final Matrix4f tmpMat = Matrix4f.identity();
+ matrixList.add(tmpMat);
+ matrixCamera.setIdentity();
+ clearFlagState();
+ programId = -1;
+ }
+
+ /**
+ * @brief remove the current matrix and get the last one from the matrix stack.
+ */
+ public static void pop() {
+ if (matrixList.size() <= 1) {
+ Log.error("set matrix list is not corect size in the stack : " + matrixList.size());
+ matrixList.clear();
+ matrixList.add(Matrix4f.identity());
+ matrixCamera.setIdentity();
+ return;
+ }
+ matrixList.remove(matrixList.size() - 1);
+ matrixCamera.setIdentity();
+ }
+
+ public static boolean programAttach(final int prog, final int shader) {
+ if (prog < 0) {
+ Log.error("wrong program ID");
+ return false;
+ }
+ if (shader < 0) {
+ Log.error("wrong shader ID");
+ return false;
+ }
+ GL20.glAttachShader(prog, shader);
+ checkGlError("glAttachShader");
+ return true;
+ }
+
+ public static void programBindAttribute(final int prog, final int attribute, final String variableName) {
+ if (prog < 0) {
+ Log.error("wrong program ID");
+ return;
+ }
+ GL20.glBindAttribLocation(prog, attribute, variableName);
+ }
+
+ public static boolean programCompile(final int prog) {
+ if (prog < 0) {
+ Log.error("wrong program ID");
+ return false;
+ }
+ GL20.glLinkProgram(prog);
+ checkGlError("glLinkProgram");
+ GL20.glValidateProgram(prog);
+
+ // GLint linkStatus = GLFALSE;
+ // glGetProgramiv(GLint(prog), GLLINKSTATUS, linkStatus);
+ // checkGlError("glGetProgramiv");
+ // if (linkStatus != GLTRUE) {
+ // GLint bufLength = 0;
+ // this.bufferDisplayError[0] = '\0';
+ // glGetProgramInfoLog(GLint(prog), LOGOGLINTERNALBUFFERLEN, bufLength, this.bufferDisplayError);
+ // char tmpLog[256];
+ // int idOut=0;
+ // Log.error("Could not compile 'PROGRAM':");
+ // for (sizet iii=0; iii= 256) {
+ // tmpLog[idOut] = '\0';
+ // Log.error(" == > " + tmpLog);
+ // idOut=0;
+ // } else {
+ // idOut++;
+ // }
+ // if (this.bufferDisplayError[iii] == '\0') {
+ // break;
+ // }
+ // }
+ // if (idOut != 0) {
+ // tmpLog[idOut] = '\0';
+ // Log.error(" == > " + tmpLog);
+ // }
+ // return false;
+ // }
+ return true;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // -- Open GL program ...
+ // ------------------------------------------------------------------------------------
+ public static int programCreate() {
+ final int programId = GL20.glCreateProgram();
+ if (programId == 0) {
+ Log.error("program creation return error ...");
+ checkGlError("glCreateProgram");
+ return -1;
+ }
+ Log.debug("Create program with oglID=" + programId);
+ return programId;
+ }
+
+ public static boolean programDetach(final int prog, final int shader) {
+ if (prog < 0) {
+ Log.error("wrong program ID");
+ return false;
+ }
+ if (shader < 0) {
+ Log.error("wrong shader ID");
+ return false;
+ }
+ GL20.glDetachShader(prog, shader);
+ checkGlError("glDetachShader");
+ return true;
+ }
+
+ public static int programGetAttributeLocation(final int prog, final String name) {
+ if (prog < 0) {
+ Log.error("wrong program ID");
+ return -1;
+ }
+ if (name.length() == 0) {
+ Log.error("wrong name of attribure");
+ return -1;
+ }
+ final int val = GL20.glGetAttribLocation(prog, name);
+ if (val < 0) {
+ checkGlError("glGetAttribLocation");
+ Log.warning("glGetAttribLocation('" + name + "') = " + val);
+ return -1;
+ }
+ return val;
+ }
+
+ public static int programGetUniformLocation(final int prog, final String name) {
+ if (prog < 0) {
+ Log.error("wrong program ID");
+ return -1;
+ }
+ if (name.length() == 0) {
+ Log.error("wrong name of uniform");
+ return -1;
+ }
+ final int val = GL20.glGetUniformLocation(prog, name);
+ if (val == GL20.GL_INVALID_VALUE) {
+ checkGlError("glGetUniformLocation");
+ Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_VALUE");
+ } else if (val == GL20.GL_INVALID_OPERATION) {
+ checkGlError("glGetUniformLocation");
+ Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_OPERATION");
+ } else if (val < 0) {
+ checkGlError("glGetUniformLocation");
+ Log.warning("glGetUniformLocation('" + name + "') = " + val);
+ }
+ return val;
+ }
+
+ public static void programLoadUniformBoolean(final int location, final boolean value) {
+ //System.out.println("set value " + value + " " + (value==true?1.0f:0.0f));
+ GL20.glUniform1f(location, value == true ? 1.0f : 0.0f);
+ }
+
+ public static void programLoadUniformColor(final int location, final Color value) {
+ GL20.glUniform4f(location, value.r, value.g, value.b, value.a);
+ }
+
+ public static void programLoadUniformFloat(final int location, final float value) {
+ GL20.glUniform1f(location, value);
+ }
+
+ public static void programLoadUniformFloat(final int location, final float value, final float value2) {
+ GL20.glUniform2f(location, value, value2);
+ }
+
+ public static void programLoadUniformFloat(final int location, final float value, final float value2, final float value3) {
+ GL20.glUniform3f(location, value, value2, value3);
+ }
+
+ public static void programLoadUniformFloat(final int location, final float value, final float value2, final float value3, final float value4) {
+ GL20.glUniform4f(location, value, value2, value3, value4);
+ }
+
+ public static void programLoadUniformInt(final int location, final int value) {
+ GL20.glUniform1i(location, value);
+ }
+
+ public static void programLoadUniformInt(final int location, final int value, final int value2) {
+ GL20.glUniform2i(location, value, value2);
+ }
+
+ public static void programLoadUniformInt(final int location, final int value, final int value2, final int value3) {
+ GL20.glUniform3i(location, value, value2, value3);
+ }
+
+ public static void programLoadUniformInt(final int location, final int value, final int value2, final int value3, final int value4) {
+ GL20.glUniform4i(location, value, value2, value3, value4);
+ }
+
+ public static void programLoadUniformMatrix(final int location, final Matrix4f value) {
+ GL20.glUniformMatrix4fv(location, true, value.getTable());
+ };
+
+ public static void programLoadUniformMatrix(final int location, final Matrix4f value, final boolean transpose) {
+ GL20.glUniformMatrix4fv(location, transpose, value.getTable());
+ }
+
+ public static void programLoadUniformVector(final int location, final Vector2f value) {
+ GL20.glUniform2f(location, value.x, value.y);
+ }
+
+ public static void programLoadUniformVector(final int location, final Vector2i value) {
+ GL20.glUniform2i(location, value.x, value.y);
+ }
+
+ public static void programLoadUniformVector(final int location, final Vector3f value) {
+ GL20.glUniform3f(location, value.x, value.y, value.z);
+ }
+
+ public static void programLoadUniformVector(final int location, final Vector3i value) {
+ GL20.glUniform3i(location, value.x, value.y, value.z);
+ }
+
+ public static void programRemove(final int prog) {
+ if (prog < 0) {
+ return;
+ }
+ // TODO Check if we are in the correct thread
+ GL20.glDeleteProgram(prog);
+ checkGlError("glDeleteProgram");
+ }
+
+ public static void programUnUse(final int id) {
+ // nothing to do ...
+ }
+
+ // public static void drawElements(RenderMode mode, List indices) {
+ // if (this.programId >= 0) {
+ // updateAllFlags();
+ // //Log.debug("Request draw of " + indices.size() + "elements");
+ // GL15.glDrawElements(convertRenderMode.get(mode), indices.size(), GL11.GL_UNSIGNED_INT);//, &indices[0]);
+ // checkGlError("glDrawElements");
+ // }
+ // }
+ // public static void drawElements16(RenderMode mode, List indices) {
+ // if (this.programId >= 0) {
+ // updateAllFlags();
+ // GL20.glDrawElements(convertRenderMode.get(mode), indices.size(), GLUNSIGNEDSHORT, &indices[0]);
+ // checkGlError("glDrawElements");
+ // }
+ // }
+ // public static void drawElements8 (enum renderMode mode, List indices) {
+ // if (this.programId >= 0) {
+ // updateAllFlags();
+ // GL20.glDrawElements(convertRenderMode[int(mode)], indices.size(), GLUNSIGNEDBYTE, &indices[0]);
+ // checkGlError("glDrawElements");
+ // }
+ // }
/**
* @brief Use openGL program
* @param id Id of the program that might be used
*/
- public static void programUse(int id) {
+ public static void programUse(final int id) {
//Log.verbose("USE prog : " + id);
// note : In normal openGL case, the system might call with the program ID and at the end with 0,
// here, we wrap this use to prevent over call of glUseProgram == > then we set -1 when the
@@ -542,9 +769,37 @@ public class OpenGL {
}
checkGlError("glUseProgram");
}
- public static void programUnUse(int id) {
- // nothing to do ...
+
+ /**
+ * @brief store current matrix in the matrix stack.
+ */
+ public static void push() {
+ if (matrixList.size() == 0) {
+ Log.error("set matrix list is not corect size in the stack : " + matrixList.size());
+ matrixList.add(Matrix4f.identity());
+ return;
+ }
+ final Matrix4f tmp = matrixList.get(matrixList.size() - 1);
+ matrixList.add(tmp);
}
+
+ protected static StringBuilder readLocalFile(final String name) {
+ final StringBuilder fileSource = new StringBuilder();
+ try {
+ final BufferedReader reader = new BufferedReader(new FileReader(name));
+ String line;
+ while ((line = reader.readLine()) != null) {
+ fileSource.append(line).append("\n");
+ }
+ reader.close();
+ } catch (final IOException e) {
+ Log.error("Could not read the file!");
+ e.printStackTrace();
+ System.exit(-1);
+ }
+ return fileSource;
+ }
+
public static void reset() {
if (DIRECT_MODE) {
Log.error("TODO ...");
@@ -554,86 +809,85 @@ public class OpenGL {
updateAllFlags();
}
}
-
- public static boolean genBuffers(int[] buffers) {
- if (buffers.length == 0) {
- Log.warning("try to generate vector buffer with size 0");
- return true;
+ public static void resetFlagState() {
+ for (final Map.Entry elem : flagsStates.entrySet()) {
+ elem.getValue().mustBeSet = false;
}
- Log.info("Create N=" + buffers.length + " Buffer");
- GL20.glGenBuffers(buffers);
- checkGlError("glGenBuffers");
- boolean hasError = false;
- for (int iii=0; iii= 256) {
-// tmpLog[idOut] = '\0';
-// Log.error(" == > " + tmpLog);
-// idOut=0;
-// } else {
-// idOut++;
-// }
-// if (this.bufferDisplayError[iii] == '\0') {
-// break;
-// }
-// }
-// if (idOut != 0) {
-// tmpLog[idOut] = '\0';
-// Log.error(" == > " + tmpLog);
-// }
-// return false;
-// }
+ }
+
+ /**
+ * @brief must be called by the thread that has openGl context to notify the system
+ * @note Call @ref gale::openGL::threadHasNoMoreContext when ended
+ */
+ public static void threadHasContext() {
+ final long curentThreadId = Thread.currentThread().getId();
+ threadHasContext.put(curentThreadId, true);
+ }
+
+ /**
+ * @brief At the end of the thread exection, set the thead has no more openGL cotext
+ */
+ public static void threadHasNoMoreContext() {
+ final long curentThreadId = Thread.currentThread().getId();
+ threadHasContext.remove(curentThreadId);
+ }
+
+ public static boolean unbindBuffer() {
+ GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, 0);
+ checkGlError("glBindBuffer(0)");
return true;
}
- public static void programBindAttribute(int prog, int attribute, String variableName) {
- if (prog < 0) {
- Log.error("wrong program ID");
+
+ /**
+ * @brief Un-lock the openGL context for an other user...
+ */
+ public static void unLock() {
+ //mutexOpenGl().unLock();
+ }
+
+ /**
+ * @brieg update all the internal flag needed to be set from tre previous element set ...
+ */
+ public static void updateAllFlags() {
+ if (DIRECT_MODE) {
return;
}
- GL20.glBindAttribLocation(prog, attribute, variableName);
- }
- public static int programGetAttributeLocation(int prog, String name) {
- if (prog < 0) {
- Log.error("wrong program ID");
- return -1;
+ // check if flags has change :
+ if (flagsStatesChange == false) {
+ return;
}
- if (name.length() == 0) {
- Log.error("wrong name of attribure");
- return -1;
- }int val = GL20.glGetAttribLocation(prog, name);
- if (val < 0) {
- checkGlError("glGetAttribLocation");
- Log.warning("glGetAttribLocation('" + name + "') = " + val);
- return -1;
+ flagsStatesChange = false;
+ for (final Map.Entry elem : flagsStates.entrySet()) {
+ final StateFlag value = elem.getValue();
+ if (value.current != value.mustBeSet) {
+ value.current = value.mustBeSet;
+ if (value.current == true) {
+ GL11.glEnable(basicFlag.get(elem.getKey()));
+ checkGlError("glEnable");
+ //Log.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey()));
+ } else {
+ GL11.glDisable(basicFlag.get(elem.getKey()));
+ checkGlError("glDisable");
+ //Log.info(" disable : " + elem.getKey());
+ }
+ }
}
- return val;
- }
- public static int programGetUniformLocation(int prog, String name) {
- if (prog < 0) {
- Log.error("wrong program ID");
- return -1;
- }
- if (name.length() == 0) {
- Log.error("wrong name of uniform");
- return -1;
- }
- int val = GL20.glGetUniformLocation(prog, name);
- if (val == GL20.GL_INVALID_VALUE) {
- checkGlError("glGetUniformLocation");
- Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_VALUE");
- } else if (val == GL20.GL_INVALID_OPERATION) {
- checkGlError("glGetUniformLocation");
- Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_OPERATION");
- } else if (val < 0) {
- checkGlError("glGetUniformLocation");
- Log.warning("glGetUniformLocation('" + name + "') = " + val);
- }
- return val;
- };
-
-
- public static void programLoadUniformFloat(int location, float value) {
- GL20.glUniform1f(location, value);
- }
- public static void programLoadUniformFloat(int location, float value, float value2) {
- GL20.glUniform2f(location, value, value2);
- }
- public static void programLoadUniformFloat(int location, float value, float value2, float value3) {
- GL20.glUniform3f(location, value, value2, value3);
- }
- public static void programLoadUniformFloat(int location, float value, float value2, float value3, float value4) {
- GL20.glUniform4f(location, value, value2, value3, value4);
- }
-
- public static void programLoadUniformInt(int location, int value) {
- GL20.glUniform1i(location, value);
- }
- public static void programLoadUniformInt(int location, int value, int value2) {
- GL20.glUniform2i(location, value, value2);
- }
- public static void programLoadUniformInt(int location, int value, int value2, int value3) {
- GL20.glUniform3i(location, value, value2, value3);
- }
- public static void programLoadUniformInt(int location, int value, int value2, int value3, int value4) {
- GL20.glUniform4i(location, value, value2, value3, value4);
- }
-
- public static void programLoadUniformColor(int location, Color value) {
- GL20.glUniform4f(location, value.r, value.g, value.b, value.a);
}
- public static void programLoadUniformVector(int location, Vector3f value) {
- GL20.glUniform3f(location, value.x, value.y, value.z);
- }
- public static void programLoadUniformVector(int location, Vector3i value) {
- GL20.glUniform3i(location, value.x, value.y, value.z);
+ public static void vertexAttribPointerFloat(final int id, final int size) {
+ GL20.glVertexAttribPointer(id, size, GL11.GL_FLOAT, false, 0, 0);
+ checkGlError("glVertexAttribPointer");
}
- public static void programLoadUniformVector(int location, Vector2f value) {
- GL20.glUniform2f(location, value.x, value.y);
- }
- public static void programLoadUniformVector(int location, Vector2i value) {
- GL20.glUniform2i(location, value.x, value.y);
- }
-
- public static void programLoadUniformBoolean(int location, boolean value) {
- //System.out.println("set value " + value + " " + (value==true?1.0f:0.0f));
- GL20.glUniform1f(location, value==true?1.0f:0.0f);
- }
-
- public static void programLoadUniformMatrix(int location, Matrix4f value) {
- GL20.glUniformMatrix4fv(location, true, value.getTable());
- }
- public static void programLoadUniformMatrix(int location, Matrix4f value, boolean transpose) {
- GL20.glUniformMatrix4fv(location, transpose, value.getTable());
- }
- public static void drawElements(RenderMode mode, int vertexCount) {
- GL11.glDrawElements(CONVERT_RENDER_MODE.get(mode), vertexCount, GL11.GL_UNSIGNED_INT, 0);
- }
- public static void setDeathMask(boolean state) {
- GL40.glDepthMask(state);
- }
+ private OpenGL() {}
}
diff --git a/src/org/atriasoft/gale/context/Context.java b/src/org/atriasoft/gale/context/Context.java
index 74cd825..42355ac 100644
--- a/src/org/atriasoft/gale/context/Context.java
+++ b/src/org/atriasoft/gale/context/Context.java
@@ -8,69 +8,25 @@ import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.gale.Application;
import org.atriasoft.gale.Fps;
import org.atriasoft.gale.Gale;
-import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.Orientation;
import org.atriasoft.gale.backend3d.OpenGL;
-import org.atriasoft.gale.resource.ResourceManager;
+import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType;
+import org.atriasoft.gale.resource.ResourceManager;
interface ActionToDoInAsyncLoop {
- public void run(Context context);
+ public void run(Context context);
}
-class PeriodicThread extends ThreadAbstract {
- private Context context;
- public PeriodicThread(Context context) {
- super("Galethread 2");
- this.context = context;
- }
- @Override
- protected void birth() {
- // TODO Auto-generated method stub
- }
- @Override
- protected void runPeriodic() {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- return;
- }
-// mutexInterface().lock();
- context.processEvents();
- // call all the application for periodic request (the application manage multiple instance )...
- Application appl = context.getApplication();
- if (appl != null) {
- appl.onPeriod(System.currentTimeMillis());
- }
-// mutexInterface().unLock();
- }
- @Override
- protected void death() {
- // TODO Auto-generated method stub
- }
-};
-
public abstract class Context {
protected static final int MAX_MANAGE_INPUT = 15;
- protected ThreadAbstract periodicThread;
- protected Application application; //!< Application handle
- public Application getApplication() {
- return this.application;
- }
- private CommandLine commandLine = new CommandLine(); //!< Start command line information
- public CommandLine getCmd() {
- return this.commandLine;
- };
- private ResourceManager resourceManager = new ResourceManager(); //!< global resources Manager
- public ResourceManager getResourcesManager() {
- return this.resourceManager;
- };
- private static Context globalContext= null;
+ private static Context globalContext = null;
+ // return true if a flush is needed
+ private static int countMemeCheck = 0;
+
/**
* @brief From everyware in the program, we can get the context inteface.
* @return current reference on the instance.
@@ -78,16 +34,28 @@ public abstract class Context {
public static Context getContext() {
return globalContext;
}
- public static void setContext(Context context) {
+
+ public static void setContext(final Context context) {
globalContext = context;
}
- protected void lockContext() {
-
- }
- protected void unLockContext() {
-
- }
- public Context(Application application, String[] args) {
+
+ protected ThreadAbstract periodicThread;;
+ protected Application application; //!< Application handle
+ private final CommandLine commandLine = new CommandLine(); //!< Start command line information;
+ private final ResourceManager resourceManager = new ResourceManager(); //!< global resources Manager
+ // simulation area:
+ private long previousDisplayTime; // this is to limit framerate ... in case...
+ private final Vector msgSystem = new Vector<>();
+ private final boolean displayFps = true;
+ private final Fps fpsSystemEvent = new Fps("SystemEvent", this.displayFps);
+ private final Fps fpsSystemContext = new Fps("SystemContext", this.displayFps);
+ private final Fps fpsSystem = new Fps("System", this.displayFps);
+ private final Fps fpsFlush = new Fps("Flush", this.displayFps);
+ protected Vector2f windowsSize = new Vector2f(0, 0); //!< current size of the system
+ protected boolean fullscreen = false;
+ protected Vector2f windowsPos; //!< current size of the system
+
+ public Context(final Application application, final String[] args) {
// set a basic
this.application = application;
setContext(this);
@@ -95,7 +63,7 @@ public abstract class Context {
if (this.application == null) {
Log.critical("Can not start context with no Application ==> rtfm ...");
}
- commandLine.parse(args);
+ this.commandLine.parse(args);
Log.info(" == > Gale system init (BEGIN)");
// create thread to manage real periodic event
this.periodicThread = new PeriodicThread(this);
@@ -105,36 +73,36 @@ public abstract class Context {
//theme::setNameDefault("COLOR", "color/black/");
// parse the debug level:
-// for(int iii=0; iii{
- Application appl = _context.getApplication();
+ postAction((_context) -> {
+ final Application appl = _context.getApplication();
if (appl == null) {
return;
}
@@ -148,241 +116,178 @@ public abstract class Context {
requestUpdateSize();
Log.info(" == > Gale system init (END)");
}
- /**
- * @brief StartProcessing (2nd thread).
- * @note to call when all the Context is started
- */
- public void start2ndThreadProcessing() {
- // set the current interface:
- lockContext();
- this.periodicThread.threadStart();
- try {
- Thread.sleep(1);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // release the current interface:
- unLockContext();
- }
- // simulation area:
- private long previousDisplayTime; // this is to limit framerate ... in case...
- private Vector msgSystem = new Vector();
- private boolean displayFps = true;
- private Fps fpsSystemEvent = new Fps("SystemEvent", displayFps);
- private Fps fpsSystemContext = new Fps("SystemContext", displayFps);
- private Fps fpsSystem = new Fps("System", displayFps);
- private Fps fpsFlush = new Fps("Flush", displayFps);
-
-
- private synchronized void postAction(ActionToDoInAsyncLoop data) {
- msgSystem.addElement(data);
- notify();
- //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
- }
-
- // Called by Consumer
- public synchronized ActionToDoInAsyncLoop getAction() {
- notify();
- while (msgSystem.size() == 0) {
- try {
+ /**
+ * @brief Inform the Gui that we want to have a copy of the clipboard
+ * @param _clipboardID ID of the clipboard (STD/SELECTION) only apear here
+ */
+ public void clipBoardGet(final ClipboardList clipboardID) {
+ // just transmit an event , we have the data in the system
+ operatingSystemClipBoardArrive(clipboardID);
+ }
+
+ /**
+ * @brief Inform the Gui that we are the new owner of the clipboard
+ * @param _clipboardID ID of the clipboard (STD/SELECTION) only apear here
+ */
+ public void clipBoardSet(final ClipboardList clipboardID) {
+ // nothing to do, data is already copyed in the GALE clipborad center
+ }
+
+ /**
+ * @brief force the screen orientation (availlable on portable elements ...
+ * @param _orientation Selected orientation.
+ */
+ public void forceOrientation(final Orientation orientation) {}
+
+ /**
+ * @brief Redraw all the windows
+ */
+ public void forceRedrawAll() {
+ if (this.application == null) {
+ return;
+ }
+ this.application.onResize(this.windowsSize);
+ }
+
+ // Called by Consumer
+ public synchronized ActionToDoInAsyncLoop getAction() {
+ notify();
+ while (this.msgSystem.size() == 0) {
+ try {
wait();
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
- }//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
- }
- ActionToDoInAsyncLoop message = (ActionToDoInAsyncLoop) msgSystem.firstElement();
- msgSystem.removeElement(message);
- return message;
- }
- /**
- * @brief Processing all the event arrived ... (commoly called in draw function)
- */
- public void processEvents() {
- int nbEvent = 0;
- //Log.debug(" ******** Event " << this.msgSystem.count());
- while (this.msgSystem.size() > 0) {
- nbEvent++;
- //Log.verbose(" [" << nbEvent << "] event ...");
- ActionToDoInAsyncLoop func = getAction();
- if (func == null) {
- continue;
- }
- func.run(this);
+ } //By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
}
+ final ActionToDoInAsyncLoop message = this.msgSystem.firstElement();
+ this.msgSystem.removeElement(message);
+ return message;
}
-// gale::Context::~Context() {
-// Log.info(" == > Gale system Un-Init (BEGIN)");
-// this.periodicThread.threadStart();
-// getResourcesManager().applicationExiting();
-// // TODO Clean the message list ...
-// // set the current interface:
-// lockContext();
-// // clean all widget and sub widget with their resources:
-// //this.objectManager.cleanInternalRemoved();
-// // call application to uninit
-// this.application.canDraw = false;
-// this.application.onPause(*this);
-// this.application.onStop(*this);
-// this.application.onDestroy(*this);
-// this.application.reset();
-// // clean all messages
-// this.msgSystem.clean();
-// // internal clean elements
-// //this.objectManager.cleanInternalRemoved();
-// this.resourceManager.cleanInternalRemoved();
-//
-// Log.info("List of all widget of this context must be equal at 0 ==> otherwise some remove is missing");
-// //this.objectManager.displayListObject();
-// // Resource is an lower element as objects ...
-// this.resourceManager.unInit();
-// // now All must be removed !!!
-// //this.objectManager.unInit();
-// // release the current interface :
-// unLockContext();
-// Log.info(" == > Gale system Un-Init (END)");
-// if (this.simulationActive) {
-// // in simulation case:
-// this.simulationFile.close();
-// }
-// }
-
- public void operatingSystemSetInput(KeySpecial special,
- KeyType type,
- KeyStatus status,
- int pointerID,
- Vector2f pos){
- postAction((context)->{
- Application appl = context.getApplication();
- if (appl == null) {
- return;
- }
- appl.onPointer(special,
- type,
- pointerID,
- pos,
- status);
- });
+
+ public Application getApplication() {
+ return this.application;
}
- public void operatingSystemsetKeyboard( KeySpecial special,
- KeyKeyboard type,
- KeyStatus state,
- boolean isARepeateKey) {
- operatingSystemsetKeyboard(special, type, state, isARepeateKey, (char)0);
+
+ public CommandLine getCmd() {
+ return this.commandLine;
}
- public void operatingSystemsetKeyboard( KeySpecial special,
- KeyKeyboard type,
- KeyStatus state,
- boolean isARepeateKey,
- Character charValue) {
- KeyStatus tmpState = state;
- if (isARepeateKey == true) {
- if (tmpState == KeyStatus.down) {
- tmpState = KeyStatus.downRepeate;
- } else {
- tmpState = KeyStatus.upRepeate;
- }
- }
- operatingSystemsetKeyboard2(special, type, state, charValue);
- }
- public void operatingSystemsetKeyboard2( KeySpecial special,
- KeyKeyboard type,
- KeyStatus state,
- Character charValue){
- postAction((context)->{
- Application appl = context.getApplication();
- if (appl == null) {
- return;
- }
- appl.onKeyboard(special,
- type,
- charValue,
- state);
- });
+
+ public boolean getFullScreen() {
+ return this.fullscreen;
}
+
/**
- * @brief The current context is suspended
+ * @brief The Application request the current position of the windows.
+ * @return Turrent position of the Windows.
*/
- public void operatingSystemSuspend(){
- // set the current interface :
- lockContext();
- Log.info("operatingSystemSuspend...");
- this.previousDisplayTime = 0;
+ public Vector2f getPos() {
+ return this.windowsPos;
+ }
+
+ public ResourceManager getResourcesManager() {
+ return this.resourceManager;
+ }
+
+ /**
+ * @brief get the current windows size
+ * @return the current size ...
+ */
+ public Vector2f getSize() {
+ return this.windowsSize;
+ }
+
+ /**
+ * @brief get all Keyboard event from the X system (like many time use of META)
+ * @param _status "true" if all the event will be get, false if we want only ours.
+ */
+ public void grabKeyboardEvents(final boolean status) {}
+
+ /**
+ * @brief get all Mouse/Touch events from the X system
+ * @param _status "true" if all the event will be get, false if we want only ours.
+ * @param _forcedPosition the position where the mouse might be reset at every events ...
+ */
+ public void grabPointerEvents(final boolean status, final Vector2f forcedPosition) {}
+
+ /**
+ * @brief The Application request that the Windows will be Hidden.
+ */
+ public void hide() {
+ Log.info("hide: NOT implemented ...");
+ }
+
+ public boolean isGrabPointerEvents() {
+ return false;
+ }
+
+ /**
+ * @brief Hide the virtal keyboard (for touch system only)
+ */
+ public void keyboardHide() {
+ Log.info("keyboardHide: NOT implemented ...");
+ }
+
+ /**
+ * @brief display the virtal keyboard (for touch system only)
+ */
+ public void keyboardShow() {
+ Log.info("keyboardShow: NOT implemented ...");
+ }
+
+ protected void lockContext() {
-// if (this.windowsCurrent != null) {
-// this.windowsCurrent.onStateSuspend();
-// }
- // release the current interface :
- unLockContext();
}
+
/**
- * @brief The current context is resumed
+ * @brief Open an URL on an eternal brother.
+ * @param _url URL to open.
*/
- public void operatingSystemResume(){
+ public void openURL(final String url) {}
+
+ /**
+ * @brief The current context is set in background (framerate is slowing down (max fps)/5 # 4fps)
+ */
+ public void operatingSystemBackground() {
// set the current interface :
lockContext();
- Log.info("operatingSystemResume...");
- this.previousDisplayTime = System.currentTimeMillis();
- // TODO this.objectManager.timeCallResume(this.previousDisplayTime);
-// if (this.windowsCurrent != null) {
-// this.windowsCurrent.onStateResume();
-// }
+ Log.info("operatingSystemBackground...");
+ // if (this.windowsCurrent != null) {
+ // this.windowsCurrent.onStateBackground();
+ // }
// release the current interface :
unLockContext();
}
/**
- * @brief The current context is set in foreground (framerate is maximum speed)
+ * @brief Call by the OS when a clipboard arrive to US (previously requested by a widget)
+ * @param Id of the clipboard
*/
- public void operatingSystemForeground(){
- // set the current interface :
- lockContext();
- Log.info("operatingSystemForeground...");
-
-// if (this.windowsCurrent != null) {
-// this.windowsCurrent.onStateForeground();
-// }
- // release the current interface :
- unLockContext();
- }
- /**
- * @brief The current context is set in background (framerate is slowing down (max fps)/5 # 4fps)
- */
- public void operatingSystemBackground(){
- // set the current interface :
- lockContext();
- Log.info("operatingSystemBackground...");
-// if (this.windowsCurrent != null) {
-// this.windowsCurrent.onStateBackground();
-// }
- // release the current interface :
- unLockContext();
- }
- public void requestUpdateSize() {
- postAction((context)->{
- //Log.debug("Receive MSG : THREAD_RESIZE");
- context.forceRedrawAll();
+ public void operatingSystemClipBoardArrive(final ClipboardList clipboardID) {
+ postAction((context) -> {
+ final Application appl = context.getApplication();
+ if (appl != null) {
+ appl.onClipboardEvent(clipboardID);
+ }
});
}
- // return true if a flush is needed
- private static int countMemeCheck = 0;
- public boolean operatingSystemDraw(boolean displayEveryTime) {
- if (countMemeCheck++ >= 10*16) {
+
+ public boolean operatingSystemDraw(final boolean displayEveryTime) {
+ if (countMemeCheck++ >= 10 * 16) {
countMemeCheck = 0;
}
//Log.verbose("Call draw");
- long currentTime = System.currentTimeMillis();
+ final long currentTime = System.currentTimeMillis();
//echrono::Time currentTime2 = echrono::Time::now();
//Log.warning("Time = " << currentTime << " " << currentTime2);
// TODO Review this ...
// this is to prevent the multiple display at the a high frequency ...
- if(currentTime - this.previousDisplayTime < 8) {
+ if (currentTime - this.previousDisplayTime < 8) {
try {
Thread.sleep(1);
- } catch (InterruptedException e) {
+ } catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
@@ -431,8 +336,7 @@ public abstract class Context {
if (this.displayFps == true) {
this.fpsSystemContext.tic();
}
- if( needRedraw = true
- || displayEveryTime == true) {
+ if (needRedraw = true || displayEveryTime == true) {
//Log.debug(" ==> real Draw");
lockContext();
this.resourceManager.updateContext();
@@ -446,8 +350,7 @@ public abstract class Context {
this.fpsSystem.tic();
}
if (this.application != null) {
- if( needRedraw == true
- || displayEveryTime == true) {
+ if (needRedraw == true || displayEveryTime == true) {
this.fpsSystem.incrementCounter();
// set the current interface :
lockContext();
@@ -497,121 +400,23 @@ public abstract class Context {
}
OpenGL.threadHasNoMoreContext();
return hasDisplayDone;
- }
+ };
+
/**
- * @brief reset event management for the IO like Input ou Mouse or keyborad
+ * @brief The current context is set in foreground (framerate is maximum speed)
*/
- public void resetIOEvent() {
- // TODO this.input.newLayerSet();
- }
- /**
- * @brief The OS inform that the openGL ext has been destroy == > use to automaticly reload the texture and other thinks ...
- */
- public void operatingSystemOpenGlContextDestroy(){
- this.resourceManager.contextHasBeenDestroyed();
- }
- /**
- * @brief The OS Inform that the Window has been killed
- */
- public void operatingSystemStop(){
+ public void operatingSystemForeground() {
// set the current interface :
lockContext();
- Log.info("operatingSystemStop...");
- if (this.application == null) {
- stop();
- return;
- }
- this.application.onKillDemand(this);
+ Log.info("operatingSystemForeground...");
+
+ // if (this.windowsCurrent != null) {
+ // this.windowsCurrent.onStateForeground();
+ // }
// release the current interface :
unLockContext();
}
- /**
- * @brief The application request that the Window will be killed
- */
- public void stop() {
- Log.warning("stop: NOT implemented for this platform...");
- }
- protected Vector2f windowsSize = new Vector2f(0,0); //!< current size of the system
- /**
- * @brief get the current windows size
- * @return the current size ...
- */
- public Vector2f getSize() {
- return this.windowsSize;
- };
- /**
- * @brief The OS inform that the current windows has change his size.
- * @param _size new size of the windows.
- */
- public void operatingSystemResize( Vector2f _size){
- if (this.windowsSize == _size) {
- return;
- }
- // TODO Better in the thread ... ==> but generate some init error ...
- //gale::Dimension::setPixelWindowsSize(_size);
- postAction((context) -> {
- Log.debug("Receive MSG : THREAD_RESIZE : " + context.windowsSize + " ==> " + _size);
- context.windowsSize = _size;
- //gale::Dimension::setPixelWindowsSize(_context.windowsSize);
- Application tmpAppl = context.getApplication();
- if (tmpAppl != null) {
- tmpAppl.onResize(context.windowsSize);
- }
- // call application inside ..
- context.forceRedrawAll();
- });
- }
- /**
- * @brief The application request a change of his current size.
- * @param _size new Requested size of the windows.
- */
- public void setSize( Vector2f size){
- Log.info("setSize: NOT implemented ...");
- };
- protected boolean fullscreen = false;
- /**
- * @brief The application request a change of his current size force the fullscreen mode.
- * @param _status status of the fullscreen mode.
- */
- public void setFullScreen(boolean status){
- fullscreen = status;
- };
- public boolean getFullScreen(){
- return fullscreen;
- };
- protected Vector2f windowsPos; //!< current size of the system
- /**
- * @brief The OS inform that the current windows has change his position.
- * @param _pos New position of the Windows.
- */
- public void operatingSystemMove( Vector2f _pos){
- if (this.windowsPos.isEqual(_pos)) {
- return;
- }
- postAction((context) -> {
- Log.debug("Receive MSG : THREAD_MOVE : " + context.windowsPos + " ==> " + _pos);
- context.windowsPos = _pos;
- Application appl = context.getApplication();
- if (appl == null) {
- return;
- }
- appl.onMovePosition(context.windowsPos);
- });
- }
- /**
- * @brief The Application request that the current windows will change his position.
- * @param _pos New position of the Windows requested.
- */
- public void setPos( Vector2f pos){
- Log.info("setPos: NOT implemented ...");
- }
- /**
- * @brief The Application request the current position of the windows.
- * @return Turrent position of the Windows.
- */
- public Vector2f getPos(){
- return this.windowsPos;
- }
+
/**
* @brief The OS inform that the Windows is now Hidden.
*/
@@ -629,17 +434,113 @@ public abstract class Context {
*/
Log.todo("HIDE ... ");
});
- }
- /**
- * @brief The Application request that the Windows will be Hidden.
- */
- public void hide(){
- Log.info("hide: NOT implemented ...");
};
+
+ /**
+ * @brief The OS inform that the current windows has change his position.
+ * @param _pos New position of the Windows.
+ */
+ public void operatingSystemMove(final Vector2f _pos) {
+ if (this.windowsPos.isEqual(_pos)) {
+ return;
+ }
+ postAction((context) -> {
+ Log.debug("Receive MSG : THREAD_MOVE : " + context.windowsPos + " ==> " + _pos);
+ context.windowsPos = _pos;
+ final Application appl = context.getApplication();
+ if (appl == null) {
+ return;
+ }
+ appl.onMovePosition(context.windowsPos);
+ });
+ }
+
+ /**
+ * @brief The OS inform that the openGL ext has been destroy == > use to automaticly reload the texture and other thinks ...
+ */
+ public void operatingSystemOpenGlContextDestroy() {
+ this.resourceManager.contextHasBeenDestroyed();
+ };
+
+ /**
+ * @brief The OS inform that the current windows has change his size.
+ * @param _size new size of the windows.
+ */
+ public void operatingSystemResize(final Vector2f _size) {
+ if (this.windowsSize == _size) {
+ return;
+ }
+ // TODO Better in the thread ... ==> but generate some init error ...
+ //gale::Dimension::setPixelWindowsSize(_size);
+ postAction((context) -> {
+ Log.debug("Receive MSG : THREAD_RESIZE : " + context.windowsSize + " ==> " + _size);
+ context.windowsSize = _size;
+ //gale::Dimension::setPixelWindowsSize(_context.windowsSize);
+ final Application tmpAppl = context.getApplication();
+ if (tmpAppl != null) {
+ tmpAppl.onResize(context.windowsSize);
+ }
+ // call application inside ..
+ context.forceRedrawAll();
+ });
+ };
+
+ /**
+ * @brief The current context is resumed
+ */
+ public void operatingSystemResume() {
+ // set the current interface :
+ lockContext();
+ Log.info("operatingSystemResume...");
+ this.previousDisplayTime = System.currentTimeMillis();
+ // TODO this.objectManager.timeCallResume(this.previousDisplayTime);
+ // if (this.windowsCurrent != null) {
+ // this.windowsCurrent.onStateResume();
+ // }
+ // release the current interface :
+ unLockContext();
+ }
+
+ public void operatingSystemSetInput(final KeySpecial special, final KeyType type, final KeyStatus status, final int pointerID, final Vector2f pos) {
+ postAction((context) -> {
+ final Application appl = context.getApplication();
+ if (appl == null) {
+ return;
+ }
+ appl.onPointer(special, type, pointerID, pos, status);
+ });
+ }
+
+ public void operatingSystemsetKeyboard(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final boolean isARepeateKey) {
+ operatingSystemsetKeyboard(special, type, state, isARepeateKey, (char) 0);
+ }
+
+ public void operatingSystemsetKeyboard(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final boolean isARepeateKey, final Character charValue) {
+ KeyStatus tmpState = state;
+ if (isARepeateKey == true) {
+ if (tmpState == KeyStatus.down) {
+ tmpState = KeyStatus.downRepeate;
+ } else {
+ tmpState = KeyStatus.upRepeate;
+ }
+ }
+ operatingSystemsetKeyboard2(special, type, state, charValue);
+ }
+
+ public void operatingSystemsetKeyboard2(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final Character charValue) {
+ postAction((context) -> {
+ final Application appl = context.getApplication();
+ if (appl == null) {
+ return;
+ }
+ appl.onKeyboard(special, type, charValue, state);
+ });
+ }
+
/**
* @brief The OS inform that the Windows is now visible.
*/
- public void operatingSystemShow(){
+ public void operatingSystemShow() {
postAction((context) -> {
/*
Application> appl = _context.getApplication();
@@ -653,106 +554,112 @@ public abstract class Context {
*/
Log.todo("SHOW ... ");
});
- }
+ };
+
/**
- * @brief The Application request that the Windows will be visible.
+ * @brief The OS Inform that the Window has been killed
*/
- public void show(){
- Log.info("show: NOT implemented ...");
- }
- /**
- * @brief Redraw all the windows
- */
- public void forceRedrawAll() {
+ public void operatingSystemStop() {
+ // set the current interface :
+ lockContext();
+ Log.info("operatingSystemStop...");
if (this.application == null) {
+ stop();
return;
}
- this.application.onResize(this.windowsSize);
- }
- /**
- * @brief display the virtal keyboard (for touch system only)
- */
- public void keyboardShow(){
- Log.info("keyboardShow: NOT implemented ...");
- }
- /**
- * @brief Hide the virtal keyboard (for touch system only)
- */
- public void keyboardHide(){
- Log.info("keyboardHide: NOT implemented ...");
+ this.application.onKillDemand(this);
+ // release the current interface :
+ unLockContext();
}
/**
- * @brief Inform the Gui that we want to have a copy of the clipboard
- * @param _clipboardID ID of the clipboard (STD/SELECTION) only apear here
+ * @brief The current context is suspended
*/
- public void clipBoardGet( ClipboardList clipboardID){
- // just transmit an event , we have the data in the system
- operatingSystemClipBoardArrive(clipboardID);
+ public void operatingSystemSuspend() {
+ // set the current interface :
+ lockContext();
+ Log.info("operatingSystemSuspend...");
+ this.previousDisplayTime = 0;
+
+ // if (this.windowsCurrent != null) {
+ // this.windowsCurrent.onStateSuspend();
+ // }
+ // release the current interface :
+ unLockContext();
}
- /**
- * @brief Inform the Gui that we are the new owner of the clipboard
- * @param _clipboardID ID of the clipboard (STD/SELECTION) only apear here
- */
- public void clipBoardSet( ClipboardList clipboardID){
- // nothing to do, data is already copyed in the GALE clipborad center
+
+ private synchronized void postAction(final ActionToDoInAsyncLoop data) {
+ this.msgSystem.addElement(data);
+ notify();
+ //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
}
+
/**
- * @brief Call by the OS when a clipboard arrive to US (previously requested by a widget)
- * @param Id of the clipboard
+ * @brief Processing all the event arrived ... (commoly called in draw function)
*/
- public void operatingSystemClipBoardArrive(ClipboardList clipboardID) {
- postAction((context) -> {
- Application appl = context.getApplication();
- if (appl != null) {
- appl.onClipboardEvent(clipboardID);
+ public void processEvents() {
+ int nbEvent = 0;
+ //Log.debug(" ******** Event " << this.msgSystem.count());
+ while (this.msgSystem.size() > 0) {
+ nbEvent++;
+ //Log.verbose(" [" << nbEvent << "] event ...");
+ final ActionToDoInAsyncLoop func = getAction();
+ if (func == null) {
+ continue;
}
+ func.run(this);
+ }
+ }
+
+ // gale::Context::~Context() {
+ // Log.info(" == > Gale system Un-Init (BEGIN)");
+ // this.periodicThread.threadStart();
+ // getResourcesManager().applicationExiting();
+ // // TODO Clean the message list ...
+ // // set the current interface:
+ // lockContext();
+ // // clean all widget and sub widget with their resources:
+ // //this.objectManager.cleanInternalRemoved();
+ // // call application to uninit
+ // this.application.canDraw = false;
+ // this.application.onPause(*this);
+ // this.application.onStop(*this);
+ // this.application.onDestroy(*this);
+ // this.application.reset();
+ // // clean all messages
+ // this.msgSystem.clean();
+ // // internal clean elements
+ // //this.objectManager.cleanInternalRemoved();
+ // this.resourceManager.cleanInternalRemoved();
+ //
+ // Log.info("List of all widget of this context must be equal at 0 ==> otherwise some remove is missing");
+ // //this.objectManager.displayListObject();
+ // // Resource is an lower element as objects ...
+ // this.resourceManager.unInit();
+ // // now All must be removed !!!
+ // //this.objectManager.unInit();
+ // // release the current interface :
+ // unLockContext();
+ // Log.info(" == > Gale system Un-Init (END)");
+ // if (this.simulationActive) {
+ // // in simulation case:
+ // this.simulationFile.close();
+ // }
+ // }
+ public void requestUpdateSize() {
+ postAction((context) -> {
+ //Log.debug("Receive MSG : THREAD_RESIZE");
+ context.forceRedrawAll();
});
}
+
/**
- * @brief set the new title of the windows
- * @param title New desired title
+ * @brief reset event management for the IO like Input ou Mouse or keyborad
*/
- public void setTitle( String title){
- Log.info("setTitle: NOT implemented ...");
+ public void resetIOEvent() {
+ // TODO this.input.newLayerSet();
}
- /**
- * @brief Open an URL on an eternal brother.
- * @param _url URL to open.
- */
- public void openURL( String url) { };
- /**
- * @brief force the screen orientation (availlable on portable elements ...
- * @param _orientation Selected orientation.
- */
- public void forceOrientation(Orientation orientation) { };
- /**
- * @brief get all Keyboard event from the X system (like many time use of META)
- * @param _status "true" if all the event will be get, false if we want only ours.
- */
- public void grabKeyboardEvents(boolean status) {}
- /**
- * @brief get all Mouse/Touch events from the X system
- * @param _status "true" if all the event will be get, false if we want only ours.
- * @param _forcedPosition the position where the mouse might be reset at every events ...
- */
- public void grabPointerEvents(boolean status, Vector2f forcedPosition) { };
- public boolean isGrabPointerEvents() { return false; };
- /**
- * @brief set the cursor display type.
- * @param NewCursor selected new cursor.
- */
- public void setCursor( Cursor newCursor) { };
- /**
- * @brief set the Icon of the program
- * @param _inputFile new filename icon of the current program.
- */
- public void setIcon(Uri inputFile) { };
- /**
- * @brief Enable or Disable the decoration on the Windows (availlable only on Desktop)
- * @param _status "true" to enable decoration / false otherwise
- */
- public void setWindowsDecoration(boolean status) {};
+
/**
* @brief Internal API to run the processing of the event loop ...
* @return The Exit value of the program
@@ -760,4 +667,128 @@ public abstract class Context {
*/
public abstract int run();
+ /**
+ * @brief set the cursor display type.
+ * @param NewCursor selected new cursor.
+ */
+ public void setCursor(final Cursor newCursor) {}
+
+ /**
+ * @brief The application request a change of his current size force the fullscreen mode.
+ * @param _status status of the fullscreen mode.
+ */
+ public void setFullScreen(final boolean status) {
+ this.fullscreen = status;
+ }
+
+ /**
+ * @brief set the Icon of the program
+ * @param _inputFile new filename icon of the current program.
+ */
+ public void setIcon(final Uri inputFile) {};
+
+ /**
+ * @brief The Application request that the current windows will change his position.
+ * @param _pos New position of the Windows requested.
+ */
+ public void setPos(final Vector2f pos) {
+ Log.info("setPos: NOT implemented ...");
+ };
+
+ /**
+ * @brief The application request a change of his current size.
+ * @param _size new Requested size of the windows.
+ */
+ public void setSize(final Vector2f size) {
+ Log.info("setSize: NOT implemented ...");
+ }
+
+ /**
+ * @brief set the new title of the windows
+ * @param title New desired title
+ */
+ public void setTitle(final String title) {
+ Log.info("setTitle: NOT implemented ...");
+ };
+
+ /**
+ * @brief Enable or Disable the decoration on the Windows (availlable only on Desktop)
+ * @param _status "true" to enable decoration / false otherwise
+ */
+ public void setWindowsDecoration(final boolean status) {};
+
+ /**
+ * @brief The Application request that the Windows will be visible.
+ */
+ public void show() {
+ Log.info("show: NOT implemented ...");
+ };
+
+ /**
+ * @brief StartProcessing (2nd thread).
+ * @note to call when all the Context is started
+ */
+ public void start2ndThreadProcessing() {
+ // set the current interface:
+ lockContext();
+ this.periodicThread.threadStart();
+ try {
+ Thread.sleep(1);
+ } catch (final InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ // release the current interface:
+ unLockContext();
+ };
+
+ /**
+ * @brief The application request that the Window will be killed
+ */
+ public void stop() {
+ Log.warning("stop: NOT implemented for this platform...");
+ };
+
+ protected void unLockContext() {
+
+ }
+
+};
+
+class PeriodicThread extends ThreadAbstract {
+ private final Context context;
+
+ public PeriodicThread(final Context context) {
+ super("Galethread 2");
+ this.context = context;
+ }
+
+ @Override
+ protected void birth() {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ protected void death() {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ protected void runPeriodic() {
+ try {
+ Thread.sleep(10);
+ } catch (final InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return;
+ }
+ synchronized (this.context) {
+ this.context.processEvents();
+ // call all the application for periodic request (the application manage multiple instance )...
+ final Application appl = this.context.getApplication();
+ if (appl != null) {
+ appl.onPeriod(System.currentTimeMillis());
+ }
+ }
+ }
}
diff --git a/src/org/atriasoft/gale/event/EventEntry.java b/src/org/atriasoft/gale/event/EventEntry.java
deleted file mode 100644
index cc6f4d2..0000000
--- a/src/org/atriasoft/gale/event/EventEntry.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package org.atriasoft.gale.event;
-
-import org.atriasoft.gale.key.KeyKeyboard;
-import org.atriasoft.gale.key.KeyStatus;
-import org.atriasoft.gale.key.KeySpecial;
-
-public class EventEntry {
- private KeySpecial specialKey; //!< input key status (prevent change in time..)
- private KeyKeyboard type; //!< type of hardware event
- private KeyStatus status; //!< status of hardware event
- private Character unicodeData; //!< Unicode data (in some case)
- public EventEntry(KeySpecial specialKey,
- KeyKeyboard type,
- KeyStatus status,
- Character charValue) {
- this.type = type;
- this.status = status;
- this.specialKey = specialKey;
- this.unicodeData = charValue;
- }
- public void setType(KeyKeyboard type) {
- this.type = type;
- }
- public KeyKeyboard getType() {
- return this.type;
- }
- public void setStatus(KeyStatus status) {
- this.status = status;
- }
- public KeyStatus getStatus() {
- return this.status;
- };
- public void setSpecialKey(KeySpecial specialKey) {
- this.specialKey = specialKey;
- }
- public KeySpecial getSpecialKey() {
- return this.specialKey;
- }
- public void setChar(Character charValue) {
- this.unicodeData = charValue;
- }
- public Character getChar() {
- return this.unicodeData;
- }
- @Override
- public String toString() {
- return "EventEntry [type=" + type + ", status=" + status + ", unicodeData="
- + unicodeData + ", specialKey=" + specialKey + "]";
- }
-}
diff --git a/src/org/atriasoft/gale/event/EventInput.java b/src/org/atriasoft/gale/event/EventInput.java
deleted file mode 100644
index 41ece79..0000000
--- a/src/org/atriasoft/gale/event/EventInput.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.atriasoft.gale.event;
-
-import org.atriasoft.gale.key.KeyType;
-import org.atriasoft.gale.key.KeyStatus;
-import org.atriasoft.etk.math.Vector2f;
-import org.atriasoft.gale.key.KeySpecial;
-
-public class EventInput {
- private KeyType type;
- private KeyStatus status;
- private int inputId;
- private Vector2f position;
- private KeySpecial specialKey; //!< input key status (prevent change in time..)
- public EventInput(KeyType type, KeyStatus status, int inputId, Vector2f position, KeySpecial specialKey) {
- this.type = type;
- this.status = status;
- this.inputId = inputId;
- this.position = position;
- this.specialKey = specialKey;
- }
- public KeyType getType() {
- return type;
- }
- public void setType(KeyType type) {
- this.type = type;
- }
- public KeyStatus getStatus() {
- return status;
- }
- public void setStatus(KeyStatus status) {
- this.status = status;
- }
- public int getInputId() {
- return inputId;
- }
- public void setInputId(int inputId) {
- this.inputId = inputId;
- }
- public Vector2f getPosition() {
- return position;
- }
- public void setPosition(Vector2f position) {
- this.position = position;
- }
- public KeySpecial getSpecialKey() {
- return specialKey;
- }
- public void setSpecialKey(KeySpecial specialKey) {
- this.specialKey = specialKey;
- }
- @Override
- public String toString() {
- return "EventInput [type=" + type + ", status=" + status + ", inputId=" + inputId + ", position=" + position
- + ", specialKey=" + specialKey + "]";
- }
-
-}
diff --git a/src/org/atriasoft/gale/event/EventTime.java b/src/org/atriasoft/gale/event/EventTime.java
deleted file mode 100644
index 265111e..0000000
--- a/src/org/atriasoft/gale/event/EventTime.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package org.atriasoft.gale.event;
-
-public class EventTime {
- private long timeSystem; //!< Current system time (micro-second)
- private long timeUpAppl; //!< Current application wake up-time (micro-second)
- private long timeDelta; //!< Time from the last cycle call of the system (main appl tick) (micro-second)
- private long timeDeltaCall; //!< Time from the last call (when we can manage periodic call with specifying periode) (micro-second)
- public EventTime(long timeSystem, long timeUpAppl, long timeDelta, long timeDeltaCall) {
- super();
- this.timeSystem = timeSystem;
- this.timeUpAppl = timeUpAppl;
- this.timeDelta = timeDelta;
- this.timeDeltaCall = timeDeltaCall;
- }
- public long getTimeSystem() {
- return timeSystem;
- }
- public void setTimeSystem(long timeSystem) {
- this.timeSystem = timeSystem;
- }
- public long getTimeUpAppl() {
- return timeUpAppl;
- }
- public void setTimeUpAppl(long timeUpAppl) {
- this.timeUpAppl = timeUpAppl;
- }
- public long getTimeDelta() {
- return timeDelta;
- }
- public float getTimeDeltaSecond() {
- return (float)timeDelta*0.0000001f;
- }
- public void setTimeDelta(long timeDelta) {
- this.timeDelta = timeDelta;
- }
- public long getTimeDeltaCall() {
- return timeDeltaCall;
- }
- public float getTimeDeltaCallSecond() {
- return (float)timeDeltaCall*0.0000001f;
- }
- public void setTimeDeltaCall(long timeDeltaCall) {
- this.timeDeltaCall = timeDeltaCall;
- }
- @Override
- public String toString() {
- return "EventTime [timeSystem=" + timeSystem + "us, timeUpAppl=" + timeUpAppl + "us, timeDelta=" + timeDelta
- + "us, timeDeltaCall=" + timeDeltaCall + "us]";
- }
-
-}
diff --git a/src/org/atriasoft/gale/key/KeyStatus.java b/src/org/atriasoft/gale/key/KeyStatus.java
index 99a7135..08dd37a 100644
--- a/src/org/atriasoft/gale/key/KeyStatus.java
+++ b/src/org/atriasoft/gale/key/KeyStatus.java
@@ -17,4 +17,21 @@ public enum KeyStatus {
leave,
abort, // Appeare when an event is tranfert betwwen widgets (the widget which receive this has lost the events)
transfert // Appeare when an event is tranfert betwwen widgets (the widget which receive this has receive the transfert of the event)
+ ;
+
+ public static KeyStatus pressCount(final int i) {
+ switch (i) {
+ case 1:
+ return pressSingle;
+ case 2:
+ return pressDouble;
+ case 3:
+ return pressTriple;
+ case 4:
+ return pressQuad;
+ case 5:
+ return pressQuinte;
+ }
+ return unknow;
+ }
}
diff --git a/src/org/atriasoft/gale/resource/Resource.java b/src/org/atriasoft/gale/resource/Resource.java
index 7818354..a6052fc 100644
--- a/src/org/atriasoft/gale/resource/Resource.java
+++ b/src/org/atriasoft/gale/resource/Resource.java
@@ -1,127 +1,111 @@
package org.atriasoft.gale.resource;
-import java.util.ArrayList;
-import java.util.List;
-
import org.atriasoft.etk.Uri;
-import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.context.Context;
+import org.atriasoft.gale.internal.Log;
public abstract class Resource {
protected static final String NO_NAME_RESOURCE = "---";
protected static final int MAXRESOURCELEVEL = 5;
private static int idGenerated = 10;
+
+ /**
+ * @brief Get the current resource Manager
+ */
+ protected static ResourceManager getManager() {
+ return Context.getContext().getResourcesManager();
+ }
+
protected long uid = -1; //!< unique ID definition
protected int count = 1;
- protected int resourceLevel = MAXRESOURCELEVEL-1; //!< Level of the resource ==> for update priority [0..5] 0 must be update first.
+ protected int resourceLevel = MAXRESOURCELEVEL - 1; //!< Level of the resource ==> for update priority [0..5] 0 must be update first.
protected String name = NO_NAME_RESOURCE; //!< name of the resource ...
- protected boolean resourceHasBeenInit = false; //!< Know if the init function has bben called
- protected List listType = new ArrayList();
+
/**
* @brief generic protected contructor (use factory to create this class)
*/
protected Resource() {
this.uid = idGenerated++;
- this.addResourceType("gale::Resource");
- this.resourceHasBeenInit = true;
+ getManager().localAdd(this);
}
- protected Resource(String name) {
- this.resourceHasBeenInit = true;
+
+ protected Resource(final String name) {
this.name = name;
+ getManager().localAdd(this);
}
- protected Resource( Uri uri) {
- this.resourceHasBeenInit = true;
+
+ protected Resource(final Uri uri) {
this.name = uri.getValue();
+ getManager().localAdd(this);
}
- public void keep() {
- this.count++;
- }
+
+ public abstract void cleanUp();
+
public int getCount() {
return this.count;
}
- public void release() {
- this.count--;
- if (this.count == 0) {
-
- }
- }
- public abstract void cleanUp();
+
public long getId() {
return this.uid;
}
- public boolean resourceHasBeenCorectlyInit() {
- return this.resourceHasBeenInit;
- }
- /**
- * @brief get the current type of the Resource
- * @return the last type name of the element
- */
- public String getType() {
- if (this.listType.size() == 0) {
- return "gale::Resource";
- }
- return this.listType.get(this.listType.size()-1);
- }
- /**
- * @brief Get the herarchic of the Resource type.
- * @return descriptive string.
- */
- public String getTypeDescription() {
- String ret = "gale::Resource";
- for(String element : this.listType) {
- ret += "|";
- ret += element;
- }
- return ret;
- }
- /**
- * @brief check if the element herited from a specific type
- * @param type Type to check.
- * @return true if the element is compatible.
- */
- public boolean isTypeCompatible( String type) {
- if (type == "gale::Resource") {
- return true;
- }
- for(String element : this.listType) {
- if (type == element) {
- return true;
- }
- }
- return false;
- }
- /**
- * @brief Add a type of the list of Object.
- * @param type Type to add.
- */
- protected void addResourceType(String type) {
- if (type == null) {
- Log.error(" try to add a type with no value...");
- return;
- }
- this.listType.add(type);
- }
+
/**
* @brief get the resource name
* @return The requested name
*/
- public String getName() {
+ public String getName() {
return this.name;
}
- /**
- * @brief get the resource name
- * @param name The name to set.
- */
- public void setName( String name) {
- this.name = name;
- }
+
/**
* @brief Get the current resource level;
* @return value in [0..5]
*/
public int getResourceLevel() {
return this.resourceLevel;
+ }
+
+ public void keep() {
+ this.count++;
+ }
+
+ public void release() {
+ this.count--;
+ if (this.count == 0) {
+
+ }
+ }
+
+ /**
+ * @brief User request the reload of all resources (usefull when the file depend on DATA:GUI:xxx ...
+ */
+ public void reload() {
+ Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
};
+
+ /**
+ * @brief The current OpenGl context is removing ==> remove yout own system data
+ */
+ public void removeContext() {
+ Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
+ }
+
+ /**
+ * @brief The notification of the Context removing is too late, we have no more acces on the OpenGl context (thank you Android).
+ * Just update your internal state
+ */
+ public void removeContextToLate() {
+ Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
+ }
+
+ /**
+ * @brief get the resource name
+ * @param name The name to set.
+ */
+ public void setName(final String name) {
+ this.name = name;
+ }
+
/**
* @brief Call when need to send data on the harware (openGL)
* @note This is done asynchronously with the create of the Resource.
@@ -132,30 +116,4 @@ public abstract class Resource {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
return true;
}
-
- /**
- * @brief The current OpenGl context is removing ==> remove yout own system data
- */
- public void removeContext() {
- Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
- }
- /**
- * @brief The notification of the Context removing is too late, we have no more acces on the OpenGl context (thank you Android).
- * Juste update your internal state
- */
- public void removeContextToLate() {
- Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
- }
- /**
- * @brief User request the reload of all resources (usefull when the file depend on DATA:GUI:xxx ...
- */
- public void reload() {
- Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
- }
- /**
- * @brief Get the current resource Manager
- */
- protected static ResourceManager getManager() {
- return Context.getContext().getResourcesManager();
- }
}
diff --git a/src/org/atriasoft/gale/resource/ResourceColored3DObject.java b/src/org/atriasoft/gale/resource/ResourceColored3DObject.java
index 853bf87..6174947 100644
--- a/src/org/atriasoft/gale/resource/ResourceColored3DObject.java
+++ b/src/org/atriasoft/gale/resource/ResourceColored3DObject.java
@@ -15,9 +15,6 @@ import org.lwjgl.BufferUtils;
public class ResourceColored3DObject extends Resource {
public static ResourceColored3DObject create() {
final ResourceColored3DObject resource = new ResourceColored3DObject();
- if (resource.resourceHasBeenCorectlyInit() == false) {
- Log.critical("resource Is not correctly init: ResourceColored3DObject");
- }
getManager().localAdd(resource);
return resource;
}
@@ -31,7 +28,6 @@ public class ResourceColored3DObject extends Resource {
protected ResourceColored3DObject() {
super();
- addResourceType("ResourceColored3DObject");
// get the shader resource :
this.oGLPosition = 0;
this.program = ResourceProgram.create(new Uri("DATA_EGE", "simple3D.vert"), new Uri("DATA_EGE", "simple3D.frag"));
@@ -153,7 +149,7 @@ public class ResourceColored3DObject extends Resource {
}
public void drawCapsule(final float radius, final float size, int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
- final List tmpVertices = new ArrayList();
+ final List tmpVertices = new ArrayList<>();
lats = lats / 2 * 2;
// center to border (TOP)
@@ -249,7 +245,7 @@ public class ResourceColored3DObject extends Resource {
}
public void drawCone(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
- final List tmpVertices = new ArrayList();
+ final List tmpVertices = new ArrayList<>();
// center to border (TOP)
for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
@@ -289,7 +285,7 @@ public class ResourceColored3DObject extends Resource {
}
public void drawCubeLine(final Vector3f min, final Vector3f max, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) {
- final List vertices = new ArrayList();
+ final List vertices = new ArrayList<>();
vertices.add(new Vector3f(min.x, min.y, min.z));
vertices.add(new Vector3f(max.x, min.y, min.z));
@@ -329,7 +325,7 @@ public class ResourceColored3DObject extends Resource {
}
public void drawCylinder(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
- final List tmpVertices = new ArrayList();
+ final List tmpVertices = new ArrayList<>();
// center to border (TOP)
// center to border (TOP)
@@ -443,7 +439,7 @@ public class ResourceColored3DObject extends Resource {
}
public void drawSphere(final float radius, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) {
- final List tmpVertices = new ArrayList();
+ final List tmpVertices = new ArrayList<>();
for (int iii = 0; iii <= lats; ++iii) {
final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats);
final float z0 = radius * (float) Math.sin(lat0);
@@ -479,7 +475,7 @@ public class ResourceColored3DObject extends Resource {
}
public void drawSquare(final Vector3f size, final Matrix4f transformationMatrix, final Color tmpColor) {
- final List tmpVertices = new ArrayList();
+ final List tmpVertices = new ArrayList<>();
final int[] indices = { 0, 1, 2, 3, 2, 1, 4, 0, 6, 6, 0, 2, 5, 1, 4, 4, 1, 0, 7, 3, 1, 7, 1, 5, 5, 4, 7, 7, 4, 6, 7, 2, 3, 7, 6, 2 };
final Vector3f[] vertices = { new Vector3f(size.x, size.y, size.z), new Vector3f(-size.x, size.y, size.z), new Vector3f(size.x, -size.y, size.z), new Vector3f(-size.x, -size.y, size.z),
new Vector3f(size.x, size.y, -size.z), new Vector3f(-size.x, size.y, -size.z), new Vector3f(size.x, -size.y, -size.z), new Vector3f(-size.x, -size.y, -size.z) };
@@ -500,7 +496,7 @@ public class ResourceColored3DObject extends Resource {
}
public void drawTriangles(final List vertex, final List indice, final Matrix4f transformationMatrix, final Color tmpColor, final Vector3f offset) {
- final List tmpVertices = new ArrayList();
+ final List tmpVertices = new ArrayList<>();
for (int iii = 0; iii < indice.size() / 3; ++iii) {
tmpVertices.add(vertex.get(indice.get(iii * 3 + 0)).addNew(offset));
tmpVertices.add(vertex.get(indice.get(iii * 3 + 1)).addNew(offset));
diff --git a/src/org/atriasoft/gale/resource/ResourceManager.java b/src/org/atriasoft/gale/resource/ResourceManager.java
index 18324c0..0357a8a 100644
--- a/src/org/atriasoft/gale/resource/ResourceManager.java
+++ b/src/org/atriasoft/gale/resource/ResourceManager.java
@@ -3,146 +3,48 @@ package org.atriasoft.gale.resource;
import java.util.ArrayList;
import java.util.List;
+import org.atriasoft.etk.Uri;
import org.atriasoft.gale.internal.Log;
public class ResourceManager {
- private List resourceList = new ArrayList();
- private List resourceListToUpdate = new ArrayList();
+ private static final int MAX_RESOURCE_LEVEL = 9;
+ private final List resourceList = new ArrayList<>();
+ private List resourceListToUpdate = new ArrayList<>();
private boolean contextHasBeenRemoved = true;
private boolean exiting = false;
- private static final int MAX_RESOURCE_LEVEL = 9;
+
/**
* @brief initialize the internal variable
*/
public ResourceManager() {
}
+
/**
- * @brief Uninitiamize the resource manager, free all resources previously requested
- * @note when not free == > generate warning, because the segfault can appear after...
+ * @brief special end of application
*/
- //public ~Manager();
- /**
- * @brief remove all resources (un-init) out of the destructor (due to the system implementation)
- */
- public void unInit() {
- display();
- this.resourceListToUpdate.clear();
- // remove all resources ...
- for(Resource it : this.resourceList) {
- Log.warning("Find a resource that is not removed : [" + it.getId() + "]"
- + "='" + it.getName() + "' "
- + it.getCount() + " elements");
- }
- this.resourceList.clear();
+ public void applicationExiting() {
+ contextHasBeenDestroyed();
+ this.exiting = true;
}
- /**
- * @brief display in the log all the resources loaded ...
- */
- public void display(){
- Log.info("Resources loaded : ");
- // remove all resources ...
- for(Resource it : this.resourceList) {
- Log.info(" [" + it.getId() + "]"
- + it.getType()
- + "='" + it.getName() + "' "
- + it.getCount() + " elements");
- }
- Log.info("Resources ---");
- }
- /**
- * @brief Reload all resources from files, and send there in openGL card if needed.
- * @note If file is reference at THEMEXXX:///filename if the Theme change the file will reload the newOne
- */
- public void reLoadResources() {
- Log.info("------------- Resources re-loaded -------------");
- // remove all resources ...
- for (long jjj=0; jjj 0) {
- it.reload();
- Log.info(" [" + it.getId() + "]="+ it.getType());
- }
- }
- }
- }
- // TODO UNderstand why it is set here ...
- //gale::requestUpdateSize();
- Log.info("------------- Resources -------------");
- }
-
- /**
- * @brief Call by the system to send all the needed data on the graphic card chen they change ...
- * @param object The resources that might be updated
- */
- public void update(Resource object) {
- // check if not added before
- for (Resource it : this.resourceListToUpdate) {
- if (it == object) {
- // just prevent some double add ...
- return;
- }
- }
- // add it ...
- this.resourceListToUpdate.add(object);
- }
- /**
- * @brief Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other ....
- */
- public void updateContext(){
- if (this.exiting == true) {
- Log.error("Request update after application EXIT ...");
- return;
- }
- // TODO Check the number of call this ... Log.info("update open-gl context ... ");
- if (this.contextHasBeenRemoved == true) {
- // need to update all ...
- this.contextHasBeenRemoved = false;
- this.resourceListToUpdate.clear();
- synchronized(this.resourceList) {
- if (this.resourceList.size() != 0) {
- for (long jjj=0; jjj postponned
- this.resourceListToUpdate.add(it);
- }
- }
- }
- }
- }
- }
- } else {
- List resourceListToUpdate = null;
- synchronized(this.resourceListToUpdate) {
- resourceListToUpdate = this.resourceListToUpdate;
- this.resourceListToUpdate = new ArrayList();
- }
- if (resourceListToUpdate.size() != 0) {
- for (long jjj=0; jjj postponned
- this.resourceListToUpdate.add(it);
- }
- }
- }
- }
- }
- }
+
+ public void cleanInternalRemoved() {
+ //Log.info("remove object in Manager");
+ updateContext();
+ // TODO ...
+ // for (auto it(this.resourceList.begin()); it!=this.resourceList.end(); ++it) {
+ // if ((*it).expired() == true) {
+ // this.resourceList.erase(it);
+ // it = this.resourceList.begin();
+ // }
+ // }
}
+
/**
* @brief This is to inform the resources manager that we have no more openGl context ...
*/
public void contextHasBeenDestroyed() {
- for (Resource it : this.resourceList) {
+ for (final Resource it : this.resourceList) {
if (it.getCount() > 0) {
it.removeContextToLate();
}
@@ -150,17 +52,28 @@ public class ResourceManager {
// no context preent ...
this.contextHasBeenRemoved = true;
}
+
/**
- * @brief special end of application
+ * @brief display in the log all the resources loaded ...
*/
- public void applicationExiting(){
- contextHasBeenDestroyed();
- this.exiting = true;
+ public void display() {
+ Log.info("Resources loaded : ");
+ // remove all resources ...
+ for (final Resource it : this.resourceList) {
+ Log.info(" [" + it.getId() + "]" + it.getClass().getCanonicalName() + "='" + it.getName() + "' " + it.getCount() + " elements");
+ }
+ Log.info("Resources ---");
}
+
+ public void localAdd(final Resource object) {
+ // add at the end if no slot is free
+ this.resourceList.add(object);
+ }
+
// internal API to extent eResources in extern Soft
- public Resource localKeep(String filename) {
+ public Resource localKeep(final String filename) {
Log.verbose("KEEP (DEFAULT) : file : '" + filename + "' in " + this.resourceList.size() + " resources");
- for (Resource it : this.resourceList) {
+ for (final Resource it : this.resourceList) {
if (it == null) {
continue;
}
@@ -177,20 +90,118 @@ public class ResourceManager {
}
return null;
}
- public void localAdd(Resource object) {
- // add at the end if no slot is free
- this.resourceList.add(object);
+
+ public Resource localKeep(final Uri uri) {
+ // TODO Auto-generated method stub
+ return localKeep(uri.toString());
}
- public void cleanInternalRemoved() {
- //Log.info("remove object in Manager");
- updateContext();
- // TODO ...
-// for (auto it(this.resourceList.begin()); it!=this.resourceList.end(); ++it) {
-// if ((*it).expired() == true) {
-// this.resourceList.erase(it);
-// it = this.resourceList.begin();
-// }
-// }
+
+ /**
+ * @brief Reload all resources from files, and send there in openGL card if needed.
+ * @note If file is reference at THEMEXXX:///filename if the Theme change the file will reload the newOne
+ */
+ public void reLoadResources() {
+ Log.info("------------- Resources re-loaded -------------");
+ // remove all resources ...
+ for (long jjj = 0; jjj < MAX_RESOURCE_LEVEL; jjj++) {
+ Log.info(" Reload level : " + jjj + "/" + (MAX_RESOURCE_LEVEL - 1));
+ for (final Resource it : this.resourceList) {
+ if (jjj == it.getResourceLevel()) {
+ if (it.getCount() > 0) {
+ it.reload();
+ Log.info(" [" + it.getId() + "]=" + it.getClass().getCanonicalName());
+ }
+ }
+ }
+ }
+ // TODO UNderstand why it is set here ...
+ //gale::requestUpdateSize();
+ Log.info("------------- Resources -------------");
}
-
+
+ /**
+ * @brief Uninitiamize the resource manager, free all resources previously requested
+ * @note when not free == > generate warning, because the segfault can appear after...
+ */
+ //public ~Manager();
+ /**
+ * @brief remove all resources (un-init) out of the destructor (due to the system implementation)
+ */
+ public void unInit() {
+ display();
+ this.resourceListToUpdate.clear();
+ // remove all resources ...
+ for (final Resource it : this.resourceList) {
+ Log.warning("Find a resource that is not removed : [" + it.getId() + "]" + "='" + it.getName() + "' " + it.getCount() + " elements");
+ }
+ this.resourceList.clear();
+ }
+
+ /**
+ * @brief Call by the system to send all the needed data on the graphic card chen they change ...
+ * @param object The resources that might be updated
+ */
+ public void update(final Resource object) {
+ // check if not added before
+ for (final Resource it : this.resourceListToUpdate) {
+ if (it == object) {
+ // just prevent some double add ...
+ return;
+ }
+ }
+ // add it ...
+ this.resourceListToUpdate.add(object);
+ }
+
+ /**
+ * @brief Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other ....
+ */
+ public void updateContext() {
+ if (this.exiting == true) {
+ Log.error("Request update after application EXIT ...");
+ return;
+ }
+ // TODO Check the number of call this ... Log.info("update open-gl context ... ");
+ if (this.contextHasBeenRemoved == true) {
+ // need to update all ...
+ this.contextHasBeenRemoved = false;
+ this.resourceListToUpdate.clear();
+ synchronized (this.resourceList) {
+ if (this.resourceList.size() != 0) {
+ for (long jjj = 0; jjj < MAX_RESOURCE_LEVEL; jjj++) {
+ Log.verbose(" updateContext level (D) : " + jjj + "/" + (MAX_RESOURCE_LEVEL - 1));
+ for (final Resource it : this.resourceList) {
+ if (jjj == it.getResourceLevel()) {
+ //Log.debug("Update context named : " + lresourceList[iii].getName());
+ if (it.updateContext() == false) {
+ // Lock error ==> postponned
+ this.resourceListToUpdate.add(it);
+ }
+ }
+ }
+ }
+ }
+ }
+ } else {
+ List resourceListToUpdate = null;
+ synchronized (this.resourceListToUpdate) {
+ resourceListToUpdate = this.resourceListToUpdate;
+ this.resourceListToUpdate = new ArrayList<>();
+ }
+ if (resourceListToUpdate.size() != 0) {
+ for (long jjj = 0; jjj < MAX_RESOURCE_LEVEL; jjj++) {
+ Log.verbose(" updateContext level (U) : " + jjj + "/" + (MAX_RESOURCE_LEVEL - 1));
+ for (final Resource it : resourceListToUpdate) {
+ if (jjj == it.getResourceLevel()) {
+ if (it.updateContext() == false) {
+ // Lock error ==> postponned
+ this.resourceListToUpdate.add(it);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
}
diff --git a/src/org/atriasoft/gale/resource/ResourceProgram.java b/src/org/atriasoft/gale/resource/ResourceProgram.java
index adf74a4..e5f94fc 100644
--- a/src/org/atriasoft/gale/resource/ResourceProgram.java
+++ b/src/org/atriasoft/gale/resource/ResourceProgram.java
@@ -11,12 +11,13 @@ import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.etk.math.Vector3i;
-import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.backend3d.OpenGL;
+import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils;
+import org.lwjgl.opengl.GL11;
+import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL40;
-
class ProgAttributeElement {
public String name; //!< Name of the element
public int elementId; //!< openGl Id if this element == > can not exist ==> @ref m_isLinked
@@ -26,36 +27,88 @@ class ProgAttributeElement {
public class ResourceProgram extends Resource {
static final boolean DEBUG = false; // TODO externalize this ...
+
+ public static ResourceProgram create(final Uri uriVertexShader, final Uri uriFragmentShader) {
+ ResourceProgram resource;
+ Resource resource2 = null;
+ final String name = uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue();
+ if (name.isEmpty() == false && name != "---") {
+ resource2 = getManager().localKeep(name);
+ }
+ if (resource2 != null) {
+ if (resource2 instanceof ResourceProgram) {
+ resource2.keep();
+ return (ResourceProgram) resource2;
+ }
+ Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
+ return null;
+ }
+ resource = new ResourceProgram(uriVertexShader, uriFragmentShader);
+ getManager().localAdd(resource);
+ return resource;
+ }
+
+ public static FloatBuffer storeDataInFloatBuffer(final float[] data) {
+ final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
+ buffer.put(data);
+ buffer.flip();
+ return buffer;
+ }
+
+ public static FloatBuffer storeDataInFloatBufferColor(final List data) {
+ final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.size() * 4);
+ for (int iii = 0; iii < data.size(); iii++) {
+ buffer.put(iii * 3, data.get(iii).r);
+ buffer.put(iii * 3 + 1, data.get(iii).g);
+ buffer.put(iii * 3 + 2, data.get(iii).b);
+ buffer.put(iii * 3 + 3, data.get(iii).a);
+ }
+ buffer.flip();
+ return buffer;
+ }
+
+ public static FloatBuffer storeDataInFloatBufferVector3f(final List data) {
+ final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.size() * 3);
+ for (int iii = 0; iii < data.size(); iii++) {
+ buffer.put(iii * 3, data.get(iii).x);
+ buffer.put(iii * 3 + 1, data.get(iii).y);
+ buffer.put(iii * 3 + 2, data.get(iii).z);
+ }
+ buffer.flip();
+ return buffer;
+ }
+
private boolean exist = false; //!< the file existed
private int program = 0; //!< openGL id of the current program
private ResourceShader shaderVertex = null;
private ResourceShader shaderFragment = null;
- private List elementList = new ArrayList(); //!< List of all the attribute requested by the user
-// private List listOfVBOUsed = new ArrayList(); //!< retain the list of VBO used to disable it when unuse program ...
-// private boolean hasTexture = false; //!< A texture has been set to the current shader
-// private boolean hasTexture1 = false; //!< A texture has been set to the current shader
+
+ private final List elementList = new ArrayList<>(); //!< List of all the attribute requested by the user
+ private final List listOfVBOUsed = new ArrayList<>(); //!< retain the list of VBO used to disable it when unuse program ...
+ // private boolean hasTexture = false; //!< A texture has been set to the current shader
+ // private boolean hasTexture1 = false; //!< A texture has been set to the current shader
+
/**
* @brief Contructor of an opengl Program.
* @param uri Uri of the file
*/
- protected ResourceProgram(Uri uriVertexShader, Uri uriFragmentShader) {
+ protected ResourceProgram(final Uri uriVertexShader, final Uri uriFragmentShader) {
super(uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue());
- addResourceType("gale::resource::Program");
this.resourceLevel = 1;
Log.debug("OGL : load PROGRAM '" + uriVertexShader + "' && '" + uriFragmentShader + "'");
- shaderVertex = ResourceShader.create(uriVertexShader);
- if (shaderVertex == null) {
+ this.shaderVertex = ResourceShader.create(uriVertexShader);
+ if (this.shaderVertex == null) {
Log.error("Error while getting a specific shader filename: " + uriVertexShader);
return;
} else {
- Log.debug("Add shader on program: '"+ uriFragmentShader + "'");
+ Log.debug("Add shader on program: '" + uriFragmentShader + "'");
}
- shaderFragment = ResourceShader.create(uriFragmentShader);
- if (shaderFragment == null) {
+ this.shaderFragment = ResourceShader.create(uriFragmentShader);
+ if (this.shaderFragment == null) {
Log.error("Error while getting a specific shader filename: " + uriFragmentShader);
return;
} else {
- Log.debug("Add shader on program : "+ uriFragmentShader + "frag");
+ Log.debug("Add shader on program : " + uriFragmentShader + "frag");
}
if (OpenGL.hasContext() == true) {
updateContext();
@@ -63,6 +116,26 @@ public class ResourceProgram extends Resource {
getManager().update(this);
}
}
+
+ public void bindAttribute(final int attribute, final String variableName) {
+ if (this.exist == false) {
+ return;
+ }
+ OpenGL.programBindAttribute(this.program, attribute, variableName);
+ }
+
+ /**
+ * @brief Check If an Id is valid in the shader or not (sometime the shader have not some attribute, then we need to display some error)
+ * @return idElem Id of the Attribute that might be sended.
+ * @return true The id is valid, false otherwise
+ */
+ public boolean checkIdValidity(final int idElem) {
+ if (idElem < 0 || idElem > this.elementList.size()) {
+ return false;
+ }
+ return this.elementList.get(idElem).isLinked;
+ }
+
/**
* @brief Destructor, remove the current Program.
*/
@@ -78,35 +151,44 @@ public class ResourceProgram extends Resource {
this.shaderVertex = null;
}
this.elementList.clear();
-// this.hasTexture = false;
-// this.hasTexture1 = false;
+ // this.hasTexture = false;
+ // this.hasTexture1 = false;
}
- /**
- * @brief Check If an Id is valid in the shader or not (sometime the shader have not some attribute, then we need to display some error)
- * @return idElem Id of the Attribute that might be sended.
- * @return true The id is valid, false otherwise
- */
- public boolean checkIdValidity(int idElem){
- if ( idElem < 0
- || idElem > this.elementList.size()) {
- return false;
+
+ private float[] convertInFloat(final List data) {
+ final float[] out = new float[data.size() * 3];
+ for (int iii = 0; iii < data.size(); iii++) {
+ out[iii * 3] = data.get(iii).x;
+ out[iii * 3 + 1] = data.get(iii).y;
+ out[iii * 3 + 2] = data.get(iii).z;
}
- return this.elementList.get(idElem).isLinked;
+ return out;
}
+
+ // private void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) {
+ // int vboID = GL15.glGenBuffers();
+ // vbos.add(vboID);
+ // OpenGL.bindBuffer(vboID);
+ // FloatBuffer buffer = storeDataInFloatBuffer(data);
+ // GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
+ // GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0);
+ // GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
+ // }
+
/**
* @brief User request an attribute on this program.
* @note The attribute is send to the fragment shaders
* @param elementName Name of the requested attribute.
* @return An abstract ID of the current attribute (this value is all time availlable, even if the program will be reloaded)
*/
- public int getAttribute(String elementName) {
+ public int getAttribute(final String elementName) {
// check if it exist previously :
- for(int iii=0; iii this.elementList.size()) {
-// Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
-// return;
-// }
-// if (this.elementList.get(idElem).isLinked == false) {
-// return;
-// }
-// // check error of the VBO goog enought ...
-// if (vbo.getElementSize(index) <= 0) {
-// Log.error("Can not bind a VBO Buffer with an element size of : " + vbo.getElementSize(index) + " named=" + vbo.getName());
-// return;
-// }
-//
-// Log.verbose("[" + this.elementList.get(idElem).name + "] send " + vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " VBOindex=" + index);
-// OpenGL.bindBuffer(vbo.getGLID(index));
-// Log.verbose(" id=" + this.elementList.get(idElem).elementId);
-// Log.verbose(" eleme size=" + vbo.getElementSize(index));
-// OpenGL.bufferData(data, Usage.staticDraw);
-// OpenGL.vertexAttribPointerFloat(this.elementList.get(idElem).elementId, vbo.getElementSize(index)); // Pointer on the buffer
-// OpenGL.unbindBuffer();
-// //glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
-// this.listOfVBOUsed.add(this.elementList.get(idElem).elementId);
-// }
-// public void sendAttributePointer2(int idElem,
-// ResourceVirtualArrayObject vbo,
-// int index) {
-// int jumpBetweenSample = 0;
-// int offset = 0;
-// if (!this.exist) {
-// return;
-// }
-// if ( idElem < 0
-// || idElem > this.elementList.size()) {
-// Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
-// return;
-// }
-// if (this.elementList.get(idElem).isLinked == false) {
-// return;
-// }
-// // check error of the VBO good enough ...
-// if (vbo.getElementSize(index) <= 0) {
-// Log.error("Can not bind a VBO Buffer with an element size of : " + vbo.getElementSize(index) + " named=" + vbo.getName());
-// return;
-// }
-//
-// Log.verbose("[" + elementList.get(idElem).name + "] send " + vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " VBOindex=" + index);
-// GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, vbo.getGLID(index));
-// //checkGlError("glBindBuffer", __LINE__, _idElem);
-// Log.verbose(" id=" + elementList.get(idElem).elementId);
-// Log.verbose(" eleme size=" + vbo.getElementSize(index));
-// Log.verbose(" jump sample=" + jumpBetweenSample);
-// Log.verbose(" offset=" + offset);
-// GL20.glVertexAttribPointer(elementList.get(idElem).elementId, // attribute ID of openGL
-// vbo.getElementSize(index), // number of elements per vertex, here (r,g,b,a)
-// GL11.GL_FLOAT, // the type of each element
-// false, // take our values as-is
-// 0, // no extra data between each position
-// 0); // Pointer on the buffer
-// //checkGlError("glVertexAttribPointer", __LINE__, _idElem);
-// GL20.glEnableVertexAttribArray(elementList.get(idElem).elementId);
-// listOfVBOUsed.add(elementList.get(idElem).elementId);
-// //checkGlError("glEnableVertexAttribArray", __LINE__, _idElem);
-// }
-
-// private void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) {
-// int vboID = GL15.glGenBuffers();
-// vbos.add(vboID);
-// OpenGL.bindBuffer(vboID);
-// FloatBuffer buffer = storeDataInFloatBuffer(data);
-// GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
-// GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0);
-// GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
-// }
-
- private float[] convertInFloat(List data) {
- float[] out = new float[data.size()*3];
- for (int iii=0; iii this.elementList.size()) {
-// Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
-// return;
-// }
-// if (this.elementList.get(idElem).isLinked == false) {
-// return;
-// }
-// FloatBuffer buffer = storeDataInFloatBuffer(data);
-// //GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
-// Log.error("[" + this.elementList.get(idElem).name + "] send " + data.length + " element");
-// GL40.glVertexAttribPointer(
-// this.elementList.get(idElem).elementId,
-// data.length,
-// GL40.GL_FLOAT,
-// false,
-// 0,
-// buffer);
-// //checkGlError("glVertexAttribPointer", LINE, idElem);
-// GL40.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
-// //checkGlError("glEnableVertexAttribArray", LINE, idElem);
-// }
-//// public void sendAttribute(int idElem, etk::Vector data) {
-//// sendAttribute(idElem, 2/*u,v / x,y*/, data[0]);
-//// }
-// public void sendAttribute(int idElem, List data) {
-// sendAttribute3fv(idElem, convertInFloat(data));
-// }
- public void sendAttribute(int idElem, int nbElement, FloatBuffer data, int jumpBetweenSample) {
- if (this.exist == false) {
- return;
- }
- if ( idElem < 0
- || (long)idElem > this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (this.elementList.get(idElem).isLinked == false) {
- return;
- }
- //GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
- //Log.error("[" + this.elementList.get(idElem).name + "] send " + 3 + " element");
- GL40.glVertexAttribPointer(
- this.elementList.get(idElem).elementId,
- nbElement,
- GL40.GL_FLOAT,
- false,
- jumpBetweenSample*4, /* 4 is the size of float in the generic system...*/
- data);
- //checkGlError("glVertexAttribPointer", LINE, idElem);
- GL40.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
- //checkGlError("glEnableVertexAttribArray", LINE, idElem);
- }
-// public void sendAttribute(int idElem, etk::Vector> data) {
-// sendAttribute(idElem, 4/*r,g,b,a*/, data[0]);
-// }
-// public void sendAttribute(int idElem, etk::Vector data) {
-// sendAttribute(idElem, 1, data[0]);
-// }
+
+ // public void sendAttribute(int idElem, etk::Vector> data) {
+ // sendAttribute(idElem, 4/*r,g,b,a*/, data[0]);
+ // }
+ // public void sendAttribute(int idElem, etk::Vector data) {
+ // sendAttribute(idElem, 1, data[0]);
+ // }
/**
* @brief User request an Uniform on this program.
* @note uniform value is availlable for all the fragment shader in the program (only one value for all)
* @param elementName Name of the requested uniform.
* @return An abstract ID of the current uniform (this value is all time availlable, even if the program will be reloaded)
*/
- public int getUniform(String elementName){
+ public int getUniform(final String elementName) {
// check if it exist previously :
- for(int iii=0; iii this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- //Log.error("[" + this.elementList.get(idElem).name + "] send 1 matrix");
- // note : Android des not supported the transposition of the matrix, then we will done it oursef:
- /*
- if (transpose == true) {
- Matrix4f tmp = matrix;
- tmp.transpose();
- programLoadUniformMatrix(this.elementList.get(idElem).elementId, tmp.mat);
- } else {
- programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix.mat);
- }
- */
- OpenGL.programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix, transpose);
- }
-
- public void uniformColor(int idElem, Color value) {
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformColor(this.elementList.get(idElem).elementId, value);
- }
- public void uniformVector(int idElem, Vector2f value) {
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
- }
- public void uniformVector(int idElem, Vector2i value) {
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
- }
- public void uniformVector(int idElem, Vector3f value) {
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
- }
- public void uniformVector(int idElem, Vector3i value) {
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
+ return this.elementList.size() - 1;
}
/**
- * @brief Send 1 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- */
- public void uniformFloat(int idElem, float value1){
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1);
- }
- /**
- * @brief Send 2 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- * @param value2 Value to send at the Uniform
- */
- public void uniformFloat(int idElem, float value1, float value2) {
-
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2);
- }
- /**
- * @brief Send 3 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- * @param value2 Value to send at the Uniform
- * @param value3 Value to send at the Uniform
- */
- public void uniformFloat(int idElem, float value1, float value2, float value3){
-
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2, value3);
- }
- /**
- * @brief Send 4 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- * @param value2 Value to send at the Uniform
- * @param value3 Value to send at the Uniform
- * @param value4 Value to send at the Uniform
- */
- public void uniformFloat(int idElem, float value1, float value2, float value3, float value4) {
-
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2, value3, value4);
- }
-
- /**
- * @brief Send 1 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- */
- public void uniformInt(int idElem, int value1){
-
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1);
- }
- /**
- * @brief Send 2 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- * @param value2 Value to send at the Uniform
- */
- public void uniformInt(int idElem, int value1, int value2) {
-
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2);
- }
- /**
- * @brief Send 3 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- * @param value2 Value to send at the Uniform
- * @param value3 Value to send at the Uniform
- */
- public void uniformInt(int idElem, int value1, int value2, int value3){
-
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2, value3);
- }
- /**
- * @brief Send 4 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
- * @param idElem Id of the uniform that might be sended.
- * @param value1 Value to send at the Uniform
- * @param value2 Value to send at the Uniform
- * @param value3 Value to send at the Uniform
- * @param value4 Value to send at the Uniform
- */
- public void uniformInt(int idElem, int value1, int value2, int value3, int value4){
-
- if (this.exist == false) {
- return;
- }
- if (idElem<0 || (long)idElem>this.elementList.size()) {
- Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
- return;
- }
- if (false == this.elementList.get(idElem).isLinked) {
- return;
- }
- OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2, value3, value4);
- }
-
- /**
- * @brief Request the processing of this program
- */
- public void use() {
- //Log.verbose("Will use program : " + this.program);
- // event if it was 0 == > set it to prevent other use of the previous shader display ...
- OpenGL.programUse(this.program);
- }
-// /**
-// * @brief set the testure Id on the specify uniform element.
-// * @param idElem Id of the uniform that might be sended.
-// * @param textureOpenGlID Real openGL texture ID
-// */
-// public void setTexture0(int idElem, int textureOpenGlID){
-//
-// if (!this.exist) {
-// return;
-// }
-// if ( idElem < 0
-// || (long)idElem > this.elementList.size()) {
-// return;
-// }
-// if (this.elementList.get(idElem).isLinked == false) {
-// return;
-// }
-// OpenGL.activeTexture(GL13.GL_TEXTURE0);
-// // set the textureID
-// GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID);
-// // set the texture on the uniform attribute
-// GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/0);
-// this.hasTexture = true;
-// }
-// public void setTexture1(int idElem, int textureOpenGlID) {
-// if (!this.exist) {
-// return;
-// }
-// if ( idElem < 0
-// || (long)idElem > this.elementList.size()) {
-// return;
-// }
-// if (this.elementList.get(idElem).isLinked == false) {
-// return;
-// }
-// OpenGL.activeTexture(GL13.GL_TEXTURE1);
-// // set the textureID
-// GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID);
-// // set the texture on the uniform attribute
-// GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/1);
-// this.hasTexture1 = true;
-// }
- /**
- * @brief Stop the processing of this program
- */
- public void unUse() {
- //Log.verbose("Will UN-use program : " + this.program);
-
- if (this.exist == false) {
- return;
- }
-// for (Integer it : this.listOfVBOUsed) {
-// GL20.glDisableVertexAttribArray(it);
-// }
-// this.listOfVBOUsed.clear();
- // no need to disable program == > this only generate perturbation on speed ...
- OpenGL.programUse(-1);
- }
-
-
- /**
- * @brief This load/reload the data in the opengl context, needed when removed previously.
- */
- public boolean updateContext(){
- if (this.exist == true) {
- // Do nothing == > too dangerous ...
- } else {
- // create the Shader
- Log.debug("Create the Program ...'" + this.name + "'");
- this.program = OpenGL.programCreate();
- if (this.program < 0) {
- return true;
- }
- // first attach vertex shader, and after fragment shader
- if (this.shaderVertex != null) {
- OpenGL.programAttach(this.program, this.shaderVertex.getGLID());
- }
- if (this.shaderFragment != null) {
- OpenGL.programAttach(this.program, this.shaderFragment.getGLID());
- }
-
- OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, "in_position");
- OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, "tin_extureCoords");
- OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_NORMALS, "in_normal");
- OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_COLORS, "in_colors");
-
- if (OpenGL.programCompile(this.program) == false) {
- Log.error("Could not compile'PROGRAM':'" + this.name + "'");
- OpenGL.programRemove(this.program);
- return true;
- }
- // now get the old attribute requested priviously ...
- long iii = 0;
- for(ProgAttributeElement it : this.elementList) {
- if (it.isAttribute == true) {
- it.elementId = OpenGL.programGetAttributeLocation(this.program, it.name);
- it.isLinked = true;
- if (it.elementId<0) {
- Log.warning(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId);
- it.isLinked = false;
- } else {
- Log.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId);
- }
- } else {
- it.elementId = OpenGL.programGetUniformLocation(this.program, it.name);
- it.isLinked = true;
- if (it.elementId < 0) {
- Log.warning(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId);
- it.isLinked = false;
- } else {
- Log.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId);
- }
- }
- iii++;
- }
- // It will existed only when all is updated...
- this.exist = true;
- }
- return true;
- }
- /**
- * @brief remove the data from the opengl context.
- */
- public void removeContext(){
- if (this.exist == true) {
- OpenGL.programRemove(this.program);
- this.program = 0;
- this.exist = false;
- for(ProgAttributeElement it : this.elementList) {
- it.elementId=0;
- it.isLinked = false;
- }
- }
- }
- /**
- * @brief Special android spec! It inform us that all context is removed and after notify us...
- */
- public void removeContextToLate(){
-
- this.exist = false;
- this.program = 0;
- }
- /**
- * @brief Relode the shader from the file. used when a request of resouces reload is done.
- * @note this is really usefull when we tested the new themes or shader developpements.
- */
- public void reload(){
+ * @brief Relode the shader from the file. used when a request of resouces reload is done.
+ * @note this is really usefull when we tested the new themes or shader developpements.
+ */
+ @Override
+ public void reload() {
/* TODO ...
etk::file file(this.name, etk::FILETYPEDATA);
if (file.Exist() == false) {
@@ -803,34 +295,574 @@ public class ResourceProgram extends Resource {
file.fRead(this.fileData, 1, fileSize);
// close the file:
file.fClose();
- */
+ */
// now change the OGL context ...
removeContext();
updateContext();
}
- public static ResourceProgram create(Uri uriVertexShader, Uri uriFragmentShader) {
- ResourceProgram resource;
- Resource resource2 = null;
- String name = uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue();
- if (name.isEmpty() == false && name != "---") {
- resource2 = getManager().localKeep(name);
- }
- if (resource2 != null) {
- if (resource2 instanceof ResourceProgram) {
- resource2.keep();
- return (ResourceProgram)resource2;
+ /**
+ * @brief remove the data from the opengl context.
+ */
+ @Override
+ public void removeContext() {
+ if (this.exist == true) {
+ OpenGL.programRemove(this.program);
+ this.program = 0;
+ this.exist = false;
+ for (final ProgAttributeElement it : this.elementList) {
+ it.elementId = 0;
+ it.isLinked = false;
}
- Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
- return null;
}
- resource = new ResourceProgram(uriVertexShader, uriFragmentShader);
- if (resource.resourceHasBeenCorectlyInit() == false) {
- Log.critical("resource Is not correctly init : ResourceProgram" );
- return null;
+ }
+
+ /**
+ * @brief Special android spec! It inform us that all context is removed and after notify us...
+ */
+ @Override
+ public void removeContextToLate() {
+
+ this.exist = false;
+ this.program = 0;
+ }
+
+ /**
+ * @brief Send attribute table to the specified ID attribute (not send if does not really exist in the openGL program).
+ * @param idElem Id of the Attribute that might be sent.
+ * @param nbElement Specifies the number of elements that are to be modified.
+ * @param pointer Pointer on the data that might be sent.
+ * @param jumpBetweenSample Number of byte to jump between 2 vertex (this permit to interlace informations)
+ */
+ // public void sendAttribute3fv(int idElem, float[] data) {
+ // if (!this.exist) {
+ // return;
+ // }
+ // if ( idElem < 0
+ // || (long)idElem > this.elementList.size()) {
+ // Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
+ // return;
+ // }
+ // if (this.elementList.get(idElem).isLinked == false) {
+ // return;
+ // }
+ // FloatBuffer buffer = storeDataInFloatBuffer(data);
+ // //GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
+ // Log.error("[" + this.elementList.get(idElem).name + "] send " + data.length + " element");
+ // GL40.glVertexAttribPointer(
+ // this.elementList.get(idElem).elementId,
+ // data.length,
+ // GL40.GL_FLOAT,
+ // false,
+ // 0,
+ // buffer);
+ // //checkGlError("glVertexAttribPointer", LINE, idElem);
+ // GL40.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
+ // //checkGlError("glEnableVertexAttribArray", LINE, idElem);
+ // }
+ //// public void sendAttribute(int idElem, etk::Vector data) {
+ //// sendAttribute(idElem, 2/*u,v / x,y*/, data[0]);
+ //// }
+ // public void sendAttribute(int idElem, List data) {
+ // sendAttribute3fv(idElem, convertInFloat(data));
+ // }
+ public void sendAttribute(final int idElem, final int nbElement, final FloatBuffer data, final int jumpBetweenSample) {
+ if (this.exist == false) {
+ return;
}
- getManager().localAdd(resource);
- return resource;
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (this.elementList.get(idElem).isLinked == false) {
+ return;
+ }
+ //GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
+ //Log.error("[" + this.elementList.get(idElem).name + "] send " + 3 + " element");
+ GL40.glVertexAttribPointer(this.elementList.get(idElem).elementId, nbElement, GL40.GL_FLOAT, false, jumpBetweenSample * 4, /* 4 is the size of float in the generic system...*/
+ data);
+ //checkGlError("glVertexAttribPointer", LINE, idElem);
+ GL40.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
+ //checkGlError("glEnableVertexAttribArray", LINE, idElem);
+ }
+
+ /**
+ * @brief Send attribute table to the spefified ID attribure (not send if does not really exist in the openGL program).
+ * @param idElem Id of the Attribute that might be sended.
+ * @param vbo Reference on the buffer to send.
+ * @param index Reference on the buffer to send.
+ * @param jumpBetweenSample Number of byte to jump between 2 vertex (this permit to enterlace informations)
+ * @param offset offset of start the elements send.
+ */
+ // public void sendAttributePointer(int idElem,
+ // ResourceVirtualArrayObject vbo,
+ // int index,
+ // int coordinateSize,
+ // float[] data){
+ //
+ // if (!this.exist) {
+ // return;
+ // }
+ // if ( idElem < 0
+ // || (long)idElem > this.elementList.size()) {
+ // Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) + "]");
+ // return;
+ // }
+ // if (this.elementList.get(idElem).isLinked == false) {
+ // return;
+ // }
+ // // check error of the VBO goog enought ...
+ // if (vbo.getElementSize(index) <= 0) {
+ // Log.error("Can not bind a VBO Buffer with an element size of : " + vbo.getElementSize(index) + " named=" + vbo.getName());
+ // return;
+ // }
+ //
+ // Log.verbose("[" + this.elementList.get(idElem).name + "] send " + vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " VBOindex=" + index);
+ // OpenGL.bindBuffer(vbo.getGLID(index));
+ // Log.verbose(" id=" + this.elementList.get(idElem).elementId);
+ // Log.verbose(" eleme size=" + vbo.getElementSize(index));
+ // OpenGL.bufferData(data, Usage.staticDraw);
+ // OpenGL.vertexAttribPointerFloat(this.elementList.get(idElem).elementId, vbo.getElementSize(index)); // Pointer on the buffer
+ // OpenGL.unbindBuffer();
+ // //glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
+ // this.listOfVBOUsed.add(this.elementList.get(idElem).elementId);
+ // }
+ public void sendAttributePointer(final int idElem, final ResourceVirtualBufferObject vbo, final int index) {
+ final int jumpBetweenSample = 0;
+ final int offset = 0;
+ if (!this.exist) {
+ return;
+ }
+ if (idElem < 0 || idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (this.elementList.get(idElem).isLinked == false) {
+ return;
+ }
+
+ Log.verbose("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getGL_ID(index) + " VBOindex=" + index);
+ GL20.glBindBuffer(GL20.GL_ARRAY_BUFFER, vbo.getGL_ID(index));
+ //checkGlError("glBindBuffer", __LINE__, _idElem);
+ Log.verbose(" id=" + this.elementList.get(idElem).elementId);
+ Log.verbose(" jump sample=" + jumpBetweenSample);
+ Log.verbose(" offset=" + offset);
+ GL20.glVertexAttribPointer(this.elementList.get(idElem).elementId, // attribute ID of openGL
+ vbo.getElementSize(index), // number of elements per vertex, here (r,g,b,a)
+ GL11.GL_FLOAT, // the type of each element
+ false, // take our values as-is
+ 0, // no extra data between each position
+ 0); // Pointer on the buffer
+ //checkGlError("glVertexAttribPointer", __LINE__, _idElem);
+ GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
+ this.listOfVBOUsed.add(this.elementList.get(idElem).elementId);
+ //checkGlError("glEnableVertexAttribArray", __LINE__, _idElem);
+ }
+
+ public void uniformColor(final int idElem, final Color value) {
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformColor(this.elementList.get(idElem).elementId, value);
+ }
+
+ /**
+ * @brief Send 1 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ */
+ public void uniformFloat(final int idElem, final float value1) {
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1);
+ }
+
+ /**
+ * @brief Send 2 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ * @param value2 Value to send at the Uniform
+ */
+ public void uniformFloat(final int idElem, final float value1, final float value2) {
+
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2);
+ }
+
+ /**
+ * @brief Send 3 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ * @param value2 Value to send at the Uniform
+ * @param value3 Value to send at the Uniform
+ */
+ public void uniformFloat(final int idElem, final float value1, final float value2, final float value3) {
+
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2, value3);
+ }
+
+ /**
+ * @brief Send 4 float uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ * @param value2 Value to send at the Uniform
+ * @param value3 Value to send at the Uniform
+ * @param value4 Value to send at the Uniform
+ */
+ public void uniformFloat(final int idElem, final float value1, final float value2, final float value3, final float value4) {
+
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformFloat(this.elementList.get(idElem).elementId, value1, value2, value3, value4);
+ }
+
+ /**
+ * @brief Send 1 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ */
+ public void uniformInt(final int idElem, final int value1) {
+
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1);
+ }
+
+ /**
+ * @brief Send 2 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ * @param value2 Value to send at the Uniform
+ */
+ public void uniformInt(final int idElem, final int value1, final int value2) {
+
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2);
+ }
+
+ /**
+ * @brief Send 3 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ * @param value2 Value to send at the Uniform
+ * @param value3 Value to send at the Uniform
+ */
+ public void uniformInt(final int idElem, final int value1, final int value2, final int value3) {
+
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2, value3);
+ }
+
+ /**
+ * @brief Send 4 signed integer uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param value1 Value to send at the Uniform
+ * @param value2 Value to send at the Uniform
+ * @param value3 Value to send at the Uniform
+ * @param value4 Value to send at the Uniform
+ */
+ public void uniformInt(final int idElem, final int value1, final int value2, final int value3, final int value4) {
+
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformInt(this.elementList.get(idElem).elementId, value1, value2, value3, value4);
+ }
+
+ /**
+ * @brief Send a uniform element to the spefified ID (not send if does not really exist in the openGL program)
+ * @param idElem Id of the uniform that might be sended.
+ * @param matrix Matrix that might be sended.
+ * @param transpose Transpose the matrix (needed all the taime in the normal openGl access (only not done in the openGL-ES2 due to the fact we must done it ourself)
+ */
+ public void uniformMatrix(final int idElem, final Matrix4f matrix) {
+ uniformMatrix(idElem, matrix, true);
+ }
+
+ public void uniformMatrix(final int idElem, final Matrix4f matrix, final boolean transpose/*=true*/) {
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ //Log.error("[" + this.elementList.get(idElem).name + "] send 1 matrix");
+ // note : Android des not supported the transposition of the matrix, then we will done it oursef:
+ /*
+ if (transpose == true) {
+ Matrix4f tmp = matrix;
+ tmp.transpose();
+ programLoadUniformMatrix(this.elementList.get(idElem).elementId, tmp.mat);
+ } else {
+ programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix.mat);
+ }
+ */
+ OpenGL.programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix, transpose);
+ }
+
+ public void uniformVector(final int idElem, final Vector2f value) {
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
+ }
+
+ public void uniformVector(final int idElem, final Vector2i value) {
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
+ }
+
+ public void uniformVector(final int idElem, final Vector3f value) {
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
+ }
+
+ public void uniformVector(final int idElem, final Vector3i value) {
+ if (this.exist == false) {
+ return;
+ }
+ if (idElem < 0 || (long) idElem > this.elementList.size()) {
+ Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
+ return;
+ }
+ if (false == this.elementList.get(idElem).isLinked) {
+ return;
+ }
+ OpenGL.programLoadUniformVector(this.elementList.get(idElem).elementId, value);
+ }
+
+ // /**
+ // * @brief set the testure Id on the specify uniform element.
+ // * @param idElem Id of the uniform that might be sended.
+ // * @param textureOpenGlID Real openGL texture ID
+ // */
+ // public void setTexture0(int idElem, int textureOpenGlID){
+ //
+ // if (!this.exist) {
+ // return;
+ // }
+ // if ( idElem < 0
+ // || (long)idElem > this.elementList.size()) {
+ // return;
+ // }
+ // if (this.elementList.get(idElem).isLinked == false) {
+ // return;
+ // }
+ // OpenGL.activeTexture(GL13.GL_TEXTURE0);
+ // // set the textureID
+ // GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID);
+ // // set the texture on the uniform attribute
+ // GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/0);
+ // this.hasTexture = true;
+ // }
+ // public void setTexture1(int idElem, int textureOpenGlID) {
+ // if (!this.exist) {
+ // return;
+ // }
+ // if ( idElem < 0
+ // || (long)idElem > this.elementList.size()) {
+ // return;
+ // }
+ // if (this.elementList.get(idElem).isLinked == false) {
+ // return;
+ // }
+ // OpenGL.activeTexture(GL13.GL_TEXTURE1);
+ // // set the textureID
+ // GL13.glBindTexture(GL13.GL_TEXTURE_2D, textureOpenGlID);
+ // // set the texture on the uniform attribute
+ // GL20.glUniform1i(this.elementList.get(idElem).elementId, /*GLTEXTURE*/1);
+ // this.hasTexture1 = true;
+ // }
+ /**
+ * @brief Stop the processing of this program
+ */
+ public void unUse() {
+ //Log.verbose("Will UN-use program : " + this.program);
+
+ if (this.exist == false) {
+ return;
+ }
+ for (final Integer it : this.listOfVBOUsed) {
+ GL20.glDisableVertexAttribArray(it);
+ }
+ this.listOfVBOUsed.clear();
+ // no need to disable program == > this only generate perturbation on speed ...
+ OpenGL.programUse(-1);
+ }
+
+ /**
+ * @brief This load/reload the data in the opengl context, needed when removed previously.
+ */
+ @Override
+ public boolean updateContext() {
+ if (this.exist == true) {
+ // Do nothing == > too dangerous ...
+ } else {
+ // create the Shader
+ Log.debug("Create the Program ...'" + this.name + "'");
+ this.program = OpenGL.programCreate();
+ if (this.program < 0) {
+ return true;
+ }
+ // first attach vertex shader, and after fragment shader
+ if (this.shaderVertex != null) {
+ OpenGL.programAttach(this.program, this.shaderVertex.getGLID());
+ }
+ if (this.shaderFragment != null) {
+ OpenGL.programAttach(this.program, this.shaderFragment.getGLID());
+ }
+
+ OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, "in_position");
+ OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, "tin_extureCoords");
+ OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_NORMALS, "in_normal");
+ OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_COLORS, "in_colors");
+
+ if (OpenGL.programCompile(this.program) == false) {
+ Log.error("Could not compile'PROGRAM':'" + this.name + "'");
+ OpenGL.programRemove(this.program);
+ return true;
+ }
+ // now get the old attribute requested priviously ...
+ long iii = 0;
+ for (final ProgAttributeElement it : this.elementList) {
+ if (it.isAttribute == true) {
+ it.elementId = OpenGL.programGetAttributeLocation(this.program, it.name);
+ it.isLinked = true;
+ if (it.elementId < 0) {
+ Log.warning(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId);
+ it.isLinked = false;
+ } else {
+ Log.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId);
+ }
+ } else {
+ it.elementId = OpenGL.programGetUniformLocation(this.program, it.name);
+ it.isLinked = true;
+ if (it.elementId < 0) {
+ Log.warning(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId);
+ it.isLinked = false;
+ } else {
+ Log.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId);
+ }
+ }
+ iii++;
+ }
+ // It will existed only when all is updated...
+ this.exist = true;
+ }
+ return true;
+ }
+
+ /**
+ * @brief Request the processing of this program
+ */
+ public void use() {
+ //Log.verbose("Will use program : " + this.program);
+ // event if it was 0 == > set it to prevent other use of the previous shader display ...
+ OpenGL.programUse(this.program);
}
}
diff --git a/src/org/atriasoft/gale/resource/ResourceShader.java b/src/org/atriasoft/gale/resource/ResourceShader.java
index a2994b5..60380fd 100644
--- a/src/org/atriasoft/gale/resource/ResourceShader.java
+++ b/src/org/atriasoft/gale/resource/ResourceShader.java
@@ -1,25 +1,52 @@
package org.atriasoft.gale.resource;
import org.atriasoft.etk.Uri;
-import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.ShaderType;
+import org.atriasoft.gale.internal.Log;
public class ResourceShader extends Resource {
-
+
+ public static ResourceShader create(final Uri uriShader) {
+ ResourceShader resource;
+ Resource resource2;
+ final String name = uriShader.getValue();
+ if (name.isEmpty() == false && name != "---") {
+ resource2 = getManager().localKeep(name);
+ } else {
+ Log.error("Can not create a shader without a filaname");
+ return null;
+ }
+ if (resource2 != null) {
+ if (resource2 instanceof ResourceShader) {
+ resource2.keep();
+ return (ResourceShader) resource2;
+ }
+ Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
+ return null;
+ }
+ resource = new ResourceShader(uriShader);
+ if (resource == null) {
+ Log.error("allocation error of a resource : " + name);
+ return null;
+ }
+ getManager().localAdd(resource);
+ return resource;
+ }
+
private boolean exist = false; //!< The shader file existed and has been loaded
- private String fileData = ""; //!< A copy of the data loaded from the file (usefull only when opengl context is removed)
+ private final String fileData = ""; //!< A copy of the data loaded from the file (usefull only when opengl context is removed)
private int shader = -1; //!< opengl id of this element
private final ShaderType type; //!< Type of the current shader(vertex/fragment)
private final Uri uri;
+
/**
* @brief Contructor of an opengl Shader
* @param filename Standard file name format. see @ref etk::FSNode
*/
- protected ResourceShader(Uri uri) {
+ protected ResourceShader(final Uri uri) {
super(uri);
this.uri = uri;
- addResourceType("gale::Shader");
this.resourceLevel = 0;
Log.debug("OGL : load SHADER '" + uri + "'");
// load data from file "all the time ..."
@@ -35,13 +62,16 @@ public class ResourceShader extends Resource {
}
reload();
}
+
/**
* @brief Destructor, remove the current Shader
*/
+ @Override
public void cleanUp() {
OpenGL.shaderRemove(this.shader);
this.exist = false;
- }
+ };
+
/**
* @brief get the opengl reference id of this shader.
* @return The opengl id.
@@ -49,50 +79,20 @@ public class ResourceShader extends Resource {
public int getGLID() {
return this.shader;
};
+
/**
* @brief get the opengl type of this shader.
* @return The type of this loaded shader.
*/
public ShaderType getShaderType() {
return this.type;
- };
- /**
- * @brief This load/reload the data in the opengl context, needed when removed previously.
- */
- public boolean updateContext(){
- if (this.exist == true) {
- // Do nothing == > too dangerous ...
- } else {
- this.shader = OpenGL.shaderLoad(this.uri.get(), type);
- // create the Shader
- if (this.shader < 0) {
- return true;
- }
- this.exist = true;
- }
- return true;
- }
- /**
- * @brief remove the data from the opengl context.
- */
- public void removeContext(){
- if (true == this.exist) {
- OpenGL.shaderRemove(this.shader);
- this.shader = -1;
- this.exist = false;
- }
- }
- /**
- * @brief Special android spec! It inform us that all context is removed and after notify us...
- */
- public void removeContextToLate(){
- this.exist = false;
- this.shader = -1;
}
+
/**
* @brief Relode the shader from the file. used when a request of resouces reload is done.
* @note this is really usefull when we tested the new themes or shader developpements.
*/
+ @Override
public void reload() {
Log.verbose("load shader:\n-----------------------------------------------------------------\n" + this.fileData + "\n-----------------------------------------------------------------");
// now change the OGL context ...
@@ -108,34 +108,43 @@ public class ResourceShader extends Resource {
getManager().update(this);
}
}
- public static ResourceShader create(Uri uriShader) {
- ResourceShader resource;
- Resource resource2;
- String name = uriShader.getValue();
- if (name.isEmpty() == false && name != "---") {
- resource2 = getManager().localKeep(name);
+
+ /**
+ * @brief remove the data from the opengl context.
+ */
+ @Override
+ public void removeContext() {
+ if (true == this.exist) {
+ OpenGL.shaderRemove(this.shader);
+ this.shader = -1;
+ this.exist = false;
+ }
+ }
+
+ /**
+ * @brief Special android spec! It inform us that all context is removed and after notify us...
+ */
+ @Override
+ public void removeContextToLate() {
+ this.exist = false;
+ this.shader = -1;
+ }
+
+ /**
+ * @brief This load/reload the data in the opengl context, needed when removed previously.
+ */
+ @Override
+ public boolean updateContext() {
+ if (this.exist == true) {
+ // Do nothing == > too dangerous ...
} else {
- Log.error("Can not create a shader without a filaname");
- return null;
- }
- if (resource2 != null) {
- if (resource2 instanceof ResourceShader) {
- resource2.keep();
- return (ResourceShader)resource2;
+ this.shader = OpenGL.shaderLoad(this.uri.get(), this.type);
+ // create the Shader
+ if (this.shader < 0) {
+ return true;
}
- Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
- return null;
+ this.exist = true;
}
- resource = new ResourceShader(uriShader);
- if (resource == null) {
- Log.error("allocation error of a resource : " + name);
- return null;
- }
- if (resource.resourceHasBeenCorectlyInit() == false) {
- Log.critical("resource Is not correctly init : ResourceProgram" );
- return null;
- }
- getManager().localAdd(resource);
- return resource;
+ return true;
}
}
diff --git a/src/org/atriasoft/gale/resource/ResourceTexture.java b/src/org/atriasoft/gale/resource/ResourceTexture.java
index 443e85e..d097896 100644
--- a/src/org/atriasoft/gale/resource/ResourceTexture.java
+++ b/src/org/atriasoft/gale/resource/ResourceTexture.java
@@ -5,8 +5,8 @@ import java.nio.ByteBuffer;
import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.etk.math.Vector2i;
-import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.backend3d.OpenGL;
+import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.tools.ImageLoader;
import org.atriasoft.gale.tools.ImageRawData;
import org.lwjgl.opengl.GL11;
@@ -14,189 +14,24 @@ import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
public class ResourceTexture extends Resource {
- private static int[] textureIdBinding = {
- GL13.GL_TEXTURE0,
- GL13.GL_TEXTURE1,
- GL13.GL_TEXTURE2,
- GL13.GL_TEXTURE3,
- GL13.GL_TEXTURE4,
- GL13.GL_TEXTURE5,
- GL13.GL_TEXTURE6,
- GL13.GL_TEXTURE7,
- GL13.GL_TEXTURE8,
- GL13.GL_TEXTURE9,
- GL13.GL_TEXTURE10,
- GL13.GL_TEXTURE11,
- GL13.GL_TEXTURE12,
- GL13.GL_TEXTURE13,
- GL13.GL_TEXTURE14,
- GL13.GL_TEXTURE15,
- GL13.GL_TEXTURE16,
- GL13.GL_TEXTURE17,
- GL13.GL_TEXTURE18,
- GL13.GL_TEXTURE19,
- GL13.GL_TEXTURE20,
- GL13.GL_TEXTURE21,
- GL13.GL_TEXTURE22,
- GL13.GL_TEXTURE23,
- GL13.GL_TEXTURE24,
- GL13.GL_TEXTURE25,
- GL13.GL_TEXTURE26,
- GL13.GL_TEXTURE27,
- GL13.GL_TEXTURE28,
- GL13.GL_TEXTURE29,
- GL13.GL_TEXTURE30,
- GL13.GL_TEXTURE31
- };
public enum TextureColorMode {
rgb, //!< red/green/blue data
rgba //!< red/green/blue/alpha data
- };
- protected int texId = -1; //!< openGl textureID.
- protected Vector2f endPointSize = new Vector2f(-1, -1); //!< some image are not square == > we need to sqared it to prevent some openGl api error the the displayable size is not all the time 0.0 . 1.0.
- protected boolean loaded = false; //!< internal state of the openGl system.
- // Image properties:
- private ByteBuffer data = null; //!< pointer on the image data.
- private Vector2i size = new Vector2i(-1,-1); //!< size of the image data.
- private TextureColorMode dataColorSpace = TextureColorMode.rgb; //!< Color space of the image.
- private int textureUnit = 0; // number of lines and colomns in the texture (multiple texturing in a single texture)
- private String filename = "";
- /**
- * @brief get the next power 2 if the input
- * @param value Value that we want the next power of 2
- * @return result value
- */
- private static int nextP2(int value) {
- int val=1;
- for (int iii=1; iii<31; iii++) {
- if (value <= val) {
- return val;
- }
- val *=2;
- }
- Log.critical("impossible CASE....");
- return val;
}
- // Public API:
- protected ResourceTexture(String filename, int textureUnit) {
- super(filename + "__" + textureUnit);
- this.filename = filename;
- this.textureUnit = textureUnit;
- addResourceType("gale::resource::Texture");
- }
- protected ResourceTexture(Uri filename, int textureUnit) {
- super(filename + "__" + textureUnit);
- this.filename = filename.get();
- this.textureUnit = textureUnit;
- addResourceType("gale::resource::Texture");
- }
- protected ResourceTexture() {
- super();
- addResourceType("gale::resource::Texture");
- }
- public void cleanUp() {
- removeContext();
- }
- // Gale internal API:
- @Override
- public boolean updateContext() {
- if (this.loaded == true) {
- return true;
- }
- // Request a new texture at openGl :
- texId = GL11.glGenTextures();
- GL13.glActiveTexture(textureUnit);
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId);
-
- // All RGB bytes are aligned to each other and each component is 1 byte
- GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
- Log.info("TEXTURE: add [" + getId() + "]=" + this.size + " OGlId=" + this.texId);
- if (dataColorSpace == TextureColorMode.rgb) {
- GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x, this.size.y, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, data);
- } else {
- GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x, this.size.y, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data);
- }
- // generate multi-texture mapping
- GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
-
- // Setup the ST coordinate system
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
-
- // Setup what to do when the texture has to be scaled
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
- GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
- // now the data is loaded
- this.loaded = true;
- return true;
- }
- public void removeContext() {
- if (true == this.loaded) {
- // Request remove texture ...
- Log.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
- // TODO Check if we are in the correct thread
- GL11.glDeleteTextures(this.texId);
- this.loaded = false;
- }
- }
- public void removeContextToLate() {
- this.loaded = false;
- this.texId = -1;
- }
- public int getRendererId() {
- return this.texId;
- };
- public Vector2f getUsableSize() {
- return this.endPointSize;
- };
- public Vector2i getOpenGlSize() {
- return this.size;
- };
- // flush the data to send it at the openGl system
- public void flush() {
- // request to the manager to be call at the next update ...
- getManager().update(this);
- }
- public void setTexture(ByteBuffer data,
- Vector2i size,
- TextureColorMode dataColorSpace,
- int textureUnit) {
- this.data = data;
- this.size = size;
- this.textureUnit = textureUnit;
- this.endPointSize.x = (float)size.x;
- this.endPointSize.y = (float)size.y;
- this.dataColorSpace = dataColorSpace;
- flush();
- }
- public void bindForRendering(int idTexture) {
- if (this.loaded == false) {
- return;
- }
- GL13.glActiveTexture(textureIdBinding[idTexture]);
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texId);
- if (dataColorSpace == TextureColorMode.rgb) {
- OpenGL.enable(OpenGL.Flag.flag_cullFace);
- OpenGL.enable(OpenGL.Flag.flag_back);
- }
- }
- public void unBindForRendering() {
- if (this.loaded == false) {
- return;
- }
- if (dataColorSpace == TextureColorMode.rgb) {
- OpenGL.disable(OpenGL.Flag.flag_cullFace);
- OpenGL.disable(OpenGL.Flag.flag_back);
- }
- }
-
- public static ResourceTexture createFromPng(Uri uriTexture) {
+
+ private static int[] textureIdBinding = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2, GL13.GL_TEXTURE3, GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7,
+ GL13.GL_TEXTURE8, GL13.GL_TEXTURE9, GL13.GL_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13, GL13.GL_TEXTURE14, GL13.GL_TEXTURE15, GL13.GL_TEXTURE16, GL13.GL_TEXTURE17,
+ GL13.GL_TEXTURE18, GL13.GL_TEXTURE19, GL13.GL_TEXTURE20, GL13.GL_TEXTURE21, GL13.GL_TEXTURE22, GL13.GL_TEXTURE23, GL13.GL_TEXTURE24, GL13.GL_TEXTURE25, GL13.GL_TEXTURE26,
+ GL13.GL_TEXTURE27, GL13.GL_TEXTURE28, GL13.GL_TEXTURE29, GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 };;
+
+ public static ResourceTexture createFromPng(final Uri uriTexture) {
return createFromPng(uriTexture, 1);
}
- public static ResourceTexture createFromPng(Uri uriTexture, int textureUnit) {
+
+ public static ResourceTexture createFromPng(final Uri uriTexture, final int textureUnit) {
ResourceTexture resource;
Resource resource2;
- String name = uriTexture.getValue();
+ final String name = uriTexture.getValue();
if (name.isEmpty() == false && name != "---") {
resource2 = getManager().localKeep(name);
} else {
@@ -206,23 +41,173 @@ public class ResourceTexture extends Resource {
if (resource2 != null) {
if (resource2 instanceof ResourceTexture) {
resource2.keep();
- return (ResourceTexture)resource2;
+ return (ResourceTexture) resource2;
}
Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
return null;
}
resource = new ResourceTexture(uriTexture, textureUnit);
- ImageRawData decodedData = ImageLoader.decodePngFile(uriTexture);
- resource.setTexture(decodedData.getBuffer(),
- new Vector2i(decodedData.getWidth(), decodedData.getHeight()),
- (decodedData.isHasAlpha() == true?TextureColorMode.rgba:TextureColorMode.rgb),
- textureUnit);
- if (resource.resourceHasBeenCorectlyInit() == false) {
- Log.critical("resource Is not correctly init : ResourceProgram" );
- return null;
- }
+ final ImageRawData decodedData = ImageLoader.decodePngFile(uriTexture);
+ resource.setTexture(decodedData.getBuffer(), new Vector2i(decodedData.getWidth(), decodedData.getHeight()), (decodedData.isHasAlpha() == true ? TextureColorMode.rgba : TextureColorMode.rgb),
+ textureUnit);
resource.flush();
return resource;
}
+ /**
+ * @brief get the next power 2 if the input
+ * @param value Value that we want the next power of 2
+ * @return result value
+ */
+ private static int nextP2(final int value) {
+ int val = 1;
+ for (int iii = 1; iii < 31; iii++) {
+ if (value <= val) {
+ return val;
+ }
+ val *= 2;
+ }
+ Log.critical("impossible CASE....");
+ return val;
+ }
+
+ protected int texId = -1; //!< openGl textureID.
+ // some image are not square == > we need to sqared it to prevent some openGl api error the the displayable size is not all the time 0.0 . 1.0.
+ protected Vector2f endPointSize = new Vector2f(-1, -1);
+ // internal state of the openGl system.
+ protected boolean loaded = false;
+ // Image properties:
+ // pointer on the image data.
+ private ByteBuffer data = null;
+ // size of the image data.
+ private Vector2i size = new Vector2i(-1, -1);
+ //!< Color space of the image.
+ private TextureColorMode dataColorSpace = TextureColorMode.rgb;
+ // number of lines and colomns in the texture (multiple texturing in a single texture)
+ private int textureUnit = 0;
+ private String filename = "";
+
+ protected ResourceTexture() {
+ super();
+ }
+
+ // Public API:
+ protected ResourceTexture(final String filename, final int textureUnit) {
+ super(filename + "__" + textureUnit);
+ this.filename = filename;
+ this.textureUnit = textureUnit;
+ }
+
+ protected ResourceTexture(final Uri filename, final int textureUnit) {
+ super(filename + "__" + textureUnit);
+ this.filename = filename.get();
+ this.textureUnit = textureUnit;
+ }
+
+ public void bindForRendering(final int idTexture) {
+ if (this.loaded == false) {
+ return;
+ }
+ GL13.glActiveTexture(textureIdBinding[idTexture]);
+ GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texId);
+ if (this.dataColorSpace == TextureColorMode.rgb) {
+ OpenGL.enable(OpenGL.Flag.flag_cullFace);
+ OpenGL.enable(OpenGL.Flag.flag_back);
+ }
+ }
+
+ @Override
+ public void cleanUp() {
+ removeContext();
+ }
+
+ // Flush the data to send it at the openGl system
+ public synchronized void flush() {
+ // request to the manager to be call at the next update ...
+ Log.verbose("Request UPDATE of Element");
+ getManager().update(this);
+ }
+
+ public Vector2i getOpenGlSize() {
+ return this.size;
+ };
+
+ public int getRendererId() {
+ return this.texId;
+ }
+
+ public Vector2f getUsableSize() {
+ return this.endPointSize;
+ }
+
+ @Override
+ public synchronized void removeContext() {
+ if (this.loaded == true) {
+ // Request remove texture ...
+ Log.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
+ // TODO Check if we are in the correct thread
+ OpenGL.glDeleteTextures(this.texId);
+ this.loaded = false;
+ }
+ }
+
+ @Override
+ public synchronized void removeContextToLate() {
+ this.loaded = false;
+ this.texId = -1;
+ }
+
+ public void setTexture(final ByteBuffer data, final Vector2i size, final TextureColorMode dataColorSpace, final int textureUnit) {
+ this.data = data;
+ this.size = size;
+ this.textureUnit = textureUnit;
+ this.endPointSize.x = size.x;
+ this.endPointSize.y = size.y;
+ this.dataColorSpace = dataColorSpace;
+ flush();
+ }
+
+ public void unBindForRendering() {
+ if (this.loaded == false) {
+ return;
+ }
+ if (this.dataColorSpace == TextureColorMode.rgb) {
+ OpenGL.disable(OpenGL.Flag.flag_cullFace);
+ OpenGL.disable(OpenGL.Flag.flag_back);
+ }
+ }
+
+ // Gale internal API:
+ @Override
+ public boolean updateContext() {
+ if (this.loaded == true) {
+ return true;
+ }
+ // Request a new texture at openGl :
+ this.texId = GL11.glGenTextures();
+ GL13.glActiveTexture(this.textureUnit);
+ GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texId);
+
+ // All RGB bytes are aligned to each other and each component is 1 byte
+ GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
+ Log.info("TEXTURE: add [" + getId() + "]=" + this.size + " OGlId=" + this.texId);
+ if (this.dataColorSpace == TextureColorMode.rgb) {
+ GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x, this.size.y, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, this.data);
+ } else {
+ GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, this.size.x, this.size.y, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, this.data);
+ }
+ // generate multi-texture mapping
+ GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
+
+ // Setup the ST coordinate system
+ GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
+ GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
+
+ // Setup what to do when the texture has to be scaled
+ GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
+ GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
+ // now the data is loaded
+ this.loaded = true;
+ return true;
+ }
}
diff --git a/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java b/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java
index 87a4629..48ceaa3 100644
--- a/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java
+++ b/src/org/atriasoft/gale/resource/ResourceVirtualArrayObject.java
@@ -4,9 +4,10 @@ import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
-import org.atriasoft.gale.internal.Log;
+
import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.RenderMode;
+import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
@@ -16,135 +17,71 @@ import org.lwjgl.opengl.GL30;
//import models.RawModel;
public class ResourceVirtualArrayObject extends Resource {
- private int vaoID = -1;
- private boolean exist = false; //!< This data is availlable in the Graphic card
- private List vbo = new ArrayList();
- float[] positions = null;
- float[] colors = null;
- float[] textureCoordinates = null;
- float[] normals = null;
- int[] indices = null;
- int vertexCount = -1;
public static final int INDICE_VBO_POSITIONS = 0;
public static final int INDICE_VBO_TEXTURE_COORDINATES = 1;
public static final int INDICE_VBO_NORMALS = 2;
public static final int INDICE_VBO_COLORS = 3;
-
- public void bindForRendering() {
- if (exist == false) {
- return;
- }
- GL30.glBindVertexArray(vaoID);
- if (positions != null) {
- GL20.glEnableVertexAttribArray(INDICE_VBO_POSITIONS);
- //Log.info("unbind POSITION");
- }
- if (textureCoordinates != null) {
- GL20.glEnableVertexAttribArray(INDICE_VBO_TEXTURE_COORDINATES);
- }
- if (normals != null) {
- GL20.glEnableVertexAttribArray(INDICE_VBO_NORMALS);
- }
- if (colors != null) {
- GL20.glEnableVertexAttribArray(INDICE_VBO_COLORS);
- }
- }
-
- public void unBindForRendering() {
- if (exist == false) {
- return;
- }
- if (positions != null) {
- GL20.glDisableVertexAttribArray(INDICE_VBO_POSITIONS);
- }
- if (textureCoordinates != null) {
- GL20.glDisableVertexAttribArray(INDICE_VBO_TEXTURE_COORDINATES);
- }
- if (normals != null) {
- GL20.glDisableVertexAttribArray(INDICE_VBO_NORMALS);
- }
- if (colors != null) {
- GL20.glDisableVertexAttribArray(INDICE_VBO_COLORS);
- }
- GL30.glBindVertexArray(0);
- }
-
- public void render(RenderMode mode) {
- OpenGL.drawElements(mode, vertexCount);
+
+ public static ResourceVirtualArrayObject create(final float[] positions, final float[] colors, final float[] textureCoordinates, final float[] normals, final int[] indices) {
+ final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, textureCoordinates, normals, indices, indices.length);
+ getManager().localAdd(resource);
+ return resource;
}
+ public static ResourceVirtualArrayObject create(final float[] positions, final float[] textureCoordinates, final float[] normals, final int[] indices) {
+ final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, textureCoordinates, normals, indices, indices.length);
+ getManager().localAdd(resource);
+ return resource;
+ }
- private FloatBuffer storeDataInFloatBuffer(float[] data) {
- FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
+ public static ResourceVirtualArrayObject create(final float[] positions, final float[] colors, final int[] indices) {
+ final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, null, null, indices, indices.length);
+ getManager().localAdd(resource);
+ return resource;
+ }
+
+ public static ResourceVirtualArrayObject create(final float[] positions, final int dimentions) {
+ final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, null, null, null, positions.length / dimentions);
+ getManager().localAdd(resource);
+ return resource;
+ }
+
+ public static FloatBuffer storeDataInFloatBuffer(final float[] data) {
+ final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
- private IntBuffer storeDataInIntBuffer(int[] data) {
- IntBuffer buffer = BufferUtils.createIntBuffer(data.length);
+ public static IntBuffer storeDataInIntBuffer(final int[] data) {
+ final IntBuffer buffer = BufferUtils.createIntBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
- private void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) {
- int vboID = GL15.glGenBuffers();
- vbo.add(vboID);
- GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
- FloatBuffer buffer = storeDataInFloatBuffer(data);
- GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
- GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0);
- GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
- }
+ private int vaoID = -1;
+ private boolean exist = false; //!< This data is availlable in the Graphic card
+ private final List vbo = new ArrayList<>();
+
+ float[] positions = null;
+
+ float[] colors = null;
+
+ float[] textureCoordinates = null;
+
+ float[] normals = null;
+
+ int[] indices = null;
+
+ int vertexCount = -1;
- private void bindIndicesBuffer(int[] indices) {
- int vboId = GL15.glGenBuffers();
- vbo.add(vboId);
- GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboId);
- IntBuffer buffer = storeDataInIntBuffer(indices);
- GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
- }
-
- private void createVAO() {
- vaoID = GL30.glGenVertexArrays();
- GL30.glBindVertexArray(vaoID);
- }
- private void unbindVAO() {
- GL30.glBindVertexArray(0);
- }
-
- public void loadToVAO() {
- createVAO();
- if (indices != null) {
- Log.info("Set indices");
- bindIndicesBuffer(indices);
- }
- if (positions != null) {
- Log.info("Set positions");
- storeDataInAttributeList(0, 3, positions);
- }
- if (textureCoordinates != null) {
- Log.info("Set textureCoordinates");
- storeDataInAttributeList(1, 2, textureCoordinates);
- }
- if (normals != null) {
- Log.info("Set normals");
- storeDataInAttributeList(2, 3, normals);
- }
- if (colors != null) {
- Log.info("Set colors");
- storeDataInAttributeList(3, 4, colors);
- }
- unbindVAO();
- }
/**
* @brief ructor of this VBO.
* @param accesMode Acces mode : ???
*/
- protected ResourceVirtualArrayObject(float[] positions, float[] colors, float[] textureCoordinates, float[] normals, int[] indices, int vertexCount) {
+ protected ResourceVirtualArrayObject(final float[] positions, final float[] colors, final float[] textureCoordinates, final float[] normals, final int[] indices, final int vertexCount) {
super();
- addResourceType("gale::VirtualBufferObject");
this.resourceLevel = 3;
this.positions = positions;
this.colors = colors;
@@ -154,6 +91,35 @@ public class ResourceVirtualArrayObject extends Resource {
this.vertexCount = vertexCount;
Log.debug("OGL: load VBO count");
}
+
+ public void bindForRendering() {
+ if (this.exist == false) {
+ return;
+ }
+ GL30.glBindVertexArray(this.vaoID);
+ if (this.positions != null) {
+ GL20.glEnableVertexAttribArray(INDICE_VBO_POSITIONS);
+ //Log.info("unbind POSITION");
+ }
+ if (this.textureCoordinates != null) {
+ GL20.glEnableVertexAttribArray(INDICE_VBO_TEXTURE_COORDINATES);
+ }
+ if (this.normals != null) {
+ GL20.glEnableVertexAttribArray(INDICE_VBO_NORMALS);
+ }
+ if (this.colors != null) {
+ GL20.glEnableVertexAttribArray(INDICE_VBO_COLORS);
+ }
+ }
+
+ private void bindIndicesBuffer(final int[] indices) {
+ final int vboId = OpenGL.glGenBuffers();
+ this.vbo.add(vboId);
+ GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboId);
+ final IntBuffer buffer = storeDataInIntBuffer(indices);
+ GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
+ }
+
/**
* @brief Destructor of this VBO.
*/
@@ -161,7 +127,7 @@ public class ResourceVirtualArrayObject extends Resource {
public void cleanUp() {
removeContext();
}
-
+
/**
* @brief clear buffers
*/
@@ -170,14 +136,12 @@ public class ResourceVirtualArrayObject extends Resource {
// DO not clear the this.vbo indexed in the graphic cards ...
}
- /**
- * @brief get the real openGL ID.
- * @return the Ogl id reference of this VBO.
- */
- public int getGLID() {
- return this.vaoID;
- };
-
+
+ private void createVAO() {
+ this.vaoID = GL30.glGenVertexArrays();
+ GL30.glBindVertexArray(this.vaoID);
+ }
+
/**
* @brief Send the data to the graphic card.
*/
@@ -186,9 +150,115 @@ public class ResourceVirtualArrayObject extends Resource {
getManager().update(this);
Log.verbose("Request flush of VBO: [" + getId() + "] '" + getName() + "'");
}
+
+ /**
+ * @brief get the real openGL ID.
+ * @return the Ogl id reference of this VBO.
+ */
+ public int getGLID() {
+ return this.vaoID;
+ };
+
+ public void loadToVAO() {
+ createVAO();
+ if (this.indices != null) {
+ Log.info("Set indices");
+ bindIndicesBuffer(this.indices);
+ }
+ if (this.positions != null) {
+ Log.info("Set positions");
+ storeDataInAttributeList(0, 3, this.positions);
+ }
+ if (this.textureCoordinates != null) {
+ Log.info("Set textureCoordinates");
+ storeDataInAttributeList(1, 2, this.textureCoordinates);
+ }
+ if (this.normals != null) {
+ Log.info("Set normals");
+ storeDataInAttributeList(2, 3, this.normals);
+ }
+ if (this.colors != null) {
+ Log.info("Set colors");
+ storeDataInAttributeList(3, 4, this.colors);
+ }
+ unbindVAO();
+ }
+
+ /**
+ * @brief Relode the shader from the file. used when a request of resouces reload is done.
+ * @note this is really usefull when we tested the new themes or shader developpements.
+ */
+ @Override
+ public void reload() {
+ removeContext();
+ updateContext();
+ }
+
+ /**
+ * @brief remove the data from the opengl context.
+ */
+ @Override
+ public void removeContext() {
+
+ if (this.exist == true) {
+ // OpenGL.deleteBuffers(this.vbo);
+ this.exist = false;
+ }
+ }
+
+ /**
+ * @brief Special android spec! It inform us that all context is removed and after notify us...
+ */
+ @Override
+ public void removeContextToLate() {
+
+ this.exist = false;
+ // for (int iii=0; iii try later ...
+ Log.warning(" ==> Lock error on VBO");
+ return false;
+ }
+ */
+ if (this.exist == false) {
+ Log.debug(" ==> ALLOCATE new handle");
+ // Allocate and assign a Vertex Array Object to our handle
+ OpenGL.genBuffers(this.vbo);
+ }
+ this.exist = true;
+ for (int iii = 0; iii < this.vbo.length; iii++) {
+ Log.verbose("VBO : add [" + getId() + "]=" + this.buffer[iii].getClass().getCanonicalName() + "*sizeof(float) OGl_Id=" + this.vbo[iii]);
+ if (this.buffer[iii] != null) {
+ OpenGL.bindBuffer(this.vbo[iii]);
+ // select the buffer to set data inside it ...
+ if (this.buffer[iii] instanceof float[]) {
+ OpenGL.bufferData((float[]) (this.buffer[iii]), Usage.streamDraw);
+ } else if (this.buffer[iii] instanceof int[]) {
+ OpenGL.bufferData((int[]) (this.buffer[iii]), Usage.streamDraw);
+ } else if (this.buffer[iii] instanceof Vector2f[]) {
+ OpenGL.bufferData((Vector2f[]) (this.buffer[iii]), Usage.streamDraw);
+ } else if (this.buffer[iii] instanceof Vector3f[]) {
+ OpenGL.bufferData((Vector3f[]) (this.buffer[iii]), Usage.streamDraw);
+ } else if (this.buffer[iii] instanceof Color[]) {
+ OpenGL.bufferData((Color[]) (this.buffer[iii]), Usage.streamDraw);
+ } else {
+ Log.error("Not managed VBO model : " + this.buffer[iii].getClass().getCanonicalName());
+ }
+ }
+ }
+ // un-bind it to permet to have no error in the next display ...
+ OpenGL.unbindBuffer();
+ Log.verbose(" Stop: [" + getId() + "] '" + getName() + "'");
+ return true;
+ }
+}