[FEAT] use Maven a build system root tool

This commit is contained in:
Edouard DUPIN 2024-06-07 09:28:33 +02:00
parent adb11eaeb3
commit 423f488740
29 changed files with 1479 additions and 1276 deletions

View File

@ -1,101 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry excluding="**/__*" kind="src" path="src"> <classpathentry including="**/*.java" kind="src" output="out/maven/classes" path="src">
<attributes> <attributes>
<attribute name="optional" value="true"/> <attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="src" path="resources"/> <classpathentry kind="src" output="out/maven/test-classes" path="test/src">
<classpathentry including="**/*.java" kind="src" output="out/eclipse/classes-test" path="test/src">
<attributes> <attributes>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/> <attribute name="optional" value="true"/>
</attributes> <attribute name="maven.pomderived" value="true"/>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-14">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl3-awt-0.1.7.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/pngdecoder.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-assimp.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-assimp-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-glfw.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-glfw-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-jawt.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-opengl.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-stb.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-stb-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="lib" path="lib/lwjgl/lwjgl-opengl-natives-linux.jar">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5">
<attributes>
<attribute name="test" value="true"/> <attribute name="test" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/atriasoft-io-gami"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-21">
<attributes> <attributes>
<attribute name="module" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/atriasoft-etk"> <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes> <attributes>
<attribute name="module" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="output" path="out/eclipse/classes"/> <classpathentry kind="output" path="out/maven/classes"/>
</classpath> </classpath>

View File

@ -1,9 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<projectDescription> <projectDescription>
<name>atriasoft-gale</name> <name>gale</name>
<comment></comment> <comment></comment>
<projects> <projects>
<project>atriasoft-gale</project>
</projects> </projects>
<buildSpec> <buildSpec>
<buildCommand> <buildCommand>
@ -12,24 +11,13 @@
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>net.sf.eclipsecs.core.CheckstyleBuilder</name> <name>org.eclipse.m2e.core.maven2Builder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature> <nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures> </natures>
<filteredResources>
<filter>
<id>1646149232195</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription> </projectDescription>

View File

@ -33,14 +33,14 @@ def configure(target, my_module):
my_module.add_src_file([ my_module.add_src_file([
'src/module-info.java', 'src/module-info.java',
'src/org/atriasoft/gale/TextureFilter.java', 'src/org/atriasoft/gale/TextureFilter.java',
'src/org/atriasoft/gale/internal/Log.java', 'src/org/atriasoft/gale/internal/LOGGER.java',
'src/org/atriasoft/gale/DisplayManagerDraw.java', 'src/org/atriasoft/gale/DisplayManagerDraw.java',
'src/org/atriasoft/gale/test/sample1/Sample1.java', 'src/org/atriasoft/gale/test/sample1/Sample1.java',
'src/org/atriasoft/gale/test/sample1/Sample1Application.java', 'src/org/atriasoft/gale/test/sample1/Sample1Application.java',
'src/org/atriasoft/gale/test/sample1/Log.java', 'src/org/atriasoft/gale/test/sample1/LOGGER.java',
'src/org/atriasoft/gale/test/sample2/Sample2Application.java', 'src/org/atriasoft/gale/test/sample2/Sample2Application.java',
'src/org/atriasoft/gale/test/sample2/Main.java', 'src/org/atriasoft/gale/test/sample2/Main.java',
'src/org/atriasoft/gale/test/sample2/Log.java', 'src/org/atriasoft/gale/test/sample2/LOGGER.java',
'src/org/atriasoft/gale/context/ClipboardList.java', 'src/org/atriasoft/gale/context/ClipboardList.java',
'src/org/atriasoft/gale/context/Cursor.java', 'src/org/atriasoft/gale/context/Cursor.java',
'src/org/atriasoft/gale/context/LWJG_AWT/ContextLWJGLAWT.java', 'src/org/atriasoft/gale/context/LWJG_AWT/ContextLWJGLAWT.java',

200
pom.xml Normal file
View File

@ -0,0 +1,200 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.atriasoft</groupId>
<artifactId>gale</artifactId>
<version>0.1.0</version>
<properties>
<maven.compiler.version>3.13.0</maven.compiler.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<maven.dependency.version>3.1.1</maven.dependency.version>
<lwjgl.version>3.3.3</lwjgl.version>
<lwjgl3-awt.version>0.1.8</lwjgl3-awt.version>
<lwjgl.natives>natives-linux-arm64</lwjgl.natives>
</properties>
<repositories>
<repository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</repository>
<snapshotRepository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</snapshotRepository>
</distributionManagement>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bom</artifactId>
<version>${lwjgl.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.atriasoft</groupId>
<artifactId>io-gami</artifactId>
<version>0.1.0</version>
</dependency>
<dependency>
<groupId>org.atriasoft</groupId>
<artifactId>png-decoder</artifactId>
<version>0.1.0</version>
</dependency>
<!-- generate with https://www.lwjgl.org/customize -->
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-assimp</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-jawt</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-assimp</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjglx</groupId>
<artifactId>lwjgl3-awt</artifactId>
<version>${lwjgl3-awt.version}</version>
</dependency>
<!-- Test tools section-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test/src</testSourceDirectory>
<directory>${project.basedir}/out/maven/</directory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<!--<encoding>${project.build.sourceEncoding}</encoding>-->
</configuration>
</plugin>
<!-- Create the source bundle -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- junit results -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<!-- Java-doc generation for stand-alone site -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<show>private</show>
<nohelp>true</nohelp>
</configuration>
</plugin>
</plugins>
</build>
<!-- Generate Java-docs As Part Of Project Reports -->
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<show>public</show>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

View File

@ -12,10 +12,10 @@ open module org.atriasoft.gale {
exports org.atriasoft.gale.context.LWJG_AWT; exports org.atriasoft.gale.context.LWJG_AWT;
exports org.atriasoft.gale.key; exports org.atriasoft.gale.key;
exports org.atriasoft.gale.resource; exports org.atriasoft.gale.resource;
requires transitive org.atriasoft.etk; requires transitive org.atriasoft.etk;
requires transitive org.atriasoft.egami; requires transitive org.atriasoft.egami;
requires transitive org.lwjgl; requires transitive org.lwjgl;
requires transitive org.lwjgl.natives; requires transitive org.lwjgl.natives;
requires transitive org.lwjgl.glfw; requires transitive org.lwjgl.glfw;
@ -27,10 +27,10 @@ open module org.atriasoft.gale {
requires transitive org.lwjgl.jawt; requires transitive org.lwjgl.jawt;
requires transitive org.lwjgl.opengl; requires transitive org.lwjgl.opengl;
requires transitive org.lwjgl.opengl.natives; requires transitive org.lwjgl.opengl.natives;
requires transitive java.desktop; requires transitive java.desktop;
requires transitive org.atriasoft.pngdecoder; requires transitive org.atriasoft.pngdecoder;
requires transitive lwjgl3.awt; requires transitive lwjgl3.awt;
requires org.atriasoft.reggol;
requires org.atriasoft.iogami; requires org.atriasoft.iogami;
requires org.slf4j;
} }

View File

@ -4,15 +4,17 @@ import org.atriasoft.etk.Uri;
import org.atriasoft.gale.context.GaleContext; import org.atriasoft.gale.context.GaleContext;
//import org.atriasoft.gale.context.JOGL.ContextJOGL; //import org.atriasoft.gale.context.JOGL.ContextJOGL;
import org.atriasoft.gale.context.LWJG_AWT.ContextLWJGLAWT; import org.atriasoft.gale.context.LWJG_AWT.ContextLWJGLAWT;
//import org.atriasoft.gale.context.LWJGL.ContextLWJGL; import org.slf4j.Logger;
import org.atriasoft.gale.internal.Log; import org.slf4j.LoggerFactory;
public class Gale { public class Gale {
static final Logger LOGGER = LoggerFactory.getLogger(Gale.class);
public static GaleContext getContext() { public static GaleContext getContext() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return GaleContext.getContext(); return GaleContext.getContext();
} }
/** /**
* get GALE version * get GALE version
* @return The string that describe gale version * @return The string that describe gale version
@ -20,16 +22,16 @@ public class Gale {
public static String getVersion() { public static String getVersion() {
return "J-0.5"; return "J-0.5";
} }
public static void init() { public static void init() {
Uri.addLibrary("gale", Gale.class, "/resources/gale/"); Uri.addLibrary("gale", Gale.class, "/resources/gale/");
} }
/** /**
* This is the only one things the User might done in his main(); * This is the only one things the User might done in his main();
* @note To answare you before you ask the question, this is really simple: * @note To answare you before you ask the question, this is really simple:
* Due to the fect that the current system is multiple-platform, you "main" * Due to the fect that the current system is multiple-platform, you "main"
* Does not exist in the android platform, then gale call other start * Does not exist in the android platform, then gale call other start
* and stop function, to permit to have only one code * and stop function, to permit to have only one code
* @note The main can not be in the gale, due to the fact thet is an librairy * @note The main can not be in the gale, due to the fact thet is an librairy
* @param _application just created instance of the applicationo * @param _application just created instance of the applicationo
@ -41,17 +43,17 @@ public class Gale {
init(); init();
//etk::init(_argc, _argv); //etk::init(_argc, _argv);
GaleContext context = null; GaleContext context = null;
String request = ""; final String request = "";
//context = ContextLWJGL.create(application, arg); //context = ContextLWJGL.create(application, arg);
//context = ContextJOGL.create(application, arg); //context = ContextJOGL.create(application, arg);
context = ContextLWJGLAWT.create(application, arg); context = ContextLWJGLAWT.create(application, arg);
if (context == null) { if (context == null) {
Log.error("Can not allocate the interface of the GUI ..."); LOGGER.error("Can not allocate the interface of the GUI ...");
return -1; return -1;
} }
return context.run(); return context.run();
} }
private Gale() {} private Gale() {}
} }

View File

@ -7,37 +7,39 @@ import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.gale.context.ClipboardList; import org.atriasoft.gale.context.ClipboardList;
import org.atriasoft.gale.context.Cursor; import org.atriasoft.gale.context.Cursor;
import org.atriasoft.gale.context.GaleContext; import org.atriasoft.gale.context.GaleContext;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.key.KeyKeyboard; import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial; import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus; import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType; import org.atriasoft.gale.key.KeyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GaleApplication { public class GaleApplication {
static final Logger LOGGER = LoggerFactory.getLogger(GaleApplication.class);
private boolean needRedraw = true; private boolean needRedraw = true;
private String title = "gale"; private String title = "gale";
private Uri iconName = null; private Uri iconName = null;
private final Cursor cursor = Cursor.arrow; private final Cursor cursor = Cursor.arrow;
private Orientation orientation = Orientation.screenAuto; private Orientation orientation = Orientation.screenAuto;
private Vector2f windowsSize = new Vector2f(800, 600); private Vector2f windowsSize = new Vector2f(800, 600);
public GaleApplication() { public GaleApplication() {
Log.verbose("Constructor Gale Application"); LOGGER.trace("Constructor Gale Application");
} }
/** /**
* Exit the application (not availlable on IOs, ==> the user will not understand the comportement. He will think the application has crashed (Apple philosophie)) * Exit the application (not availlable on IOs, ==> the user will not understand the comportement. He will think the application has crashed (Apple philosophie))
* @param value value to return on the program * @param value value to return on the program
*/ */
public void exit(final int value) { public void exit(final int value) {
Log.verbose("Exit Requested " + value); LOGGER.trace("Exit Requested " + value);
Gale.getContext().stop(); Gale.getContext().stop();
} }
public float getAspectRatio() { public float getAspectRatio() {
return this.windowsSize.x() / this.windowsSize.y(); return this.windowsSize.x() / this.windowsSize.y();
} }
/** /**
* Get the cursor type. * Get the cursor type.
* @return the current cursor. * @return the current cursor.
@ -45,7 +47,7 @@ public class GaleApplication {
public Cursor getCursor() { public Cursor getCursor() {
return this.cursor; return this.cursor;
} }
/** /**
* Get the current filename of the application. * Get the current filename of the application.
* @return Filename of the icon. * @return Filename of the icon.
@ -53,7 +55,7 @@ public class GaleApplication {
public Uri getIcon() { public Uri getIcon() {
return this.iconName; return this.iconName;
} }
/** /**
* get the screen orientation (if possible : only on iOs/Android) * get the screen orientation (if possible : only on iOs/Android)
* @return Current orientation. * @return Current orientation.
@ -61,7 +63,7 @@ public class GaleApplication {
public Orientation getOrientation() { public Orientation getOrientation() {
return this.orientation; return this.orientation;
} }
/** /**
* Get the position of the window. * Get the position of the window.
* @return Current position of the window. * @return Current position of the window.
@ -69,7 +71,7 @@ public class GaleApplication {
public Vector2f getPosition() { public Vector2f getPosition() {
return new Vector2f(0, 0); return new Vector2f(0, 0);
} }
/** /**
* Get the size of the window. * Get the size of the window.
* @return Current size of the window. * @return Current size of the window.
@ -77,7 +79,7 @@ public class GaleApplication {
public Vector2f getSize() { public Vector2f getSize() {
return this.windowsSize; return this.windowsSize;
} }
/** /**
* Get the current title of the application * Get the current title of the application
* @return Current title * @return Current title
@ -85,13 +87,13 @@ public class GaleApplication {
public String getTitle() { public String getTitle() {
return this.title; return this.title;
} }
public boolean isDrawingNeeded() { public boolean isDrawingNeeded() {
final boolean tmp = this.needRedraw; final boolean tmp = this.needRedraw;
this.needRedraw = false; this.needRedraw = false;
return tmp; return tmp;
} }
/** /**
* Hide the virtal keyboard (if possible : only on iOs/Android) * Hide the virtal keyboard (if possible : only on iOs/Android)
*/ */
@ -102,7 +104,7 @@ public class GaleApplication {
} }
context.keyboardHide(); context.keyboardHide();
} }
/** /**
* Show the virtal keyboard (if possible : only on iOs/Android) * Show the virtal keyboard (if possible : only on iOs/Android)
*/ */
@ -113,43 +115,43 @@ public class GaleApplication {
} }
context.keyboardShow(); context.keyboardShow();
} }
public void markDrawingIsNeeded() { public void markDrawingIsNeeded() {
this.needRedraw = true; this.needRedraw = true;
} }
/** /**
* A clipboard data is back (apear after a request of a new clipboard). * A clipboard data is back (apear after a request of a new clipboard).
* @param clipboardId Id of the clipboard. * @param clipboardId Id of the clipboard.
*/ */
public void onClipboardEvent(final ClipboardList clipboardId) { public void onClipboardEvent(final ClipboardList clipboardId) {
} }
/** /**
* The application is created. * The application is created.
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onCreate(final GaleContext context) { public void onCreate(final GaleContext context) {
Log.verbose("Create Gale Application"); LOGGER.trace("Create Gale Application");
} }
/** /**
* The application is removed (call destructor just adter it.). * The application is removed (call destructor just adter it.).
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onDestroy(final GaleContext context) { public void onDestroy(final GaleContext context) {
Log.verbose("Destroy Gale Application"); LOGGER.trace("Destroy Gale Application");
} }
/** /**
* Real draw of the application * Real draw of the application
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onDraw(final GaleContext context) { public void onDraw(final GaleContext context) {
Log.verbose("draw Gale Application"); LOGGER.trace("draw Gale Application");
} }
/** /**
* Get keyborad value input. * Get keyborad value input.
* @param special Current special key status (ctrl/alt/shift ...). * @param special Current special key status (ctrl/alt/shift ...).
@ -157,42 +159,46 @@ public class GaleApplication {
* @param value Unicode value of the char pushed (viable only if type==gale::key::keyboard::character). * @param value Unicode value of the char pushed (viable only if type==gale::key::keyboard::character).
* @param state State of the key (up/down/upRepeate/downRepeate) * @param state State of the key (up/down/upRepeate/downRepeate)
*/ */
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) { public void onKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final Character value,
final KeyStatus state) {
} }
/** /**
* The user request application removing. * The user request application removing.
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onKillDemand(final GaleContext context) { public void onKillDemand(final GaleContext context) {
Log.info("Gale request auto destroy ==> no applification specification"); LOGGER.info("Gale request auto destroy ==> no applification specification");
System.exit(0); System.exit(0);
} }
/** /**
* Event generated when user change the position of the window. * Event generated when user change the position of the window.
* @param size New position of the window. * @param size New position of the window.
*/ */
public void onMovePosition(final Vector2f size) { public void onMovePosition(final Vector2f size) {
} }
/** /**
* The application is Hide / not visible. * The application is Hide / not visible.
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onPause(final GaleContext context) { public void onPause(final GaleContext context) {
Log.verbose("Pause Gale Application"); LOGGER.trace("Pause Gale Application");
} }
/** /**
* Call when contrext finish process event in the buffer and add a latency of 10ms between calls * Call when contrext finish process event in the buffer and add a latency of 10ms between calls
* @param clock Current time of the call; * @param clock Current time of the call;
* @param time time of the program in nanoseconds (monotonic) ==> need restart application approximately every 292 years * @param time time of the program in nanoseconds (monotonic) ==> need restart application approximately every 292 years
*/ */
public void onPeriod(final Clock clock, final long time) {} public void onPeriod(final Clock clock, final long time) {}
/** /**
* Get touch/mouse/... event. * Get touch/mouse/... event.
* @param type Type of pointer event * @param type Type of pointer event
@ -200,56 +206,61 @@ public class GaleApplication {
* @param pos Position of the event (can be <0 if out of window). * @param pos Position of the event (can be <0 if out of window).
* @param state Key state (up/down/move) * @param state Key state (up/down/move)
*/ */
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) { public void onPointer(
final KeySpecial special,
final KeyType type,
final int pointerID,
final Vector2f pos,
final KeyStatus state) {
} }
/** /**
* call application to precalculate drawing. * call application to precalculate drawing.
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onRegenerateDisplay(final GaleContext context) { public void onRegenerateDisplay(final GaleContext context) {
//Log.verbose("Regenerate Gale Application"); //LOGGER.trace("Regenerate Gale Application");
markDrawingIsNeeded(); markDrawingIsNeeded();
} }
/** /**
* Event generated when user change the size of the window. * Event generated when user change the size of the window.
* @param size New size of the window. * @param size New size of the window.
*/ */
public void onResize(final Vector2f size) { public void onResize(final Vector2f size) {
if (size == null) { if (size == null) {
Log.error("Try to set a null size ..."); LOGGER.error("Try to set a null size ...");
return; return;
} }
this.windowsSize = size; this.windowsSize = size;
markDrawingIsNeeded(); markDrawingIsNeeded();
} }
/** /**
* The application is resumed (now visible). * The application is resumed (now visible).
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onResume(final GaleContext context) { public void onResume(final GaleContext context) {
Log.verbose("Start Gale Application"); LOGGER.trace("Start Gale Application");
} }
/** /**
* The application is started. * The application is started.
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onStart(final GaleContext context) { public void onStart(final GaleContext context) {
Log.verbose("Start Gale Application"); LOGGER.trace("Start Gale Application");
} }
/** /**
* The application is stopped. * The application is stopped.
* @param context Current gale context. * @param context Current gale context.
*/ */
public void onStop(final GaleContext context) { public void onStop(final GaleContext context) {
Log.verbose("Stop Gale Application"); LOGGER.trace("Stop Gale Application");
} }
/** /**
* Set the cursor type. * Set the cursor type.
* @param newCursor Selected cursor. * @param newCursor Selected cursor.
@ -257,11 +268,11 @@ public class GaleApplication {
public void setCursor(final Cursor newCursor) { public void setCursor(final Cursor newCursor) {
Gale.getContext().setCursor(this.cursor); Gale.getContext().setCursor(this.cursor);
} }
void setForceRedraw() { void setForceRedraw() {
this.needRedraw = true; this.needRedraw = true;
} }
/** /**
* set the Icon of the application. * set the Icon of the application.
* @param iconFile File name icon (.bmp/.png). * @param iconFile File name icon (.bmp/.png).
@ -270,7 +281,7 @@ public class GaleApplication {
this.iconName = iconFile; this.iconName = iconFile;
Gale.getContext().setIcon(this.iconName); Gale.getContext().setIcon(this.iconName);
} }
/** /**
* set the screen orientation (if possible : only on iOs/Android) * set the screen orientation (if possible : only on iOs/Android)
* @param orientation New orientation. * @param orientation New orientation.
@ -279,15 +290,15 @@ public class GaleApplication {
this.orientation = orientation; this.orientation = orientation;
Gale.getContext().forceOrientation(this.orientation); Gale.getContext().forceOrientation(this.orientation);
} }
/** /**
* Set the position of the window (if possible: Android and Ios does not support it) * Set the position of the window (if possible: Android and Ios does not support it)
* @param size New position of the window. * @param size New position of the window.
*/ */
public void setPosition(final Vector2f size) { public void setPosition(final Vector2f size) {
} }
/** /**
* Set the size of the window (if possible: Android and Ios does not support it) * Set the size of the window (if possible: Android and Ios does not support it)
* @param size New size of the window. * @param size New size of the window.
@ -295,7 +306,7 @@ public class GaleApplication {
*/ */
public void setSize(final Vector2f size) { public void setSize(final Vector2f size) {
if (size.x() <= 0 || size.y() <= 0) { if (size.x() <= 0 || size.y() <= 0) {
Log.error("Wrong windows size: " + size); LOGGER.error("Wrong windows size: " + size);
} }
final Vector2f oldSize = this.windowsSize; final Vector2f oldSize = this.windowsSize;
this.windowsSize = size; this.windowsSize = size;
@ -306,12 +317,12 @@ public class GaleApplication {
context.setSize(size); context.setSize(size);
/* ==> change API ==> need the GUI notify the Windows that the size has change ???? /* ==> change API ==> need the GUI notify the Windows that the size has change ????
if (!) { if (!) {
Log.error("Can not set the size required by the user."); LOGGER.error("Can not set the size required by the user.");
this.windowsSize = oldSize; this.windowsSize = oldSize;
} }
*/ */
} }
/** /**
* Set the title of the application * Set the title of the application
* @param title New title to set at the application (if possible: Android and Ios does not support it) * @param title New title to set at the application (if possible: Android and Ios does not support it)

View File

@ -25,15 +25,18 @@ import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.etk.math.Vector3f; import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.etk.math.Vector3i; import org.atriasoft.etk.math.Vector3i;
import org.atriasoft.etk.math.Vector4f; import org.atriasoft.etk.math.Vector4f;
import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OpenGL { public class OpenGL {
static final Logger LOGGER = LoggerFactory.getLogger(OpenGL.class);
public enum ClearFlag { public enum ClearFlag {
clearFlag_colorBuffer, // !< Indicates the buffers currently enabled for color writing. clearFlag_colorBuffer, // !< Indicates the buffers currently enabled for color writing.
clearFlag_depthBuffer, // !< Indicates the depth buffer. clearFlag_depthBuffer, // !< Indicates the depth buffer.
@ -147,10 +150,13 @@ public class OpenGL {
streamDraw, staticDraw, dynamicDraw streamDraw, staticDraw, dynamicDraw
} }
private static final int[] TEXTURE_ID_BINDING = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2, GL13.GL_TEXTURE3, GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7, private static final int[] TEXTURE_ID_BINDING = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2,
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_TEXTURE3, GL13.GL_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7, GL13.GL_TEXTURE8,
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_TEXTURE9, GL13.GL_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13,
GL13.GL_TEXTURE27, GL13.GL_TEXTURE28, GL13.GL_TEXTURE29, GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 }; 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 final int GL_RGB = GL11.GL_RGB; public static final int GL_RGB = GL11.GL_RGB;
@ -170,9 +176,11 @@ public class OpenGL {
private static Matrix4f matrixCamera = Matrix4f.IDENTITY; private static Matrix4f matrixCamera = Matrix4f.IDENTITY;
private static int programId = 0; private static int programId = 0;
private static final Map<RenderMode, Integer> CONVERT_RENDER_MODE = Map.of(RenderMode.POINT, GL11.GL_POINTS, RenderMode.LINE, GL11.GL_LINES, RenderMode.LINE_STRIP, GL11.GL_LINE_STRIP, private static final Map<RenderMode, Integer> CONVERT_RENDER_MODE = Map.of(RenderMode.POINT, GL11.GL_POINTS,
RenderMode.LINE_LOOP, GL11.GL_LINE_LOOP, RenderMode.TRIANGLE, GL11.GL_TRIANGLES, RenderMode.TRIANGLE_STRIP, GL11.GL_TRIANGLE_STRIP, RenderMode.TRIANGLE_FAN, GL11.GL_TRIANGLE_FAN, RenderMode.LINE, GL11.GL_LINES, RenderMode.LINE_STRIP, GL11.GL_LINE_STRIP, RenderMode.LINE_LOOP,
RenderMode.QUAD, GL11.GL_QUADS, RenderMode.QUAD_STRIP, GL11.GL_QUAD_STRIP, RenderMode.POLYGON, GL11.GL_POLYGON); GL11.GL_LINE_LOOP, RenderMode.TRIANGLE, GL11.GL_TRIANGLES, RenderMode.TRIANGLE_STRIP,
GL11.GL_TRIANGLE_STRIP, RenderMode.TRIANGLE_FAN, GL11.GL_TRIANGLE_FAN, RenderMode.QUAD, GL11.GL_QUADS,
RenderMode.QUAD_STRIP, GL11.GL_QUAD_STRIP, RenderMode.POLYGON, GL11.GL_POLYGON);
private static final Map<Flag, Integer> BASIC_FLAG; private static final Map<Flag, Integer> BASIC_FLAG;
private static boolean flagsStatesChange = false; private static boolean flagsStatesChange = false;
@ -248,7 +256,8 @@ public class OpenGL {
OpenGL.convertUsage.put(Usage.dynamicDraw, GL15.GL_DYNAMIC_DRAW); OpenGL.convertUsage.put(Usage.dynamicDraw, GL15.GL_DYNAMIC_DRAW);
} }
private static final Map<Long, Boolean> THREAD_HAS_CONTEXT = new HashMap<>(); private static final Map<Long, Boolean> THREAD_HAS_CONTEXT = new HashMap<>();
private static final Map<ClearFlag, Integer> BASIC_FLAG_CLEAR = Map.of(ClearFlag.clearFlag_colorBuffer, GL11.GL_COLOR_BUFFER_BIT, ClearFlag.clearFlag_depthBuffer, GL11.GL_DEPTH_BUFFER_BIT, private static final Map<ClearFlag, Integer> 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); ClearFlag.clearFlag_stencilBuffer, GL11.GL_STENCIL_BUFFER_BIT);
/** /**
@ -260,7 +269,7 @@ public class OpenGL {
GL13.glActiveTexture(OpenGL.TEXTURE_ID_BINDING[textureID]); GL13.glActiveTexture(OpenGL.TEXTURE_ID_BINDING[textureID]);
OpenGL.checkGlError("glActiveTexture"); OpenGL.checkGlError("glActiveTexture");
} else if (OpenGL.DEBUG) { } else if (OpenGL.DEBUG) {
Log.error("try to bind texture with no program set"); LOGGER.error("try to bind texture with no program set");
} }
} }
@ -312,14 +321,14 @@ public class OpenGL {
// if (CHECKERROROPENGL) { // if (CHECKERROROPENGL) {
// boolean hasError = false; // boolean hasError = false;
// for (int error = GL11.glGetError(); error != null; error = GL11.glGetError()) { // for (int error = GL11.glGetError(); error != null; error = GL11.glGetError()) {
// Log.error("after " + op + "():" + localLine + " glError(" + error + ")"); // LOGGER.error("after " + op + "():" + localLine + " glError(" + error + ")");
// hasError = true; // hasError = true;
// } // }
// if (hasError) { // if (hasError) {
// Log.critical("plop"); // LOGGER.critical("plop");
// } // }
// for (GLint error = glGetError(); error; error = glGetError()) { // for (GLint error = glGetError(); error; error = glGetError()) {
// Log.error("after " + op + "() glError (" + error + ")"); // LOGGER.error("after " + op + "() glError (" + error + ")");
// } // }
// } // }
} }
@ -380,7 +389,7 @@ public class OpenGL {
public static boolean deleteBuffers(final int[] buffers) { public static boolean deleteBuffers(final int[] buffers) {
if (buffers.length == 0) { if (buffers.length == 0) {
Log.warning("try to delete vector buffer with size 0"); LOGGER.warn("try to delete vector buffer with size 0");
return true; return true;
} }
// TODO Check if we are in the correct thread // TODO Check if we are in the correct thread
@ -406,15 +415,15 @@ public class OpenGL {
* @param flagID The flag requested * @param flagID The flag requested
*/ */
public static void disable(final Flag flagID) { public static void disable(final Flag flagID) {
// Log.info("Disable : " + flagID); // LOGGER.info("Disable : " + flagID);
if (OpenGL.DIRECT_MODE) { if (OpenGL.DIRECT_MODE) {
GL11.glDisable(OpenGL.BASIC_FLAG.get(flagID)); GL11.glDisable(OpenGL.BASIC_FLAG.get(flagID));
OpenGL.checkGlError("glDisable"); OpenGL.checkGlError("glDisable");
} else { } else {
// Log.debug("Disable FLAGS = " + this.flagsStates); // LOGGER.debug("Disable FLAGS = " + this.flagsStates);
OpenGL.FLAGS_STATES.get(flagID).mustBeSet = false; OpenGL.FLAGS_STATES.get(flagID).mustBeSet = false;
OpenGL.flagsStatesChange = true; OpenGL.flagsStatesChange = true;
// Log.debug(" == >" + this.flagsStates); // LOGGER.debug(" == >" + this.flagsStates);
} }
} }
@ -442,35 +451,35 @@ public class OpenGL {
* @param flagID The flag requested * @param flagID The flag requested
*/ */
public static void enable(final Flag flagID) { public static void enable(final Flag flagID) {
// Log.info("Enable : " + flagID); // LOGGER.info("Enable : " + flagID);
if (OpenGL.DIRECT_MODE) { if (OpenGL.DIRECT_MODE) {
GL11.glEnable(OpenGL.BASIC_FLAG.get(flagID)); GL11.glEnable(OpenGL.BASIC_FLAG.get(flagID));
OpenGL.checkGlError("glEnable"); OpenGL.checkGlError("glEnable");
} else { } else {
// Log.debug("Enable FLAGS = " + this.flagsStates); // LOGGER.debug("Enable FLAGS = " + this.flagsStates);
OpenGL.FLAGS_STATES.get(flagID).mustBeSet = true; OpenGL.FLAGS_STATES.get(flagID).mustBeSet = true;
OpenGL.flagsStatesChange = true; OpenGL.flagsStatesChange = true;
// Log.debug(" == >" + this.flagsStates); // LOGGER.debug(" == >" + this.flagsStates);
} }
} }
/** /**
* *
*/ */
public static void finish() { public static void finish() {
OpenGL.programId = -1; OpenGL.programId = -1;
} }
/** /**
* *
*/ */
public static void flush() { public static void flush() {
OpenGL.programId = -1; OpenGL.programId = -1;
GL11.glFlush(); GL11.glFlush();
// checkGlError("glFlush"); // checkGlError("glFlush");
// Log.info("========================" ); // LOGGER.info("========================" );
// Log.info("== FLUSH OPEN GL ==" ); // LOGGER.info("== FLUSH OPEN GL ==" );
// Log.info("========================"); // LOGGER.info("========================");
} }
public static int genBuffers() { public static int genBuffers() {
@ -479,16 +488,16 @@ public class OpenGL {
public static boolean genBuffers(final int[] buffers) { public static boolean genBuffers(final int[] buffers) {
if (buffers.length == 0) { if (buffers.length == 0) {
Log.warning("try to generate vector buffer with size 0"); LOGGER.warn("try to generate vector buffer with size 0");
return true; return true;
} }
Log.info("Create N=" + buffers.length + " Buffer"); LOGGER.info("Create N=" + buffers.length + " Buffer");
GL15.glGenBuffers(buffers); GL15.glGenBuffers(buffers);
OpenGL.checkGlError("glGenBuffers"); OpenGL.checkGlError("glGenBuffers");
boolean hasError = false; boolean hasError = false;
for (int iii = 0; iii < buffers.length; iii++) { for (int iii = 0; iii < buffers.length; iii++) {
if (buffers[iii] == 0) { if (buffers[iii] == 0) {
Log.error("[" + iii + "] error to create a buffer id=" + buffers[iii]); LOGGER.error("[" + iii + "] error to create a buffer id=" + buffers[iii]);
hasError = true; hasError = true;
} }
} }
@ -510,7 +519,7 @@ public class OpenGL {
*/ */
public static Matrix4f getMatrix() { public static Matrix4f getMatrix() {
if (OpenGL.MATRIX_LIST.size() == 0) { if (OpenGL.MATRIX_LIST.size() == 0) {
Log.error("set matrix list is not corect size in the stack: 0"); LOGGER.error("set matrix list is not corect size in the stack: 0");
OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY); OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY);
} }
return OpenGL.MATRIX_LIST.get(OpenGL.MATRIX_LIST.size() - 1); return OpenGL.MATRIX_LIST.get(OpenGL.MATRIX_LIST.size() - 1);
@ -524,29 +533,63 @@ public class OpenGL {
return GL11.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) { 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.allocateDirect(data.length); final ByteBuffer dataBuffer = ByteBuffer.allocateDirect(data.length);
for (int iii = 0; iii < data.length; iii++) { for (final byte element : data) {
dataBuffer.put(data[iii]); dataBuffer.put(element);
} }
dataBuffer.flip(); dataBuffer.flip();
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, level, internalFormat, width, height, border, format, sizeObject, dataBuffer); 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) { 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); 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) { 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.allocateDirect(data.length); final ByteBuffer dataBuffer = ByteBuffer.allocateDirect(data.length);
for (int iii = 0; iii < data.length; iii++) { for (final byte element : data) {
dataBuffer.put(data[iii]); dataBuffer.put(element);
} }
dataBuffer.flip(); dataBuffer.flip();
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, xOffset, yOffset, width, height, format, sizeObject, dataBuffer); 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) { 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); GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, level, xOffset, yOffset, width, height, format, sizeObject, data);
} }
@ -582,9 +625,9 @@ public class OpenGL {
* remove the current matrix and get the last one from the matrix stack. * remove the current matrix and get the last one from the matrix stack.
*/ */
public static void pop() { public static void pop() {
Log.verbose("Pop OpenGl Matrix: " + OpenGL.MATRIX_LIST.size()); LOGGER.trace("Pop OpenGl Matrix: " + OpenGL.MATRIX_LIST.size());
if (OpenGL.MATRIX_LIST.size() <= 1) { if (OpenGL.MATRIX_LIST.size() <= 1) {
Log.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size()); LOGGER.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
OpenGL.MATRIX_LIST.clear(); OpenGL.MATRIX_LIST.clear();
OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY); OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY);
OpenGL.matrixCamera = Matrix4f.IDENTITY; OpenGL.matrixCamera = Matrix4f.IDENTITY;
@ -596,11 +639,11 @@ public class OpenGL {
public static boolean programAttach(final int prog, final int shader) { public static boolean programAttach(final int prog, final int shader) {
if (prog < 0) { if (prog < 0) {
Log.error("wrong program ID"); LOGGER.error("wrong program ID");
return false; return false;
} }
if (shader < 0) { if (shader < 0) {
Log.error("wrong shader ID"); LOGGER.error("wrong shader ID");
return false; return false;
} }
GL20.glAttachShader(prog, shader); GL20.glAttachShader(prog, shader);
@ -610,7 +653,7 @@ public class OpenGL {
public static void programBindAttribute(final int prog, final int attribute, final String variableName) { public static void programBindAttribute(final int prog, final int attribute, final String variableName) {
if (prog < 0) { if (prog < 0) {
Log.error("wrong program ID"); LOGGER.error("wrong program ID");
return; return;
} }
GL20.glBindAttribLocation(prog, attribute, variableName); GL20.glBindAttribLocation(prog, attribute, variableName);
@ -618,7 +661,7 @@ public class OpenGL {
public static boolean programCompile(final int prog) { public static boolean programCompile(final int prog) {
if (prog < 0) { if (prog < 0) {
Log.error("wrong program ID"); LOGGER.error("wrong program ID");
return false; return false;
} }
GL20.glLinkProgram(prog); GL20.glLinkProgram(prog);
@ -635,14 +678,14 @@ public class OpenGL {
// this.bufferDisplayError); // this.bufferDisplayError);
// char tmpLog[256]; // char tmpLog[256];
// int idOut=0; // int idOut=0;
// Log.error("Could not compile 'PROGRAM':"); // LOGGER.error("Could not compile 'PROGRAM':");
// for (sizet iii=0; iii<LOGOGLINTERNALBUFFERLEN ; iii++) { // for (sizet iii=0; iii<LOGOGLINTERNALBUFFERLEN ; iii++) {
// tmpLog[idOut] = this.bufferDisplayError[iii]; // tmpLog[idOut] = this.bufferDisplayError[iii];
// if ( tmpLog[idOut] == '\n' // if ( tmpLog[idOut] == '\n'
// || tmpLog[idOut] == '\0' // || tmpLog[idOut] == '\0'
// || idOut >= 256) { // || idOut >= 256) {
// tmpLog[idOut] = '\0'; // tmpLog[idOut] = '\0';
// Log.error(" == > " + tmpLog); // LOGGER.error(" == > " + tmpLog);
// idOut=0; // idOut=0;
// } else { // } else {
// idOut++; // idOut++;
@ -653,7 +696,7 @@ public class OpenGL {
// } // }
// if (idOut != 0) { // if (idOut != 0) {
// tmpLog[idOut] = '\0'; // tmpLog[idOut] = '\0';
// Log.error(" == > " + tmpLog); // LOGGER.error(" == > " + tmpLog);
// } // }
// return false; // return false;
// } // }
@ -666,21 +709,21 @@ public class OpenGL {
public static int programCreate() { public static int programCreate() {
final int programId = GL20.glCreateProgram(); final int programId = GL20.glCreateProgram();
if (programId == 0) { if (programId == 0) {
Log.error("program creation return error ..."); LOGGER.error("program creation return error ...");
OpenGL.checkGlError("glCreateProgram"); OpenGL.checkGlError("glCreateProgram");
return -1; return -1;
} }
Log.debug("Create program with oglID=" + programId); LOGGER.debug("Create program with oglID=" + programId);
return programId; return programId;
} }
public static boolean programDetach(final int prog, final int shader) { public static boolean programDetach(final int prog, final int shader) {
if (prog < 0) { if (prog < 0) {
Log.error("wrong program ID"); LOGGER.error("wrong program ID");
return false; return false;
} }
if (shader < 0) { if (shader < 0) {
Log.error("wrong shader ID"); LOGGER.error("wrong shader ID");
return false; return false;
} }
GL20.glDetachShader(prog, shader); GL20.glDetachShader(prog, shader);
@ -690,17 +733,17 @@ public class OpenGL {
public static int programGetAttributeLocation(final int prog, final String name) { public static int programGetAttributeLocation(final int prog, final String name) {
if (prog < 0) { if (prog < 0) {
Log.error("wrong program ID"); LOGGER.error("wrong program ID");
return -1; return -1;
} }
if (name.length() == 0) { if (name.length() == 0) {
Log.error("wrong name of attribure"); LOGGER.error("wrong name of attribure");
return -1; return -1;
} }
final int val = GL20.glGetAttribLocation(prog, name); final int val = GL20.glGetAttribLocation(prog, name);
if (val < 0) { if (val < 0) {
OpenGL.checkGlError("glGetAttribLocation"); OpenGL.checkGlError("glGetAttribLocation");
Log.warning("glGetAttribLocation('" + name + "') = " + val); LOGGER.warn("glGetAttribLocation('" + name + "') = " + val);
return -1; return -1;
} }
return val; return val;
@ -708,23 +751,23 @@ public class OpenGL {
public static int programGetUniformLocation(final int prog, final String name) { public static int programGetUniformLocation(final int prog, final String name) {
if (prog < 0) { if (prog < 0) {
Log.error("wrong program ID"); LOGGER.error("wrong program ID");
return -1; return -1;
} }
if (name.length() == 0) { if (name.length() == 0) {
Log.error("wrong name of uniform"); LOGGER.error("wrong name of uniform");
return -1; return -1;
} }
final int val = GL20.glGetUniformLocation(prog, name); final int val = GL20.glGetUniformLocation(prog, name);
if (val == GL11.GL_INVALID_VALUE) { if (val == GL11.GL_INVALID_VALUE) {
OpenGL.checkGlError("glGetUniformLocation"); OpenGL.checkGlError("glGetUniformLocation");
Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_VALUE"); LOGGER.warn("glGetUniformLocation('" + name + "') = GL_INVALID_VALUE");
} else if (val == GL11.GL_INVALID_OPERATION) { } else if (val == GL11.GL_INVALID_OPERATION) {
OpenGL.checkGlError("glGetUniformLocation"); OpenGL.checkGlError("glGetUniformLocation");
Log.warning("glGetUniformLocation('" + name + "') = GL_INVALID_OPERATION"); LOGGER.warn("glGetUniformLocation('" + name + "') = GL_INVALID_OPERATION");
} else if (val < 0) { } else if (val < 0) {
OpenGL.checkGlError("glGetUniformLocation"); OpenGL.checkGlError("glGetUniformLocation");
Log.warning("glGetUniformLocation('" + name + "') = " + val); LOGGER.warn("glGetUniformLocation('" + name + "') = " + val);
} }
return val; return val;
} }
@ -750,11 +793,20 @@ public class OpenGL {
GL20.glUniform2f(location, value, value2); GL20.glUniform2f(location, value, value2);
} }
public static void programLoadUniformFloat(final int location, final float value, final float value2, final float value3) { public static void programLoadUniformFloat(
final int location,
final float value,
final float value2,
final float value3) {
GL20.glUniform3f(location, value, value2, 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) { 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); GL20.glUniform4f(location, value, value2, value3, value4);
} }
@ -770,7 +822,12 @@ public class OpenGL {
GL20.glUniform3i(location, value, value2, 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) { 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); GL20.glUniform4i(location, value, value2, value3, value4);
} }
@ -818,7 +875,7 @@ public class OpenGL {
// public static void drawElements(RenderMode mode, List<Integer> indices) { // public static void drawElements(RenderMode mode, List<Integer> indices) {
// if (this.programId >= 0) { // if (this.programId >= 0) {
// updateAllFlags(); // updateAllFlags();
// //Log.debug("Request draw of " + indices.size() + "elements"); // //LOGGER.debug("Request draw of " + indices.size() + "elements");
// GL15.glDrawElements(convertRenderMode.get(mode), indices.size(), // GL15.glDrawElements(convertRenderMode.get(mode), indices.size(),
// GL11.GL_UNSIGNED_INT);//, &indices[0]); // GL11.GL_UNSIGNED_INT);//, &indices[0]);
// checkGlError("glDrawElements"); // checkGlError("glDrawElements");
@ -845,7 +902,7 @@ public class OpenGL {
* @param id Id of the program that might be used * @param id Id of the program that might be used
*/ */
public static void programUse(final int id) { public static void programUse(final int id) {
// Log.verbose("USE prog : " + id); // LOGGER.trace("USE prog : " + id);
// note : In normal openGL case, the system might call with the program ID and // note : In normal openGL case, the system might call with the program ID and
// at the end with 0, // at the end with 0,
// here, we wrap this use to prevent over call of glUseProgram == > then we set // here, we wrap this use to prevent over call of glUseProgram == > then we set
@ -867,9 +924,9 @@ public class OpenGL {
* store current matrix in the matrix stack. * store current matrix in the matrix stack.
*/ */
public static void push() { public static void push() {
Log.verbose("push OpenGl Matrix: " + OpenGL.MATRIX_LIST.size()); LOGGER.trace("push OpenGl Matrix: " + OpenGL.MATRIX_LIST.size());
if (OpenGL.MATRIX_LIST.size() == 0) { if (OpenGL.MATRIX_LIST.size() == 0) {
Log.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size()); LOGGER.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY); OpenGL.MATRIX_LIST.add(Matrix4f.IDENTITY);
return; return;
} }
@ -887,7 +944,8 @@ public class OpenGL {
} }
reader.close(); reader.close();
} catch (final IOException e) { } catch (final IOException e) {
Log.critical("Could not read the file!"); LOGGER.error("Could not read the file!");
System.exit(-1);
} }
return fileSource; return fileSource;
} }
@ -897,15 +955,17 @@ public class OpenGL {
try { try {
final InputStream inputStream = Uri.getStream(name); final InputStream inputStream = Uri.getStream(name);
if (inputStream == null) { if (inputStream == null) {
Log.critical("Could not read the file! " + name); LOGGER.error("Could not read the file! " + name);
System.exit(-1);
} }
final Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name()))); final Reader reader = new BufferedReader(
new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())));
int c = 0; int c = 0;
while ((c = reader.read()) != -1) { while ((c = reader.read()) != -1) {
fileSource.append((char) c); fileSource.append((char) c);
} }
} catch (final IOException e) { } catch (final IOException e) {
Log.error("Could not read the file! " + name); LOGGER.error("Could not read the file! " + name);
e.printStackTrace(); e.printStackTrace();
System.exit(-1); System.exit(-1);
} }
@ -914,7 +974,7 @@ public class OpenGL {
public static void reset() { public static void reset() {
if (OpenGL.DIRECT_MODE) { if (OpenGL.DIRECT_MODE) {
Log.error("TODO ..."); LOGGER.error("TODO ...");
} else { } else {
OpenGL.clearFlagState(); OpenGL.clearFlagState();
OpenGL.programId = -1; OpenGL.programId = -1;
@ -938,7 +998,7 @@ public class OpenGL {
*/ */
public static void setBasicMatrix(final Matrix4f newOne) { public static void setBasicMatrix(final Matrix4f newOne) {
if (OpenGL.MATRIX_LIST.size() != 1) { if (OpenGL.MATRIX_LIST.size() != 1) {
Log.error("matrix is not corect size in the stack : " + OpenGL.MATRIX_LIST.size()); LOGGER.error("matrix is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
} }
OpenGL.MATRIX_LIST.clear(); OpenGL.MATRIX_LIST.clear();
OpenGL.MATRIX_LIST.add(newOne); OpenGL.MATRIX_LIST.add(newOne);
@ -965,7 +1025,7 @@ public class OpenGL {
*/ */
public static void setMatrix(final Matrix4f newOne) { public static void setMatrix(final Matrix4f newOne) {
if (OpenGL.MATRIX_LIST.size() == 0) { if (OpenGL.MATRIX_LIST.size() == 0) {
Log.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size()); LOGGER.error("set matrix list is not corect size in the stack : " + OpenGL.MATRIX_LIST.size());
OpenGL.MATRIX_LIST.add(newOne); OpenGL.MATRIX_LIST.add(newOne);
return; return;
} }
@ -993,25 +1053,25 @@ public class OpenGL {
} }
public static void setViewPort(final Vector2f start, final Vector2f stop) { public static void setViewPort(final Vector2f start, final Vector2f stop) {
// Log.info("setViewport " + start + " " + stop); // LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport((int) start.x(), (int) start.y(), (int) stop.x(), (int) stop.y()); GL11.glViewport((int) start.x(), (int) start.y(), (int) stop.x(), (int) stop.y());
OpenGL.checkGlError("glViewport"); OpenGL.checkGlError("glViewport");
} }
public static void setViewPort(final Vector2i start, final Vector2i stop) { public static void setViewPort(final Vector2i start, final Vector2i stop) {
// Log.info("setViewport " + start + " " + stop); // LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport(start.x(), start.y(), stop.x(), stop.y()); GL11.glViewport(start.x(), start.y(), stop.x(), stop.y());
OpenGL.checkGlError("glViewport"); OpenGL.checkGlError("glViewport");
} }
public static void setViewPort(final Vector3f start, final Vector3f stop) { public static void setViewPort(final Vector3f start, final Vector3f stop) {
// Log.info("setViewport " + start + " " + stop); // LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport((int) start.x(), (int) start.y(), (int) stop.x(), (int) stop.y()); GL11.glViewport((int) start.x(), (int) start.y(), (int) stop.x(), (int) stop.y());
OpenGL.checkGlError("glViewport"); OpenGL.checkGlError("glViewport");
} }
public static void setViewPort(final Vector3i start, final Vector3i stop) { public static void setViewPort(final Vector3i start, final Vector3i stop) {
// Log.info("setViewport " + start + " " + stop); // LOGGER.info("setViewport " + start + " " + stop);
GL11.glViewport(start.x(), start.y(), stop.x(), stop.y()); GL11.glViewport(start.x(), start.y(), stop.x(), stop.y());
OpenGL.checkGlError("glViewport"); OpenGL.checkGlError("glViewport");
} }
@ -1019,18 +1079,18 @@ public class OpenGL {
private static int shaderCreate(final ShaderType type) { private static int shaderCreate(final ShaderType type) {
int shaderId = 0; int shaderId = 0;
if (type == ShaderType.VERTEX) { if (type == ShaderType.VERTEX) {
Log.verbose("create shader: VERTEX"); LOGGER.trace("create shader: VERTEX");
shaderId = GL20.glCreateShader(GL20.GL_VERTEX_SHADER); shaderId = GL20.glCreateShader(GL20.GL_VERTEX_SHADER);
} else if (type == ShaderType.FRAGMENT) { } else if (type == ShaderType.FRAGMENT) {
Log.verbose("create shader: FRAGMENT"); LOGGER.trace("create shader: FRAGMENT");
shaderId = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER); shaderId = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER);
} else { } else {
Log.error("create shader with wrong type ..."); LOGGER.error("create shader with wrong type ...");
return -1; return -1;
} }
Log.verbose("create shader: ... (done)"); LOGGER.trace("create shader: ... (done)");
if (shaderId == 0) { if (shaderId == 0) {
Log.error("glCreateShader return error ..."); LOGGER.error("glCreateShader return error ...");
OpenGL.checkGlError("glCreateShader"); OpenGL.checkGlError("glCreateShader");
return -1; return -1;
} }
@ -1044,8 +1104,8 @@ public class OpenGL {
GL20.glShaderSource(shaderID, shaderSource); GL20.glShaderSource(shaderID, shaderSource);
GL20.glCompileShader(shaderID); GL20.glCompileShader(shaderID);
if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
Log.error(GL20.glGetShaderInfoLog(shaderID, 500)); LOGGER.error(GL20.glGetShaderInfoLog(shaderID, 500));
Log.error("Could not compile the shader"); LOGGER.error("Could not compile the shader");
return -1; return -1;
} }
return shaderID; return shaderID;
@ -1061,7 +1121,7 @@ public class OpenGL {
} }
public static FloatBuffer storeDataInFloatBuffer(final Color[] data) { public static FloatBuffer storeDataInFloatBuffer(final Color[] data) {
float[] tmpData = new float[data.length * 4]; final float[] tmpData = new float[data.length * 4];
for (int iii = 0; iii < data.length; iii++) { for (int iii = 0; iii < data.length; iii++) {
tmpData[iii * 4] = data[iii].r(); tmpData[iii * 4] = data[iii].r();
tmpData[iii * 4 + 1] = data[iii].g(); tmpData[iii * 4 + 1] = data[iii].g();
@ -1098,7 +1158,7 @@ public class OpenGL {
} }
public static FloatBuffer storeDataInFloatBuffer(final Vector2f[] data) { public static FloatBuffer storeDataInFloatBuffer(final Vector2f[] data) {
float[] tmpData = new float[data.length * 2]; final float[] tmpData = new float[data.length * 2];
for (int iii = 0; iii < data.length; iii++) { for (int iii = 0; iii < data.length; iii++) {
tmpData[iii * 2] = data[iii].x(); tmpData[iii * 2] = data[iii].x();
tmpData[iii * 2 + 1] = data[iii].y(); tmpData[iii * 2 + 1] = data[iii].y();
@ -1117,7 +1177,7 @@ public class OpenGL {
} }
public static FloatBuffer storeDataInFloatBuffer(final Vector3f[] data) { public static FloatBuffer storeDataInFloatBuffer(final Vector3f[] data) {
float[] tmpData = new float[data.length * 3]; final float[] tmpData = new float[data.length * 3];
for (int iii = 0; iii < data.length; iii++) { for (int iii = 0; iii < data.length; iii++) {
tmpData[iii * 3] = data[iii].x(); tmpData[iii * 3] = data[iii].x();
tmpData[iii * 3 + 1] = data[iii].y(); tmpData[iii * 3 + 1] = data[iii].y();
@ -1140,7 +1200,7 @@ public class OpenGL {
} }
/** /**
* *
*/ */
public static void swap() { public static void swap() {
@ -1198,11 +1258,11 @@ public class OpenGL {
if (value.current) { if (value.current) {
GL11.glEnable(OpenGL.BASIC_FLAG.get(elem.getKey())); GL11.glEnable(OpenGL.BASIC_FLAG.get(elem.getKey()));
OpenGL.checkGlError("glEnable"); OpenGL.checkGlError("glEnable");
// Log.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey())); // LOGGER.info(" enable : " + elem.getKey() + " " + basicFlag.get(elem.getKey()));
} else { } else {
GL11.glDisable(OpenGL.BASIC_FLAG.get(elem.getKey())); GL11.glDisable(OpenGL.BASIC_FLAG.get(elem.getKey()));
OpenGL.checkGlError("glDisable"); OpenGL.checkGlError("glDisable");
// Log.info(" disable : " + elem.getKey()); // LOGGER.info(" disable : " + elem.getKey());
} }
} }
} }

View File

@ -3,31 +3,33 @@ package org.atriasoft.gale.context;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommandLine { public class CommandLine {
private List<String> listArgs = new ArrayList<String>(); static final Logger LOGGER = LoggerFactory.getLogger(CommandLine.class);
private final List<String> listArgs = new ArrayList<>();
public void parse(String[] args) {
for (int iii=1 ; iii<args.length; iii++) { public void parse(final String[] args) {
Log.info("commandLine : '" + args[iii] + "'" ); for (int iii = 1; iii < args.length; iii++) {
listArgs.add(args[iii]); LOGGER.info("commandLine : '" + args[iii] + "'");
this.listArgs.add(args[iii]);
} }
} }
public int size() { public int size() {
return listArgs.size(); return this.listArgs.size();
} }
public String get(int id) { public String get(final int id) {
return listArgs.get(id); return this.listArgs.get(id);
} }
public void add(String newElement) { public void add(final String newElement) {
listArgs.add(newElement); this.listArgs.add(newElement);
} }
public void remove(int id) { public void remove(final int id) {
listArgs.remove(id); this.listArgs.remove(id);
} }
} }

View File

@ -14,12 +14,13 @@ import org.atriasoft.gale.Gale;
import org.atriasoft.gale.GaleApplication; import org.atriasoft.gale.GaleApplication;
import org.atriasoft.gale.Orientation; import org.atriasoft.gale.Orientation;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.key.KeyKeyboard; import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial; import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus; import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType; import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceManager; import org.atriasoft.gale.resource.ResourceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
interface ActionToDoInAsyncLoop { interface ActionToDoInAsyncLoop {
void run(GaleContext context); void run(GaleContext context);
@ -30,13 +31,14 @@ enum ApplicationState {
} }
public abstract class GaleContext { public abstract class GaleContext {
static final Logger LOGGER = LoggerFactory.getLogger(GaleContext.class);
protected static final int MAX_MANAGE_INPUT = 15; protected static final int MAX_MANAGE_INPUT = 15;
private static final String STATIC_ID_RESIZE = "010__RESIZE"; private static final String STATIC_ID_RESIZE = "010__RESIZE";
private static final String STATIC_ID_REDRAW_ALL = "0100__REDRAW_ALL"; private static final String STATIC_ID_REDRAW_ALL = "0100__REDRAW_ALL";
private static GaleContext globalContext = null; private static GaleContext globalContext = null;
// return true if a flush is needed // return true if a flush is needed
private static int countMemeCheck = 0; private static int countMemeCheck = 0;
/** /**
* From everyware in the program, we can get the context inteface. * From everyware in the program, we can get the context inteface.
* @return current reference on the instance. * @return current reference on the instance.
@ -45,11 +47,11 @@ public abstract class GaleContext {
public static GaleContext getContext() { public static GaleContext getContext() {
return GaleContext.globalContext; return GaleContext.globalContext;
} }
public static void setContext(final GaleContext context) { public static void setContext(final GaleContext context) {
GaleContext.globalContext = context; GaleContext.globalContext = context;
} }
protected ThreadAbstract periodicThread; protected ThreadAbstract periodicThread;
protected GaleApplication application; //!< Application handle protected GaleApplication application; //!< Application handle
protected ApplicationState applicationState = ApplicationState.UNDEFINED; // state of the application protected ApplicationState applicationState = ApplicationState.UNDEFINED; // state of the application
@ -58,7 +60,7 @@ public abstract class GaleContext {
// simulation area: // simulation area:
private long previousDisplayTime; // this is to limit framerate ... in case... private long previousDisplayTime; // this is to limit framerate ... in case...
private final boolean displayFps = true; private final boolean displayFps = true;
private final Lock msgSystemAsyncLock = new ReentrantLock(); private final Lock msgSystemAsyncLock = new ReentrantLock();
private final MessageSystem msgSystemAsync = new MessageSystem(); private final MessageSystem msgSystemAsync = new MessageSystem();
private final MessageSystem msgSystemGui = new MessageSystem(); private final MessageSystem msgSystemGui = new MessageSystem();
@ -71,7 +73,7 @@ public abstract class GaleContext {
protected Vector2f windowsPos; //!< current size of the system protected Vector2f windowsPos; //!< current size of the system
// note: in the current mode, the management is not able to synchronize it good.. // note: in the current mode, the management is not able to synchronize it good..
private final boolean requestSynchronousProcessing = true; //!< this permit to process the event in the global GUI thread instead of the local processing thread. private final boolean requestSynchronousProcessing = true; //!< this permit to process the event in the global GUI thread instead of the local processing thread.
public GaleContext(final GaleApplication application, final String[] args) { public GaleContext(final GaleApplication application, final String[] args) {
// set a basic // set a basic
this.application = application; this.application = application;
@ -79,17 +81,18 @@ public abstract class GaleContext {
GaleContext.setContext(this); GaleContext.setContext(this);
Thread.currentThread().setName("galeThread"); Thread.currentThread().setName("galeThread");
if (this.application == null) { if (this.application == null) {
Log.critical("Can not start context with no Application ==> rtfm ..."); LOGGER.error("Can not start context with no Application ==> rtfm ...");
throw new RuntimeException("Can not start context with no Application ==> rtfm ...");
} }
this.commandLine.parse(args); this.commandLine.parse(args);
Log.info(" == > Gale system init (BEGIN)"); LOGGER.info(" == > Gale system init (BEGIN)");
// create thread to manage real periodic event // create thread to manage real periodic event
this.periodicThread = new PeriodicThread(this); this.periodicThread = new PeriodicThread(this);
// By default we set 2 themes (1 color and 1 shape ...) : // By default we set 2 themes (1 color and 1 shape ...) :
//theme::setNameDefault("GUI", "shape/square/"); //theme::setNameDefault("GUI", "shape/square/");
//theme::setNameDefault("COLOR", "color/black/"); //theme::setNameDefault("COLOR", "color/black/");
// parse the debug level: // parse the debug level:
// for(int iii=0; iii<this.commandLine.size(); ++iii) { // for(int iii=0; iii<this.commandLine.size(); ++iii) {
// if (this.commandLine.get(iii) == "--gale-fps") { // if (this.commandLine.get(iii) == "--gale-fps") {
@ -97,13 +100,13 @@ public abstract class GaleContext {
// } else if ( this.commandLine.get(iii) == "-h" // } else if ( this.commandLine.get(iii) == "-h"
// || this.commandLine.get(iii) == "--help" // || this.commandLine.get(iii) == "--help"
// || startwith(this.commandLine.get(iii), "--gale")) { // || startwith(this.commandLine.get(iii), "--gale")) {
// Log.print("gale - help : "); // LOGGER.print("gale - help : ");
// Log.print(" --gale-fps"); // LOGGER.print(" --gale-fps");
// Log.print(" Display the current fps of the display"); // LOGGER.print(" Display the current fps of the display");
// Log.print(" -h/--help"); // LOGGER.print(" -h/--help");
// Log.print(" Display this help"); // LOGGER.print(" Display this help");
// if (startwith(this.commandLine.get(iii), "--gale")) { // if (startwith(this.commandLine.get(iii), "--gale")) {
// Log.error("gale unknow element in parameter: '" << this.commandLine.get(iii) << "'"); // LOGGER.error("gale unknow element in parameter: '" << this.commandLine.get(iii) << "'");
// // remove parameter ... // // remove parameter ...
// } else { // } else {
// // this is a global help system does not remove it // // this is a global help system does not remove it
@ -116,8 +119,8 @@ public abstract class GaleContext {
// --iii; // --iii;
// } // }
//cout.setOutputFile(true); //cout.setOutputFile(true);
Log.info("GALE v: {}", Gale.getVersion()); LOGGER.info("GALE v: {}", Gale.getVersion());
forceOrientation(Orientation.screenAuto); forceOrientation(Orientation.screenAuto);
postActionAsync(context -> { postActionAsync(context -> {
final GaleApplication appl = context.getApplication(); final GaleApplication appl = context.getApplication();
@ -132,12 +135,12 @@ public abstract class GaleContext {
// this is done at the end to perform a full ended rendering. // this is done at the end to perform a full ended rendering.
context.requestUpdateSize(); context.requestUpdateSize();
}); });
// force a recalculation // force a recalculation
//requestUpdateSize(); //requestUpdateSize();
Log.info(" == > Gale system init (END)"); LOGGER.info(" == > Gale system init (END)");
} }
/** /**
* Inform the Gui that we want to have a copy of the clipboard * Inform the Gui that we want to have a copy of the clipboard
* @param clipboardID ID of the clipboard (STD/SELECTION) only apear here * @param clipboardID ID of the clipboard (STD/SELECTION) only apear here
@ -146,7 +149,7 @@ public abstract class GaleContext {
// just transmit an event , we have the data in the system // just transmit an event , we have the data in the system
operatingSystemClipBoardArrive(clipboardID); operatingSystemClipBoardArrive(clipboardID);
} }
/** /**
* Inform the Gui that we are the new owner of the clipboard * Inform the Gui that we are the new owner of the clipboard
* @param clipboardID ID of the clipboard (STD/SELECTION) only apear here * @param clipboardID ID of the clipboard (STD/SELECTION) only apear here
@ -154,7 +157,7 @@ public abstract class GaleContext {
public void clipBoardSet(final ClipboardList clipboardID) { public void clipBoardSet(final ClipboardList clipboardID) {
// nothing to do, data is already copyed in the GALE clipborad center // nothing to do, data is already copyed in the GALE clipborad center
} }
/** /**
* force the screen orientation (availlable on portable elements ... * force the screen orientation (availlable on portable elements ...
* @param orientation Selected orientation. * @param orientation Selected orientation.
@ -164,11 +167,11 @@ public abstract class GaleContext {
context.forceOrientationThreadGUI(orientation); context.forceOrientationThreadGUI(orientation);
}); });
} }
protected void forceOrientationThreadGUI(final Orientation orientation) { protected void forceOrientationThreadGUI(final Orientation orientation) {
Log.todo("forceOrientation: not implemented"); LOGGER.info("TODO: forceOrientation: not implemented");
} }
/** /**
* Redraw all the windows * Redraw all the windows
*/ */
@ -181,12 +184,12 @@ public abstract class GaleContext {
} }
this.application.onResize(this.windowsSize); this.application.onResize(this.windowsSize);
} }
// Called by Consumer // Called by Consumer
public ActionToDoInAsyncLoop getAction() { public ActionToDoInAsyncLoop getAction() {
return this.msgSystemAsync.getElementWait(); return this.msgSystemAsync.getElementWait();
} }
public GaleApplication getApplication() { public GaleApplication getApplication() {
return this.application; return this.application;
/* /*
@ -199,15 +202,15 @@ public abstract class GaleContext {
} }
*/ */
} }
public CommandLine getCmd() { public CommandLine getCmd() {
return this.commandLine; return this.commandLine;
} }
public boolean getFullScreen() { public boolean getFullScreen() {
return this.fullscreen; return this.fullscreen;
} }
/** /**
* The Application request the current position of the windows. * The Application request the current position of the windows.
* @return Turrent position of the Windows. * @return Turrent position of the Windows.
@ -215,11 +218,11 @@ public abstract class GaleContext {
public Vector2f getPos() { public Vector2f getPos() {
return this.windowsPos; return this.windowsPos;
} }
public ResourceManager getResourcesManager() { public ResourceManager getResourcesManager() {
return this.resourceManager; return this.resourceManager;
} }
/** /**
* get the current windows size * get the current windows size
* @return the current size ... * @return the current size ...
@ -227,7 +230,7 @@ public abstract class GaleContext {
public Vector2f getSize() { public Vector2f getSize() {
return this.windowsSize; return this.windowsSize;
} }
/** /**
* get all Keyboard event from the X system (like many time use of META) * 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. * @param status "true" if all the event will be get, false if we want only ours.
@ -237,11 +240,11 @@ public abstract class GaleContext {
context.grabKeyboardEventsThreadGUI(status); context.grabKeyboardEventsThreadGUI(status);
}); });
} }
protected void grabKeyboardEventsThreadGUI(final boolean status) { protected void grabKeyboardEventsThreadGUI(final boolean status) {
Log.info("grabKeyboardEvents: NOT implemented ..."); LOGGER.info("grabKeyboardEvents: NOT implemented ...");
} }
/** /**
* get all Mouse/Touch events from the X system * 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 status "true" if all the event will be get, false if we want only ours.
@ -252,12 +255,12 @@ public abstract class GaleContext {
context.grabPointerEventsThreadGUI(status, forcedPosition); context.grabPointerEventsThreadGUI(status, forcedPosition);
}); });
} }
protected void grabPointerEventsThreadGUI(final boolean status, final Vector2f forcedPosition) { protected void grabPointerEventsThreadGUI(final boolean status, final Vector2f forcedPosition) {
Log.info("grabPointerEvents: NOT implemented ..."); LOGGER.info("grabPointerEvents: NOT implemented ...");
} }
/** /**
* The Application request that the Windows will be Hidden. * The Application request that the Windows will be Hidden.
*/ */
@ -266,15 +269,15 @@ public abstract class GaleContext {
context.hideThreadGUI(); context.hideThreadGUI();
}); });
} }
protected void hideThreadGUI() { protected void hideThreadGUI() {
Log.info("hide: NOT implemented ..."); LOGGER.info("hide: NOT implemented ...");
} }
public boolean isGrabPointerEvents() { public boolean isGrabPointerEvents() {
return false; return false;
} }
/** /**
* Hide the virtual keyboard (for touch system only) * Hide the virtual keyboard (for touch system only)
*/ */
@ -283,11 +286,11 @@ public abstract class GaleContext {
context.keyboardHideThreadGUI(); context.keyboardHideThreadGUI();
}); });
} }
protected void keyboardHideThreadGUI() { protected void keyboardHideThreadGUI() {
Log.info("keyboardHide: NOT implemented ..."); LOGGER.info("keyboardHide: NOT implemented ...");
} }
/** /**
* display the virtual keyboard (for touch system only) * display the virtual keyboard (for touch system only)
*/ */
@ -296,11 +299,11 @@ public abstract class GaleContext {
context.keyboardShowThreadGUI(); context.keyboardShowThreadGUI();
}); });
} }
protected void keyboardShowThreadGUI() { protected void keyboardShowThreadGUI() {
Log.info("keyboardShow: NOT implemented ..."); LOGGER.info("keyboardShow: NOT implemented ...");
} }
/** /**
* Open an URL on an eternal brother. * Open an URL on an eternal brother.
* @param url URL to open. * @param url URL to open.
@ -310,25 +313,25 @@ public abstract class GaleContext {
context.openURLThreadGUI(url); context.openURLThreadGUI(url);
}); });
} }
protected void openURLThreadGUI(final String url) { protected void openURLThreadGUI(final String url) {
Log.info("openURL: NOT implemented ..."); LOGGER.info("openURL: NOT implemented ...");
} }
/** /**
* The current context is set in background (framerate is slowing down (max fps)/5 # 4fps) * The current context is set in background (framerate is slowing down (max fps)/5 # 4fps)
*/ */
public void operatingSystemBackground() { public void operatingSystemBackground() {
// set the current interface : // set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) { try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemBackground..."); LOGGER.info("operatingSystemBackground...");
// if (this.windowsCurrent != null) { // if (this.windowsCurrent != null) {
// this.windowsCurrent.onStateBackground(); // this.windowsCurrent.onStateBackground();
// } // }
// release the current interface : // release the current interface :
} }
} }
/** /**
* Call by the OS when a clipboard arrive to US (previously requested by a widget) * Call by the OS when a clipboard arrive to US (previously requested by a widget)
* @param clipboardID of the clipboard * @param clipboardID of the clipboard
@ -341,14 +344,14 @@ public abstract class GaleContext {
} }
}); });
} }
public boolean operatingSystemDraw(final boolean displayEveryTime) { public boolean operatingSystemDraw(final boolean displayEveryTime) {
if (GaleContext.countMemeCheck++ >= 10 * 16) { if (GaleContext.countMemeCheck++ >= 10 * 16) {
GaleContext.countMemeCheck = 0; GaleContext.countMemeCheck = 0;
} }
Log.verbose("Call draw"); LOGGER.trace("Call draw");
final long currentTime = System.nanoTime(); final long currentTime = System.nanoTime();
//Log.warning("Time = " << currentTime << " " << currentTime2); //LOGGER.warn("Time = " << currentTime << " " << currentTime2);
// TODO Review this ... // TODO Review this ...
// this is to prevent the multiple display at the a high frequency ... // this is to prevent the multiple display at the a high frequency ...
if (currentTime - this.previousDisplayTime < 8) { if (currentTime - this.previousDisplayTime < 8) {
@ -374,18 +377,18 @@ public abstract class GaleContext {
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) { try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
/* /*
Lock the event processing Lock the event processing
Wait end of current processing Wait end of current processing
Display ... Display ...
Release the event processing Release the event processing
*/ */
if (this.application != null) { if (this.application != null) {
if (this.applicationState == ApplicationState.RUNNING) { if (this.applicationState == ApplicationState.RUNNING) {
// Redraw all needed elements // Redraw all needed elements
//Log.debug("Regenerate Display"); //LOGGER.debug("Regenerate Display");
this.application.onRegenerateDisplay(this); this.application.onRegenerateDisplay(this);
needRedraw = this.application.isDrawingNeeded(); needRedraw = this.application.isDrawingNeeded();
} else { } else {
@ -407,7 +410,7 @@ public abstract class GaleContext {
this.fpsSystemContext.tic(); this.fpsSystemContext.tic();
} }
if (needRedraw || displayEveryTime) { if (needRedraw || displayEveryTime) {
//Log.debug(" ==> real Draw"); //LOGGER.debug(" ==> real Draw");
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) { try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
this.resourceManager.updateContext(); this.resourceManager.updateContext();
} }
@ -430,7 +433,7 @@ public abstract class GaleContext {
OpenGL.setViewPort(new Vector2f(0, 0), this.application.getSize()); OpenGL.setViewPort(new Vector2f(0, 0), this.application.getSize());
final Color bgColor = new Color(0.8f, 0.5f, 0.8f, 1.0f); final Color bgColor = new Color(0.8f, 0.5f, 0.8f, 1.0f);
OpenGL.clearColor(bgColor); OpenGL.clearColor(bgColor);
//Log.info("==> appl clear ==> not created ..."); //LOGGER.info("==> appl clear ==> not created ...");
} }
} }
hasDisplayDone = true; hasDisplayDone = true;
@ -441,7 +444,7 @@ public abstract class GaleContext {
this.fpsFlush.tic(); this.fpsFlush.tic();
} }
if (hasDisplayDone) { if (hasDisplayDone) {
//Log.info("lklklklklk " << displayEveryTime); //LOGGER.info("lklklklklk " << displayEveryTime);
if (this.displayFps) { if (this.displayFps) {
this.fpsFlush.incrementCounter(); this.fpsFlush.incrementCounter();
} }
@ -475,21 +478,21 @@ public abstract class GaleContext {
OpenGL.threadHasNoMoreContext(); OpenGL.threadHasNoMoreContext();
return hasDisplayDone; return hasDisplayDone;
} }
/** /**
* The current context is set in foreground (framerate is maximum speed) * The current context is set in foreground (framerate is maximum speed)
*/ */
public void operatingSystemForeground() { public void operatingSystemForeground() {
// set the current interface : // set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) { try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemForeground..."); LOGGER.info("operatingSystemForeground...");
// if (this.windowsCurrent != null) { // if (this.windowsCurrent != null) {
// this.windowsCurrent.onStateForeground(); // this.windowsCurrent.onStateForeground();
// } // }
} }
} }
/** /**
* The OS inform that the Windows is now Hidden. * The OS inform that the Windows is now Hidden.
*/ */
@ -505,10 +508,10 @@ public abstract class GaleContext {
char, char,
state); state);
*/ */
Log.todo("HIDE ... "); LOGGER.info("TODO: HIDE ... ");
}); });
} }
/** /**
* The OS inform that the current windows has change his position. * The OS inform that the current windows has change his position.
* @param pos New position of the Windows. * @param pos New position of the Windows.
@ -518,7 +521,7 @@ public abstract class GaleContext {
return; return;
} }
postActionAsync(context -> { postActionAsync(context -> {
Log.debug("Receive MSG : THREADMOVE : {} ==> {}", context.windowsPos, pos); LOGGER.debug("Receive MSG : THREADMOVE : {} ==> {}", context.windowsPos, pos);
context.windowsPos = pos; context.windowsPos = pos;
final GaleApplication appl = context.getApplication(); final GaleApplication appl = context.getApplication();
if (appl == null) { if (appl == null) {
@ -527,27 +530,27 @@ public abstract class GaleContext {
appl.onMovePosition(context.windowsPos); appl.onMovePosition(context.windowsPos);
}); });
} }
/** /**
* The OS inform that the openGL ext has been destroy == > use to automaticly reload the texture and other thinks ... * The OS inform that the openGL ext has been destroy == > use to automaticly reload the texture and other thinks ...
*/ */
public void operatingSystemOpenGlContextDestroy() { public void operatingSystemOpenGlContextDestroy() {
this.resourceManager.contextHasBeenDestroyed(); this.resourceManager.contextHasBeenDestroyed();
} }
/** /**
* The OS inform that the current windows has change his size. * The OS inform that the current windows has change his size.
* @param size new size of the windows. * @param size new size of the windows.
*/ */
public void operatingSystemResize(final Vector2f size) { public void operatingSystemResize(final Vector2f size) {
Log.warning("Resize request={} previous={}", size, this.windowsSize); LOGGER.warn("Resize request={} previous={}", size, this.windowsSize);
if (this.windowsSize.equals(size)) { if (this.windowsSize.equals(size)) {
return; return;
} }
// TODO Better in the thread ... ==> but generate some init error ... // TODO Better in the thread ... ==> but generate some init error ...
//gale::Dimension::setPixelWindowsSize(size); //gale::Dimension::setPixelWindowsSize(size);
postActionAsync(GaleContext.STATIC_ID_RESIZE, context -> { postActionAsync(GaleContext.STATIC_ID_RESIZE, context -> {
Log.error("Receive MSG : THREAD_RESIZE : {} ==> {}", context.windowsSize, size); LOGGER.error("Receive MSG : THREAD_RESIZE : {} ==> {}", context.windowsSize, size);
context.windowsSize = size; context.windowsSize = size;
//gale::Dimension::setPixelWindowsSize(context.windowsSize); //gale::Dimension::setPixelWindowsSize(context.windowsSize);
final GaleApplication tmpAppl = context.getApplication(); final GaleApplication tmpAppl = context.getApplication();
@ -558,14 +561,14 @@ public abstract class GaleContext {
context.forceRedrawAll(); context.forceRedrawAll();
}); });
} }
/** /**
* The current context is resumed * The current context is resumed
*/ */
public void operatingSystemResume() { public void operatingSystemResume() {
// set the current interface : // set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) { try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemResume..."); LOGGER.info("operatingSystemResume...");
this.previousDisplayTime = System.currentTimeMillis(); this.previousDisplayTime = System.currentTimeMillis();
// TODO this.objectManager.timeCallResume(this.previousDisplayTime); // TODO this.objectManager.timeCallResume(this.previousDisplayTime);
// if (this.windowsCurrent != null) { // if (this.windowsCurrent != null) {
@ -573,9 +576,14 @@ public abstract class GaleContext {
// } // }
} }
} }
public void operatingSystemSetInput(final KeySpecial special, final KeyType type, final KeyStatus status, final int pointerID, final Vector2f pos) { public void operatingSystemSetInput(
Log.verbose("Position motion: " + pos); final KeySpecial special,
final KeyType type,
final KeyStatus status,
final int pointerID,
final Vector2f pos) {
LOGGER.trace("Position motion: " + pos);
postActionAsync(context -> { postActionAsync(context -> {
final GaleApplication appl = context.getApplication(); final GaleApplication appl = context.getApplication();
if (appl == null) { if (appl == null) {
@ -584,12 +592,21 @@ public abstract class GaleContext {
appl.onPointer(special, type, pointerID, pos, status); appl.onPointer(special, type, pointerID, pos, status);
}); });
} }
public void operatingSystemsetKeyboard(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final boolean isARepeateKey) { public void operatingSystemsetKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final KeyStatus state,
final boolean isARepeateKey) {
operatingSystemsetKeyboard(special, type, state, isARepeateKey, (char) 0); 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) { public void operatingSystemsetKeyboard(
final KeySpecial special,
final KeyKeyboard type,
final KeyStatus state,
final boolean isARepeateKey,
final Character charValue) {
KeyStatus tmpState = state; KeyStatus tmpState = state;
if (isARepeateKey) { if (isARepeateKey) {
if (tmpState == KeyStatus.down) { if (tmpState == KeyStatus.down) {
@ -600,8 +617,12 @@ public abstract class GaleContext {
} }
operatingSystemsetKeyboard2(special, type, state, charValue); operatingSystemsetKeyboard2(special, type, state, charValue);
} }
public void operatingSystemsetKeyboard2(final KeySpecial special, final KeyKeyboard type, final KeyStatus state, final Character charValue) { public void operatingSystemsetKeyboard2(
final KeySpecial special,
final KeyKeyboard type,
final KeyStatus state,
final Character charValue) {
postActionAsync(context -> { postActionAsync(context -> {
final GaleApplication appl = context.getApplication(); final GaleApplication appl = context.getApplication();
if (appl == null) { if (appl == null) {
@ -610,7 +631,7 @@ public abstract class GaleContext {
appl.onKeyboard(special, type, charValue, state); appl.onKeyboard(special, type, charValue, state);
}); });
} }
/** /**
* The OS inform that the Windows is now visible. * The OS inform that the Windows is now visible.
*/ */
@ -626,17 +647,17 @@ public abstract class GaleContext {
char, char,
state); state);
*/ */
Log.todo("SHOW ... "); LOGGER.info("TODO: SHOW ... ");
}); });
} }
/** /**
* The OS Inform that the Window has been killed * The OS Inform that the Window has been killed
*/ */
public void operatingSystemStop() { public void operatingSystemStop() {
// set the current interface : // set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) { try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemStop..."); LOGGER.info("operatingSystemStop...");
if (this.application == null) { if (this.application == null) {
stop(); stop();
return; return;
@ -644,22 +665,22 @@ public abstract class GaleContext {
this.application.onKillDemand(this); this.application.onKillDemand(this);
} }
} }
/** /**
* The current context is suspended * The current context is suspended
*/ */
public void operatingSystemSuspend() { public void operatingSystemSuspend() {
// set the current interface : // set the current interface :
try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) { try (AutoUnLock autoUnlock = AutoUnLock.lock(this.msgSystemAsyncLock)) {
Log.info("operatingSystemSuspend..."); LOGGER.info("operatingSystemSuspend...");
this.previousDisplayTime = 0; this.previousDisplayTime = 0;
// if (this.windowsCurrent != null) { // if (this.windowsCurrent != null) {
// this.windowsCurrent.onStateSuspend(); // this.windowsCurrent.onStateSuspend();
// } // }
} }
} }
protected void postActionAsync(final ActionToDoInAsyncLoop data) { protected void postActionAsync(final ActionToDoInAsyncLoop data) {
if (this.requestSynchronousProcessing) { if (this.requestSynchronousProcessing) {
this.msgSystemGui.addElement(data); this.msgSystemGui.addElement(data);
@ -668,7 +689,7 @@ public abstract class GaleContext {
} }
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object. //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
} }
protected void postActionAsync(final String uniqueID, final ActionToDoInAsyncLoop data) { protected void postActionAsync(final String uniqueID, final ActionToDoInAsyncLoop data) {
if (this.requestSynchronousProcessing) { if (this.requestSynchronousProcessing) {
this.msgSystemGui.addElement(uniqueID, data); this.msgSystemGui.addElement(uniqueID, data);
@ -677,12 +698,12 @@ public abstract class GaleContext {
} }
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object. //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
} }
protected void postActionToGui(final ActionToDoInAsyncLoop data) { protected void postActionToGui(final ActionToDoInAsyncLoop data) {
this.msgSystemGui.addElement(data); this.msgSystemGui.addElement(data);
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object. //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
} }
/** /**
* Processing all the event arrived ... (commonly called in draw function) * Processing all the event arrived ... (commonly called in draw function)
*/ */
@ -693,7 +714,7 @@ public abstract class GaleContext {
try { try {
int nbEvent = 0; int nbEvent = 0;
while (this.msgSystemAsync.getSize() > 0) { while (this.msgSystemAsync.getSize() > 0) {
Log.verbose(" [" + nbEvent + "] event ..."); LOGGER.trace(" [" + nbEvent + "] event ...");
nbEvent++; nbEvent++;
final ActionToDoInAsyncLoop func = this.msgSystemAsync.getElementWait(); final ActionToDoInAsyncLoop func = this.msgSystemAsync.getElementWait();
if (func == null) { if (func == null) {
@ -702,12 +723,13 @@ public abstract class GaleContext {
func.run(this); func.run(this);
} }
} catch (final Exception e) { } catch (final Exception e) {
Log.critical("Catch exception in main event Loop ...", e); LOGGER.error("Catch exception in main event Loop ...", e);
throw e;
} finally { } finally {
this.msgSystemAsyncLock.unlock(); this.msgSystemAsyncLock.unlock();
} }
} }
/** /**
* Process event in the GUI thread ==> prevent dead lock on the global GUI interface * Process event in the GUI thread ==> prevent dead lock on the global GUI interface
*/ */
@ -724,14 +746,15 @@ public abstract class GaleContext {
func.run(this); func.run(this);
} }
} catch (final Exception e) { } catch (final Exception e) {
Log.critical("Catch exception in main event Loop ...", e); LOGGER.error("Catch exception in main event Loop ...", e);
throw e;
} finally { } finally {
this.msgSystemAsyncLock.unlock(); this.msgSystemAsyncLock.unlock();
} }
} }
// gale::Context::~Context() { // gale::Context::~Context() {
// Log.info(" == > Gale system Un-Init (BEGIN)"); // LOGGER.info(" == > Gale system Un-Init (BEGIN)");
// this.periodicThread.threadStart(); // this.periodicThread.threadStart();
// getResourcesManager().applicationExiting(); // getResourcesManager().applicationExiting();
// // TODO Clean the message list ... // // TODO Clean the message list ...
@ -751,7 +774,7 @@ public abstract class GaleContext {
// //this.objectManager.cleanInternalRemoved(); // //this.objectManager.cleanInternalRemoved();
// this.resourceManager.cleanInternalRemoved(); // this.resourceManager.cleanInternalRemoved();
// //
// Log.info("List of all widget of this context must be equal at 0 ==> otherwise some remove is missing"); // LOGGER.info("List of all widget of this context must be equal at 0 ==> otherwise some remove is missing");
// //this.objectManager.displayListObject(); // //this.objectManager.displayListObject();
// // Resource is an lower element as objects ... // // Resource is an lower element as objects ...
// this.resourceManager.unInit(); // this.resourceManager.unInit();
@ -759,7 +782,7 @@ public abstract class GaleContext {
// //this.objectManager.unInit(); // //this.objectManager.unInit();
// // release the current interface : // // release the current interface :
// unLockContext(); // unLockContext();
// Log.info(" == > Gale system Un-Init (END)"); // LOGGER.info(" == > Gale system Un-Init (END)");
// if (this.simulationActive) { // if (this.simulationActive) {
// // in simulation case: // // in simulation case:
// this.simulationFile.close(); // this.simulationFile.close();
@ -767,25 +790,25 @@ public abstract class GaleContext {
// } // }
public void requestUpdateSize() { public void requestUpdateSize() {
postActionAsync(this.STATIC_ID_REDRAW_ALL, context -> { postActionAsync(this.STATIC_ID_REDRAW_ALL, context -> {
//Log.debug("Receive MSG : THREADRESIZE"); //LOGGER.debug("Receive MSG : THREADRESIZE");
context.forceRedrawAll(); context.forceRedrawAll();
}); });
} }
/** /**
* reset event management for the IO like Input ou Mouse or keyborad * reset event management for the IO like Input ou Mouse or keyborad
*/ */
public void resetIOEvent() { public void resetIOEvent() {
// TODO this.input.newLayerSet(); // TODO this.input.newLayerSet();
} }
/** /**
* Internal API to run the processing of the event loop ... * Internal API to run the processing of the event loop ...
* @return The Exit value of the program * @return The Exit value of the program
* @note INTERNAL API * @note INTERNAL API
*/ */
public abstract int run(); public abstract int run();
/** /**
* set the cursor display type. * set the cursor display type.
* @param newCursor selected new cursor. * @param newCursor selected new cursor.
@ -795,11 +818,11 @@ public abstract class GaleContext {
context.setCursorThreadGUI(newCursor); context.setCursorThreadGUI(newCursor);
}); });
} }
public void setCursorThreadGUI(final Cursor newCursor) { public void setCursorThreadGUI(final Cursor newCursor) {
Log.info("setCursor: NOT implemented ..."); LOGGER.info("setCursor: NOT implemented ...");
} }
/** /**
* The application request a change of his current size force the fullscreen mode. * The application request a change of his current size force the fullscreen mode.
* @param status status of the fullscreen mode. * @param status status of the fullscreen mode.
@ -810,11 +833,11 @@ public abstract class GaleContext {
context.setFullScreenThreadGUI(status); context.setFullScreenThreadGUI(status);
}); });
} }
protected void setFullScreenThreadGUI(final boolean status) { protected void setFullScreenThreadGUI(final boolean status) {
Log.info("setFullScreen: NOT implemented ..."); LOGGER.info("setFullScreen: NOT implemented ...");
} }
/** /**
* set the Icon of the program * set the Icon of the program
* @param inputFile new filename icon of the current program. * @param inputFile new filename icon of the current program.
@ -824,11 +847,11 @@ public abstract class GaleContext {
context.setIconThreadGUI(inputFile); context.setIconThreadGUI(inputFile);
}); });
} }
public void setIconThreadGUI(final Uri inputFile) { public void setIconThreadGUI(final Uri inputFile) {
Log.info("setIcon: NOT implemented ..."); LOGGER.info("setIcon: NOT implemented ...");
} }
/** /**
* The Application request that the current windows will change his position. * The Application request that the current windows will change his position.
* @param pos New position of the Windows requested. * @param pos New position of the Windows requested.
@ -838,11 +861,11 @@ public abstract class GaleContext {
context.setPosThreadGUI(pos); context.setPosThreadGUI(pos);
}); });
} }
protected void setPosThreadGUI(final Vector2f pos) { protected void setPosThreadGUI(final Vector2f pos) {
Log.info("setPos: NOT implemented ..."); LOGGER.info("setPos: NOT implemented ...");
} }
/** /**
* The application request a change of his current size. * The application request a change of his current size.
* @param size new Requested size of the windows. * @param size new Requested size of the windows.
@ -852,11 +875,11 @@ public abstract class GaleContext {
context.setSizeThreadGUI(size); context.setSizeThreadGUI(size);
}); });
} }
protected void setSizeThreadGUI(final Vector2f size) { protected void setSizeThreadGUI(final Vector2f size) {
Log.info("setSize: NOT implemented ..."); LOGGER.info("setSize: NOT implemented ...");
} }
/** /**
* set the new title of the windows * set the new title of the windows
* @param title New desired title * @param title New desired title
@ -866,15 +889,15 @@ public abstract class GaleContext {
context.setTitleThreadGUI(title); context.setTitleThreadGUI(title);
}); });
} }
/** /**
* set the new title of the windows * set the new title of the windows
* @param title New desired title * @param title New desired title
*/ */
protected void setTitleThreadGUI(final String title) { protected void setTitleThreadGUI(final String title) {
Log.info("setTitle: NOT implemented ..."); LOGGER.info("setTitle: NOT implemented ...");
} }
/** /**
* Enable or Disable the decoration on the Windows (availlable only on Desktop) * Enable or Disable the decoration on the Windows (availlable only on Desktop)
* @param status "true" to enable decoration / false otherwise * @param status "true" to enable decoration / false otherwise
@ -884,11 +907,11 @@ public abstract class GaleContext {
context.setWindowsDecorationThreadGUI(status); context.setWindowsDecorationThreadGUI(status);
}); });
} }
protected void setWindowsDecorationThreadGUI(final boolean status) { protected void setWindowsDecorationThreadGUI(final boolean status) {
Log.info("setWindowsDecoration: NOT implemented ..."); LOGGER.info("setWindowsDecoration: NOT implemented ...");
} }
/** /**
* The Application request that the Windows will be visible. * The Application request that the Windows will be visible.
*/ */
@ -897,11 +920,11 @@ public abstract class GaleContext {
context.showThreadGUI(); context.showThreadGUI();
}); });
} }
public void showThreadGUI() { public void showThreadGUI() {
Log.info("show: NOT implemented ..."); LOGGER.info("show: NOT implemented ...");
} }
/** /**
* StartProcessing (2nd thread). * StartProcessing (2nd thread).
* @note to call when all the Context is started * @note to call when all the Context is started
@ -918,12 +941,12 @@ public abstract class GaleContext {
} }
} }
} }
/** /**
* The application request that the Window will be killed * The application request that the Window will be killed
*/ */
public void stop() { public void stop() {
Log.warning("stop: NOT implemented for this platform..."); LOGGER.warn("stop: NOT implemented for this platform...");
} }
} }

View File

@ -31,7 +31,6 @@ import org.atriasoft.gale.DisplayManagerDraw;
import org.atriasoft.gale.Fps; import org.atriasoft.gale.Fps;
import org.atriasoft.gale.GaleApplication; import org.atriasoft.gale.GaleApplication;
import org.atriasoft.gale.context.GaleContext; import org.atriasoft.gale.context.GaleContext;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.key.KeyKeyboard; import org.atriasoft.gale.key.KeyKeyboard;
import org.atriasoft.gale.key.KeySpecial; import org.atriasoft.gale.key.KeySpecial;
import org.atriasoft.gale.key.KeyStatus; import org.atriasoft.gale.key.KeyStatus;
@ -45,10 +44,12 @@ import org.lwjgl.opengl.awt.AWTGLCanvas;
//import org.lwjgl.opengl.GL; //import org.lwjgl.opengl.GL;
//import org.lwjgl.system.MemoryStack; //import org.lwjgl.system.MemoryStack;
import org.lwjgl.opengl.awt.GLData; import org.lwjgl.opengl.awt.GLData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.atriasoft.reggol.Logger; public class ContextLWJGLAWT extends GaleContext
implements MouseListener, MouseMotionListener, KeyListener, MouseWheelListener {
public class ContextLWJGLAWT extends GaleContext implements MouseListener, MouseMotionListener, KeyListener, MouseWheelListener { static final Logger LOGGER = LoggerFactory.getLogger(ContextLWJGLAWT.class);
private static final int WIDTH = 800; private static final int WIDTH = 800;
private static final int HEIGHT = 600; private static final int HEIGHT = 600;
private static final int MAX_MANAGE_INPUT = 15; private static final int MAX_MANAGE_INPUT = 15;
@ -57,36 +58,36 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
private static float delta; private static float delta;
private static double whellOffsetY; private static double whellOffsetY;
private static double whellOffsetX; private static double whellOffsetX;
private static boolean rightButtonStateDown = false; private static boolean rightButtonStateDown = false;
private static boolean leftButtonStateDown = false; private static boolean leftButtonStateDown = false;
private static double lastMousePositionX = 0; private static double lastMousePositionX = 0;
private static double lastMousePositionY = 0; private static double lastMousePositionY = 0;
private static double currentMousePositionX = 0; private static double currentMousePositionX = 0;
private static double currentMousePositionY = 0; private static double currentMousePositionY = 0;
public static GaleContext create(final GaleApplication application, final String[] arg) { public static GaleContext create(final GaleApplication application, final String[] arg) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return new ContextLWJGLAWT(application, arg); return new ContextLWJGLAWT(application, arg);
} }
private static long getCurrentTime() { private static long getCurrentTime() {
return System.currentTimeMillis(); return System.currentTimeMillis();
} }
public static float getFrameTimeSecconds() { public static float getFrameTimeSecconds() {
return ContextLWJGLAWT.delta; return ContextLWJGLAWT.delta;
} }
private final boolean[] inputIsPressed = new boolean[ContextLWJGLAWT.MAX_MANAGE_INPUT]; private final boolean[] inputIsPressed = new boolean[ContextLWJGLAWT.MAX_MANAGE_INPUT];
private Vector2f decoratedWindowsSize = Vector2f.ZERO; private Vector2f decoratedWindowsSize = Vector2f.ZERO;
private Vector2f cursorPos = Vector2f.ZERO; private Vector2f cursorPos = Vector2f.ZERO;
private final Vector2f cursorSize = Vector2f.ZERO; private final Vector2f cursorSize = Vector2f.ZERO;
private final Fps fps = new Fps("Main Loop", true); private final Fps fps = new Fps("Main Loop", true);
private DisplayManagerDraw drawer = null; private DisplayManagerDraw drawer = null;
// The window handle // The window handle
private final long window = 0; private final long window = 0;
@ -94,14 +95,14 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
// Generic UI properties // Generic UI properties
private JFrame frame; private JFrame frame;
private GLData glData; private GLData glData;
private AWTGLCanvas canvas; private AWTGLCanvas canvas;
private Robot robot = null; private Robot robot = null;
private final List<Integer> pressedKey = new ArrayList<>(); private final List<Integer> pressedKey = new ArrayList<>();
private Boolean isInitialized = false; private Boolean isInitialized = false;
public ContextLWJGLAWT(final GaleApplication application, final String[] args) { public ContextLWJGLAWT(final GaleApplication application, final String[] args) {
super(application, args); super(application, args);
System.out.println("Hello JOGL !"); System.out.println("Hello JOGL !");
@ -109,7 +110,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
start2ndThreadProcessing(); start2ndThreadProcessing();
this.isInitialized = true; this.isInitialized = true;
} }
private int getUniqueIndex(final KeyEvent e) { private int getUniqueIndex(final KeyEvent e) {
int internalKeyValue = e.getKeyCode(); int internalKeyValue = e.getKeyCode();
if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) {
@ -123,7 +124,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
} }
return internalKeyValue; return internalKeyValue;
} }
@Override @Override
protected void grabPointerEventsThreadGUI(final boolean status, final Vector2f forcedPosition) { protected void grabPointerEventsThreadGUI(final boolean status, final Vector2f forcedPosition) {
if (status) { if (status) {
@ -139,14 +140,15 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
showCursor(); showCursor();
} }
} }
private void hideCursor() { private void hideCursor() {
final int[] pixels = new int[16 * 16]; final int[] pixels = new int[16 * 16];
final Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16)); final Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
final Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor"); final Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0),
"invisiblecursor");
this.frame.setCursor(transparentCursor); this.frame.setCursor(transparentCursor);
} }
private void initWindows() { private void initWindows() {
this.frame = new JFrame("Gale base"); this.frame = new JFrame("Gale base");
this.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
@ -158,19 +160,21 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
this.frame.add(this.canvas = new AWTGLCanvas(this.glData) { this.frame.add(this.canvas = new AWTGLCanvas(this.glData) {
@Override @Override
public void initGL() { public void initGL() {
System.out.println("OpenGL version: " + this.effective.majorVersion + "." + this.effective.minorVersion + " (Profile: " + this.effective.profile + ")"); System.out.println("OpenGL version: " + this.effective.majorVersion + "." + this.effective.minorVersion
+ " (Profile: " + this.effective.profile + ")");
GL.createCapabilities(); GL.createCapabilities();
GL11.glClearColor(0.3f, 0.4f, 0.5f, 1); GL11.glClearColor(0.3f, 0.4f, 0.5f, 1);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
} }
@Override @Override
public void paintGL() { public void paintGL() {
final long startRender = System.currentTimeMillis(); final long startRender = System.currentTimeMillis();
//Log.warning("Draw ... "); //LOGGER.warn("Draw ... ");
final int w = getWidth(); final int w = getWidth();
final int h = getHeight(); final int h = getHeight();
if (ContextLWJGLAWT.this.decoratedWindowsSize.x() != w || ContextLWJGLAWT.this.decoratedWindowsSize.y() != h) { if (ContextLWJGLAWT.this.decoratedWindowsSize.x() != w
|| ContextLWJGLAWT.this.decoratedWindowsSize.y() != h) {
ContextLWJGLAWT.this.decoratedWindowsSize = new Vector2f(w, h); ContextLWJGLAWT.this.decoratedWindowsSize = new Vector2f(w, h);
final Rectangle bounds = ContextLWJGLAWT.this.canvas.getBounds(); final Rectangle bounds = ContextLWJGLAWT.this.canvas.getBounds();
final Vector2f tmpWindowsSize = new Vector2f(bounds.width, bounds.height); final Vector2f tmpWindowsSize = new Vector2f(bounds.width, bounds.height);
@ -178,9 +182,11 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
} }
operatingSystemDraw(true); operatingSystemDraw(true);
swapBuffers(); swapBuffers();
/*
if (Logger.isCriticalOccured()) { if (Logger.isCriticalOccured()) {
ContextLWJGLAWT.this.frame.dispose(); ContextLWJGLAWT.this.frame.dispose();
} }
*/
// Process event from the GUI (specific events... // Process event from the GUI (specific events...
processEventsGui(); processEventsGui();
/* /*
@ -204,21 +210,21 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
this.canvas.addKeyListener(this); this.canvas.addKeyListener(this);
this.canvas.addMouseWheelListener(this); this.canvas.addMouseWheelListener(this);
this.frame.transferFocus(); this.frame.transferFocus();
ContextLWJGLAWT.lastFrameTime = ContextLWJGLAWT.getCurrentTime(); ContextLWJGLAWT.lastFrameTime = ContextLWJGLAWT.getCurrentTime();
} }
@Override @Override
public boolean isGrabPointerEvents() { public boolean isGrabPointerEvents() {
return this.robot != null; return this.robot != null;
} }
public void keyEvent(final KeyEvent e, final boolean pressed, final boolean thisIsAReapeateKey) { public void keyEvent(final KeyEvent e, final boolean pressed, final boolean thisIsAReapeateKey) {
//Log.info("event " + thisIsAReapeateKey + " " + e.getKeyCode() + " " + e); //LOGGER.info("event " + thisIsAReapeateKey + " " + e.getKeyCode() + " " + e);
boolean find = true; boolean find = true;
KeyKeyboard keyInput = KeyKeyboard.UNKNOWN; KeyKeyboard keyInput = KeyKeyboard.UNKNOWN;
//Log.error("keyboard input " + e.getWhen() + " " + e.getKeyCode() + " " + e.getKeyLocation()); //LOGGER.error("keyboard input " + e.getWhen() + " " + e.getKeyCode() + " " + e.getKeyLocation());
switch (e.getKeyCode()) { switch (e.getKeyCode()) {
//case 328: // keypad //case 328: // keypad
case KeyEvent.VK_UP: case KeyEvent.VK_UP:
@ -362,38 +368,48 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
find = false; find = false;
if (this.guiKeyBoardMode.getNumLock()) { if (this.guiKeyBoardMode.getNumLock()) {
if (thisIsAReapeateKey) { if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.'); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.');
} }
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.'); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, '.');
} else { } else {
if (thisIsAReapeateKey) { if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F);
} }
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x7F);
} }
break; break;
case KeyEvent.VK_TAB: // special case for TAB case KeyEvent.VK_TAB: // special case for TAB
find = false; find = false;
if (thisIsAReapeateKey) { if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09);
} }
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, (char) 0x09);
break; break;
default: default:
find = false; find = false;
if (thisIsAReapeateKey) { if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar()); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar());
} }
operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar()); operatingSystemsetKeyboard(this.guiKeyBoardMode, KeyKeyboard.CHARACTER,
(pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey, e.getKeyChar());
} }
if (find) { if (find) {
if (thisIsAReapeateKey) { if (thisIsAReapeateKey) {
operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (!pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey); operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (!pressed ? KeyStatus.down : KeyStatus.up),
thisIsAReapeateKey);
} }
operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (pressed ? KeyStatus.down : KeyStatus.up), thisIsAReapeateKey); operatingSystemsetKeyboard(this.guiKeyBoardMode, keyInput, (pressed ? KeyStatus.down : KeyStatus.up),
thisIsAReapeateKey);
} }
} }
@Override @Override
public void keyPressed(final KeyEvent e) { public void keyPressed(final KeyEvent e) {
final int internalKeyValue = getUniqueIndex(e); final int internalKeyValue = getUniqueIndex(e);
@ -403,7 +419,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
} }
keyEvent(e, true, index != -1); keyEvent(e, true, index != -1);
} }
@Override @Override
public void keyReleased(final KeyEvent e) { public void keyReleased(final KeyEvent e) {
final int internalKeyValue = getUniqueIndex(e); final int internalKeyValue = getUniqueIndex(e);
@ -413,60 +429,60 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
} }
keyEvent(e, false, false); keyEvent(e, false, false);
} }
@Override @Override
public void keyTyped(final KeyEvent e) { public void keyTyped(final KeyEvent e) {
// not needed with my model ... // not needed with my model ...
//Log.info(" typed " + e.getKeyChar() + " " + e); //LOGGER.info(" typed " + e.getKeyChar() + " " + e);
} }
@Override @Override
public void mouseClicked(final MouseEvent e) { public void mouseClicked(final MouseEvent e) {
// System.out.println(e.getX()); // System.out.println(e.getX());
// System.out.println(e.getY()); // System.out.println(e.getY());
Log.info("Mouse clicked:" + e.getX() + " " + e.getY()); LOGGER.info("Mouse clicked:" + e.getX() + " " + e.getY());
} }
@Override @Override
public void mouseDragged(final MouseEvent e) { public void mouseDragged(final MouseEvent e) {
//Log.error("mouse drag ... " + e); //LOGGER.error("mouse drag ... " + e);
mouseMoved(e); mouseMoved(e);
} }
@Override @Override
public void mouseEntered(final MouseEvent e) { public void mouseEntered(final MouseEvent e) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
//Log.info("Mouse entered:" + e.getX() + " " + e.getY()); //LOGGER.info("Mouse entered:" + e.getX() + " " + e.getY());
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY()); this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.enter, 0, this.cursorPos); operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.enter, 0, this.cursorPos);
} }
@Override @Override
public void mouseExited(final MouseEvent e) { public void mouseExited(final MouseEvent e) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
//Log.info("Mouse exited:" + e.getX() + " " + e.getY()); //LOGGER.info("Mouse exited:" + e.getX() + " " + e.getY());
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY()); this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.leave, 0, this.cursorPos); operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.leave, 0, this.cursorPos);
//this.frame.mouseMove(e, 200, 200); //this.frame.mouseMove(e, 200, 200);
} }
@Override @Override
public void mouseMoved(final MouseEvent e) { public void mouseMoved(final MouseEvent e) {
Log.verbose("Mouse moved:" + e.getX() + " " + e.getY() + " " + e); LOGGER.trace("Mouse moved:" + e.getX() + " " + e.getY() + " " + e);
if (this.robot != null) { if (this.robot != null) {
final Rectangle bounds = this.frame.getBounds(); final Rectangle bounds = this.frame.getBounds();
//Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize); //LOGGER.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize);
final float refPosX = bounds.x + bounds.width / 2.0f; final float refPosX = bounds.x + bounds.width / 2.0f;
final float refPosY = bounds.y + bounds.height / 2.0f; final float refPosY = bounds.y + bounds.height / 2.0f;
if (e.getXOnScreen() == (int) refPosX && e.getYOnScreen() == (int) refPosY) { if (e.getXOnScreen() == (int) refPosX && e.getYOnScreen() == (int) refPosY) {
this.cursorPos = Vector2f.ZERO; this.cursorPos = Vector2f.ZERO;
return; return;
} }
//Log.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize); //LOGGER.error(" " + bounds + " windows=" + windowsSize + " deco= " + decoratedWindowsSize);
this.cursorPos = new Vector2f(-(e.getXOnScreen() - refPosX), (e.getYOnScreen() - refPosY)); this.cursorPos = new Vector2f(-(e.getXOnScreen() - refPosX), (e.getYOnScreen() - refPosY));
//this.cursorPos = new Vector2f(-(e.getXOnScreen() - refPosX), refPosY); //this.cursorPos = new Vector2f(-(e.getXOnScreen() - refPosX), refPosY);
this.robot.mouseMove((int) refPosX, (int) refPosY); this.robot.mouseMove((int) refPosX, (int) refPosY);
Log.info("delta moved:" + this.cursorPos); LOGGER.info("delta moved:" + this.cursorPos);
} else { } else {
// TODO use real size ... !!!! // TODO use real size ... !!!!
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() + (this.cursorSize.y() - e.getY())); this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() + (this.cursorSize.y() - e.getY()));
@ -475,7 +491,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
boolean findOne = false; boolean findOne = false;
for (int iii = 0; iii < ContextLWJGLAWT.MAX_MANAGE_INPUT; iii++) { for (int iii = 0; iii < ContextLWJGLAWT.MAX_MANAGE_INPUT; iii++) {
if (this.inputIsPressed[iii]) { if (this.inputIsPressed[iii]) {
//Log.debug("X11 event: bt=" << iii << " " << event.type << " = \"MotionNotify\" (" << m_cursorEventX << "," << m_cursorEventY << ")"); //LOGGER.debug("X11 event: bt=" << iii << " " << event.type << " = \"MotionNotify\" (" << m_cursorEventX << "," << m_cursorEventY << ")");
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, iii, this.cursorPos); operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, iii, this.cursorPos);
findOne = true; findOne = true;
} }
@ -485,10 +501,10 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, 0, this.cursorPos); operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.move, 0, this.cursorPos);
} }
} }
@Override @Override
public void mousePressed(final MouseEvent e) { public void mousePressed(final MouseEvent e) {
Log.info("Mouse pressed:" + e.getX() + " " + e.getY()); LOGGER.info("Mouse pressed:" + e.getX() + " " + e.getY());
final int button = e.getButton(); final int button = e.getButton();
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY()); this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
if (button < ContextLWJGLAWT.MAX_MANAGE_INPUT) { if (button < ContextLWJGLAWT.MAX_MANAGE_INPUT) {
@ -496,11 +512,11 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
} }
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.down, button, this.cursorPos); operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.down, button, this.cursorPos);
} }
@Override @Override
public void mouseReleased(final MouseEvent e) { public void mouseReleased(final MouseEvent e) {
//Log.info("Mouse release:" + e.getX() + " " + e.getY()); //LOGGER.info("Mouse release:" + e.getX() + " " + e.getY());
// Log.info("mouse value: GLFW_RELEASE" + action + " bt=" + button); // LOGGER.info("mouse value: GLFW_RELEASE" + action + " bt=" + button);
final int button = e.getButton(); final int button = e.getButton();
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY()); this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
if (button < ContextLWJGLAWT.MAX_MANAGE_INPUT) { if (button < ContextLWJGLAWT.MAX_MANAGE_INPUT) {
@ -508,10 +524,10 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
} }
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, button, this.cursorPos); operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, button, this.cursorPos);
} }
@Override @Override
public void mouseWheelMoved(final MouseWheelEvent e) { public void mouseWheelMoved(final MouseWheelEvent e) {
//Log.info("wheel_event : " + e); //LOGGER.info("wheel_event : " + e);
this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY()); this.cursorPos = new Vector2f(e.getX(), this.decoratedWindowsSize.y() - e.getY());
if (e.getWheelRotation() < 0) { if (e.getWheelRotation() < 0) {
this.inputIsPressed[5] = true; this.inputIsPressed[5] = true;
@ -525,7 +541,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, 4, this.cursorPos); operatingSystemSetInput(this.guiKeyBoardMode, KeyType.mouse, KeyStatus.up, 4, this.cursorPos);
} }
} }
@Override @Override
public int run() { public int run() {
final Runnable renderLoop = new Runnable() { final Runnable renderLoop = new Runnable() {
@ -545,7 +561,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
} }
}; };
SwingUtilities.invokeLater(renderLoop); SwingUtilities.invokeLater(renderLoop);
// while (canvas != null && canvas.isValid()) { // while (canvas != null && canvas.isValid()) {
// canvas.render(); // canvas.render();
// try { // try {
@ -555,7 +571,7 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
// e.printStackTrace(); // e.printStackTrace();
// } // }
// } // }
// Run the rendering loop until the user has attempted to close // Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key. // the window or has pressed the ESCAPE key.
// while ( !glfwWindowShouldClose(window) ) { // while ( !glfwWindowShouldClose(window) ) {
@ -597,11 +613,11 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
//System.exit(0); //System.exit(0);
return 0; return 0;
} }
public void setDrawer(final DisplayManagerDraw drawer) { public void setDrawer(final DisplayManagerDraw drawer) {
this.drawer = drawer; this.drawer = drawer;
} }
@Override @Override
public void setFullScreenThreadGUI(final boolean status) { public void setFullScreenThreadGUI(final boolean status) {
super.setFullScreen(status); super.setFullScreen(status);
@ -613,24 +629,24 @@ public class ContextLWJGLAWT extends GaleContext implements MouseListener, Mouse
this.frame.setUndecorated(false); this.frame.setUndecorated(false);
} }
} }
@Override @Override
public void setIconThreadGUI(final Uri inputFile) { public void setIconThreadGUI(final Uri inputFile) {
} }
/****************************************************************************************/ /****************************************************************************************/
@Override @Override
public void setTitleThreadGUI(final String title) { public void setTitleThreadGUI(final String title) {
this.frame.setTitle(title); this.frame.setTitle(title);
} }
private void showCursor() { private void showCursor() {
this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
} }
public void unInit() { public void unInit() {
} }
} }

View File

@ -4,40 +4,42 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Vector; import java.util.Vector;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageSystem { public class MessageSystem {
static final Logger LOGGER = LoggerFactory.getLogger(MessageSystem.class);
private final Vector<ActionToDoInAsyncLoop> data = new Vector<>(); private final Vector<ActionToDoInAsyncLoop> data = new Vector<>();
private final Map<String, ActionToDoInAsyncLoop> dataSingle = new HashMap<>(); private final Map<String, ActionToDoInAsyncLoop> dataSingle = new HashMap<>();
public synchronized void addElement(final ActionToDoInAsyncLoop data2) { public synchronized void addElement(final ActionToDoInAsyncLoop data2) {
this.data.addElement(data2); this.data.addElement(data2);
notifyAll(); notifyAll();
} }
public synchronized void addElement(final String uniqueID, final ActionToDoInAsyncLoop data2) { public synchronized void addElement(final String uniqueID, final ActionToDoInAsyncLoop data2) {
this.dataSingle.put(uniqueID, data2); this.dataSingle.put(uniqueID, data2);
notifyAll(); notifyAll();
} }
protected synchronized ActionToDoInAsyncLoop getElementSingle() { protected synchronized ActionToDoInAsyncLoop getElementSingle() {
//Log.warning("+++++++++++++++++++++++++++++++++ getElement()"); //LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement()");
final Map.Entry<String, ActionToDoInAsyncLoop> entry = this.dataSingle.entrySet().iterator().next(); final Map.Entry<String, ActionToDoInAsyncLoop> entry = this.dataSingle.entrySet().iterator().next();
final String key = entry.getKey(); final String key = entry.getKey();
final ActionToDoInAsyncLoop message = entry.getValue(); final ActionToDoInAsyncLoop message = entry.getValue();
this.dataSingle.remove(key); this.dataSingle.remove(key);
//Log.warning("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message); //LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message);
return message; return message;
} }
protected synchronized ActionToDoInAsyncLoop getElementVector() { protected synchronized ActionToDoInAsyncLoop getElementVector() {
//Log.warning("+++++++++++++++++++++++++++++++++ getElement()"); //LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement()");
final ActionToDoInAsyncLoop message = this.data.firstElement(); final ActionToDoInAsyncLoop message = this.data.firstElement();
this.data.removeElement(message); this.data.removeElement(message);
//Log.warning("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message); //LOGGER.warn("+++++++++++++++++++++++++++++++++ getElement() ===> done " + message);
return message; return message;
} }
public synchronized ActionToDoInAsyncLoop getElementWait() { public synchronized ActionToDoInAsyncLoop getElementWait() {
if (this.data.isEmpty() && this.dataSingle.isEmpty()) { if (this.data.isEmpty() && this.dataSingle.isEmpty()) {
try { try {
@ -56,11 +58,11 @@ public class MessageSystem {
} }
return null; return null;
} }
public synchronized int getSize() { public synchronized int getSize() {
Log.verbose("------------------------------------------------------------"); LOGGER.trace("------------------------------------------------------------");
Log.verbose("-- nb message: {} + {}", this.data.size(), this.dataSingle.size()); LOGGER.trace("-- nb message: {} + {}", this.data.size(), this.dataSingle.size());
Log.verbose("------------------------------------------------------------"); LOGGER.trace("------------------------------------------------------------");
return this.data.size() + this.dataSingle.size(); return this.data.size() + this.dataSingle.size();
} }
} }

View File

@ -4,29 +4,31 @@ import java.time.Clock;
import org.atriasoft.etk.ThreadAbstract; import org.atriasoft.etk.ThreadAbstract;
import org.atriasoft.gale.GaleApplication; import org.atriasoft.gale.GaleApplication;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PeriodicThread extends ThreadAbstract { public class PeriodicThread extends ThreadAbstract {
static final Logger LOGGER = LoggerFactory.getLogger(PeriodicThread.class);
private final GaleContext context; private final GaleContext context;
public PeriodicThread(final GaleContext context) { public PeriodicThread(final GaleContext context) {
super("GaleAsync"); super("GaleAsync");
this.context = context; this.context = context;
} }
@Override @Override
protected void birth() { protected void birth() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
protected void death() { protected void death() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
protected void runPeriodic() { protected void runPeriodic() {
Log.verbose("----------------------------- [START] -----------------------------------"); LOGGER.trace("----------------------------- [START] -----------------------------------");
try { try {
Thread.sleep(100); Thread.sleep(100);
} catch (final InterruptedException e) { } catch (final InterruptedException e) {
@ -37,15 +39,15 @@ public class PeriodicThread extends ThreadAbstract {
// Keep global clock to process events // Keep global clock to process events
final Clock clock = Clock.systemUTC(); final Clock clock = Clock.systemUTC();
final long time = System.nanoTime(); final long time = System.nanoTime();
///synchronized (this.context) { ///synchronized (this.context) {
this.context.processEventsAsync(clock, time); this.context.processEventsAsync(clock, time);
// call all the application for periodic request (the application manage multiple instance )... // call all the application for periodic request (the application manage multiple instance )...
final GaleApplication appl = this.context.getApplication(); final GaleApplication appl = this.context.getApplication();
//Log.verbose("Call application : " + appl); //LOGGER.trace("Call application : " + appl);
if (appl != null) { if (appl != null) {
appl.onPeriod(clock, time); appl.onPeriod(clock, time);
} }
Log.verbose("----------------------------- [ END ] -----------------------------------"); LOGGER.trace("----------------------------- [ END ] -----------------------------------");
} }
} }

View File

@ -1,76 +0,0 @@
package org.atriasoft.gale.internal;
import org.atriasoft.reggol.LogLevel;
import org.atriasoft.reggol.Logger;
public class Log {
private static final boolean FORCE_ALL = false;
private static final String LIB_NAME = "gale";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_CRITICAL = Logger.getNeedPrint(LIB_NAME, LogLevel.CRITICAL);
private static final boolean PRINT_ERROR = Logger.getNeedPrint(LIB_NAME, LogLevel.ERROR);
private static final boolean PRINT_WARNING = Logger.getNeedPrint(LIB_NAME, LogLevel.WARNING);
private static final boolean PRINT_INFO = Logger.getNeedPrint(LIB_NAME, LogLevel.INFO);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private static final boolean PRINT_VERBOSE = Logger.getNeedPrint(LIB_NAME, LogLevel.VERBOSE);
private static final boolean PRINT_TODO = Logger.getNeedPrint(LIB_NAME, LogLevel.TODO);
private static final boolean PRINT_PRINT = Logger.getNeedPrint(LIB_NAME, LogLevel.PRINT);
public static void critical(final Exception e, final String data) {
e.printStackTrace();
if (PRINT_CRITICAL || FORCE_ALL) {
Logger.critical(LIB_NAME_DRAW, data + " : " + e.getMessage());
}
}
public static void critical(final String data, final Object... objects) {
if (PRINT_CRITICAL || FORCE_ALL) {
Logger.critical(LIB_NAME_DRAW, data, objects);
}
}
public static void debug(final String data, final Object... objects) {
if (PRINT_DEBUG || FORCE_ALL) {
Logger.debug(LIB_NAME_DRAW, data, objects);
}
}
public static void error(final String data, final Object... objects) {
if (PRINT_ERROR || FORCE_ALL) {
Logger.error(LIB_NAME_DRAW, data, objects);
}
}
public static void info(final String data, final Object... objects) {
if (PRINT_INFO || FORCE_ALL) {
Logger.info(LIB_NAME_DRAW, data, objects);
}
}
public static void print(final String data, final Object... objects) {
if (PRINT_PRINT || FORCE_ALL) {
Logger.print(LIB_NAME_DRAW, data, objects);
}
}
public static void todo(final String data, final Object... objects) {
if (PRINT_TODO || FORCE_ALL) {
Logger.todo(LIB_NAME_DRAW, data, objects);
}
}
public static void verbose(final String data, final Object... objects) {
if (PRINT_VERBOSE || FORCE_ALL) {
Logger.verbose(LIB_NAME_DRAW, data, objects);
}
}
public static void warning(final String data, final Object... objects) {
if (PRINT_WARNING || FORCE_ALL) {
Logger.warning(LIB_NAME_DRAW, data, objects);
}
}
private Log() {}
}

View File

@ -2,25 +2,27 @@ package org.atriasoft.gale.resource;
import org.atriasoft.etk.Uri; import org.atriasoft.etk.Uri;
import org.atriasoft.gale.context.GaleContext; import org.atriasoft.gale.context.GaleContext;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Resource { public abstract class Resource {
static final Logger LOGGER = LoggerFactory.getLogger(Resource.class);
protected static final String NO_NAME_RESOURCE = "---"; protected static final String NO_NAME_RESOURCE = "---";
protected static final int MAXRESOURCELEVEL = 5; protected static final int MAXRESOURCELEVEL = 5;
private static int idGenerated = 10; private static int idGenerated = 10;
/** /**
* Get the current resource Manager * Get the current resource Manager
*/ */
protected static ResourceManager getManager() { protected static ResourceManager getManager() {
return GaleContext.getContext().getResourcesManager(); return GaleContext.getContext().getResourcesManager();
} }
protected long uid = -1; //!< unique ID definition protected long uid = -1; //!< unique ID definition
protected int count = 1; 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 String name = NO_NAME_RESOURCE; //!< name of the resource ...
/** /**
* generic protected contructor (use factory to create this class) * generic protected contructor (use factory to create this class)
*/ */
@ -28,7 +30,7 @@ public abstract class Resource {
this.uid = idGenerated++; this.uid = idGenerated++;
getManager().localAdd(this); getManager().localAdd(this);
} }
protected Resource(final String name) { protected Resource(final String name) {
if (name == null) { if (name == null) {
this.name = "---"; this.name = "---";
@ -37,7 +39,7 @@ public abstract class Resource {
} }
getManager().localAdd(this); getManager().localAdd(this);
} }
protected Resource(final Uri uri) { protected Resource(final Uri uri) {
if (uri == null) { if (uri == null) {
this.name = "---"; this.name = "---";
@ -46,17 +48,17 @@ public abstract class Resource {
} }
getManager().localAdd(this); getManager().localAdd(this);
} }
public abstract void cleanUp(); public abstract void cleanUp();
public int getCount() { public int getCount() {
return this.count; return this.count;
} }
public long getId() { public long getId() {
return this.uid; return this.uid;
} }
/** /**
* get the resource name * get the resource name
* @return The requested name * @return The requested name
@ -64,7 +66,7 @@ public abstract class Resource {
public String getName() { public String getName() {
return this.name; return this.name;
} }
/** /**
* Get the current resource level; * Get the current resource level;
* @return value in [0..5] * @return value in [0..5]
@ -72,40 +74,40 @@ public abstract class Resource {
public int getResourceLevel() { public int getResourceLevel() {
return this.resourceLevel; return this.resourceLevel;
} }
public void keep() { public void keep() {
this.count++; this.count++;
} }
public void release() { public void release() {
this.count--; this.count--;
if (this.count == 0) { if (this.count == 0) {
} }
} }
/** /**
* User request the reload of all resources (usefull when the file depend on DATA:GUI:xxx ... * User request the reload of all resources (usefull when the file depend on DATA:GUI:xxx ...
*/ */
public void reload() { public void reload() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)"); LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
} }
/** /**
* The current OpenGl context is removing ==> remove yout own system data * The current OpenGl context is removing ==> remove yout own system data
*/ */
public void removeContext() { public void removeContext() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)"); LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
} }
/** /**
* The notification of the Context removing is too late, we have no more acces on the OpenGl context (thank you Android). * 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 * Just update your internal state
*/ */
public void removeContextToLate() { public void removeContextToLate() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)"); LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
} }
/** /**
* get the resource name * get the resource name
* @param name The name to set. * @param name The name to set.
@ -113,7 +115,7 @@ public abstract class Resource {
public void setName(final String name) { public void setName(final String name) {
this.name = name; this.name = name;
} }
/** /**
* Call when need to send data on the harware (openGL) * Call when need to send data on the harware (openGL)
* @note This is done asynchronously with the create of the Resource. * @note This is done asynchronously with the create of the Resource.
@ -121,7 +123,7 @@ public abstract class Resource {
* @return false The context is not updated * @return false The context is not updated
*/ */
public boolean updateContext() { public boolean updateContext() {
Log.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)"); LOGGER.debug("Not set for : [" + getId() + "]" + getName() + " loaded ??? time(s)");
return true; return true;
} }
} }

View File

@ -9,27 +9,31 @@ import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Matrix4f; import org.atriasoft.etk.math.Matrix4f;
import org.atriasoft.etk.math.Vector3f; import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceColored3DObject extends Resource { public class ResourceColored3DObject extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceColored3DObject.class);
public static ResourceColored3DObject create() { public static ResourceColored3DObject create() {
final ResourceColored3DObject resource = new ResourceColored3DObject(); final ResourceColored3DObject resource = new ResourceColored3DObject();
getManager().localAdd(resource); getManager().localAdd(resource);
return resource; return resource;
} }
private final ResourceProgram program; private final ResourceProgram program;
private int oGLPosition; private int oGLPosition;
private int oGLColor; private int oGLColor;
private int oGLMatrixTransformation; private int oGLMatrixTransformation;
private int oGLMatrixProjection; private int oGLMatrixProjection;
private int oGLMatrixView; private int oGLMatrixView;
protected ResourceColored3DObject() { protected ResourceColored3DObject() {
// get the shader resource : // get the shader resource :
this.oGLPosition = 0; this.oGLPosition = 0;
this.program = ResourceProgram.create(new Uri("DATA", "simple3D.vert", "gale"), new Uri("DATA", "simple3D.frag", "gale")); this.program = ResourceProgram.create(new Uri("DATA", "simple3D.vert", "gale"),
new Uri("DATA", "simple3D.frag", "gale"));
if (this.program != null) { if (this.program != null) {
this.oGLMatrixTransformation = this.program.getUniform("in_matrixTransformation"); this.oGLMatrixTransformation = this.program.getUniform("in_matrixTransformation");
this.oGLMatrixProjection = this.program.getUniform("in_matrixProjection"); this.oGLMatrixProjection = this.program.getUniform("in_matrixProjection");
@ -38,13 +42,13 @@ public class ResourceColored3DObject extends Resource {
this.oGLColor = this.program.getUniform("in_colors"); this.oGLColor = this.program.getUniform("in_colors");
} }
} }
@Override @Override
public void cleanUp() { public void cleanUp() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
private float[] convertInFloat(final List<Vector3f> data) { private float[] convertInFloat(final List<Vector3f> data) {
final float[] out = new float[data.size() * 3]; final float[] out = new float[data.size() * 3];
for (int iii = 0; iii < data.size(); iii++) { for (int iii = 0; iii < data.size(); iii++) {
@ -54,13 +58,17 @@ public class ResourceColored3DObject extends Resource {
} }
return out; return out;
} }
public void draw(final List<Vector3f> vertices, final Color color, final boolean updateDepthBuffer, final boolean depthtest) { public void draw(
final List<Vector3f> vertices,
final Color color,
final boolean updateDepthBuffer,
final boolean depthtest) {
if (vertices.size() <= 0) { if (vertices.size() <= 0) {
return; return;
} }
if (this.program == null) { if (this.program == null) {
Log.error("No shader ..."); LOGGER.error("No shader ...");
return; return;
} }
if (depthtest) { if (depthtest) {
@ -69,7 +77,7 @@ public class ResourceColored3DObject extends Resource {
OpenGL.setDeathMask(false); OpenGL.setDeathMask(false);
} }
} }
//Log.debug(" display " << this.coord.size() << " elements" ); //LOGGER.debug(" display " << this.coord.size() << " elements" );
this.program.use(); this.program.use();
final Matrix4f projectionMatrix = OpenGL.getMatrix(); final Matrix4f projectionMatrix = OpenGL.getMatrix();
final Matrix4f viewMatrix = OpenGL.getCameraMatrix(); final Matrix4f viewMatrix = OpenGL.getCameraMatrix();
@ -101,13 +109,18 @@ public class ResourceColored3DObject extends Resource {
OpenGL.disable(OpenGL.Flag.flag_depthTest); OpenGL.disable(OpenGL.Flag.flag_depthTest);
} }
} }
public void draw(final List<Vector3f> vertices, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) { public void draw(
final List<Vector3f> vertices,
final Color color,
final Matrix4f transformationMatrix,
final boolean updateDepthBuffer,
final boolean depthtest) {
if (vertices.size() <= 0) { if (vertices.size() <= 0) {
return; return;
} }
if (this.program == null) { if (this.program == null) {
Log.error("No shader ..."); LOGGER.error("No shader ...");
return; return;
} }
if (depthtest) { if (depthtest) {
@ -116,7 +129,7 @@ public class ResourceColored3DObject extends Resource {
OpenGL.setDeathMask(false); OpenGL.setDeathMask(false);
} }
} }
//Log.debug(" display " << this.coord.size() << " elements" ); //LOGGER.debug(" display " << this.coord.size() << " elements" );
this.program.use(); this.program.use();
// set Matrix: translation/positionMatrix // set Matrix: translation/positionMatrix
final Matrix4f projectionMatrix = OpenGL.getMatrix(); final Matrix4f projectionMatrix = OpenGL.getMatrix();
@ -128,7 +141,7 @@ public class ResourceColored3DObject extends Resource {
final FloatBuffer buffer = storeDataInFloatBuffer(convertInFloat(vertices)); final FloatBuffer buffer = storeDataInFloatBuffer(convertInFloat(vertices));
this.program.sendAttribute(this.oGLPosition, 3, buffer, 3); this.program.sendAttribute(this.oGLPosition, 3, buffer, 3);
// color : // color :
//Log.info("color= " + color + " " + this.oGLPosition); //LOGGER.info("color= " + color + " " + this.oGLPosition);
this.program.uniformColor(this.oGLColor, color); this.program.uniformColor(this.oGLColor, color);
if (color.a() < 1.0f) { if (color.a() < 1.0f) {
OpenGL.enable(OpenGL.Flag.flag_blend); OpenGL.enable(OpenGL.Flag.flag_blend);
@ -146,29 +159,35 @@ public class ResourceColored3DObject extends Resource {
OpenGL.disable(OpenGL.Flag.flag_depthTest); OpenGL.disable(OpenGL.Flag.flag_depthTest);
} }
} }
public void drawCapsule(final float radius, final float size, int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) { public void drawCapsule(
final float radius,
final float size,
int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>(); final List<Vector3f> tmpVertices = new ArrayList<>();
lats = lats / 2 * 2; lats = lats / 2 * 2;
// center to border (TOP) // center to border (TOP)
float offset = size * 0.5f; float offset = size * 0.5f;
for (int iii = lats / 2 + 1; iii <= lats; ++iii) { for (int iii = lats / 2 + 1; iii <= lats; ++iii) {
final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats); final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats);
final float z0 = radius * (float) Math.sin(lat0); final float z0 = radius * (float) Math.sin(lat0);
final float zr0 = radius * (float) Math.cos(lat0); final float zr0 = radius * (float) Math.cos(lat0);
final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats); final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats);
final float z1 = radius * (float) Math.sin(lat1); final float z1 = radius * (float) Math.sin(lat1);
final float zr1 = radius * (float) Math.cos(lat1); final float zr1 = radius * (float) Math.cos(lat1);
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
float x = (float) Math.cos(lng); float x = (float) Math.cos(lng);
float y = (float) Math.sin(lng); float y = (float) Math.sin(lng);
final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1 + offset); final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1 + offset);
final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0 + offset); final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0 + offset);
lng = 2 * (float) Math.PI * (jjj) / longs; lng = 2 * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng); x = (float) Math.cos(lng);
y = (float) Math.sin(lng); y = (float) Math.sin(lng);
@ -177,7 +196,7 @@ public class ResourceColored3DObject extends Resource {
tmpVertices.add(v1); tmpVertices.add(v1);
tmpVertices.add(v2); tmpVertices.add(v2);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v1); tmpVertices.add(v1);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v4); tmpVertices.add(v4);
@ -186,24 +205,24 @@ public class ResourceColored3DObject extends Resource {
// Cylinder // Cylinder
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * 0.5f; final float z = size * 0.5f;
float x = (float) Math.cos(lng) * radius; float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius; float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z); final Vector3f v2 = new Vector3f(x, y, z);
final Vector3f v2b = new Vector3f(x, y, -z); final Vector3f v2b = new Vector3f(x, y, -z);
lng = 2.0f * (float) Math.PI * (jjj) / longs; lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius; x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius; y = (float) Math.sin(lng) * radius;
final Vector3f v3 = new Vector3f(x, y, z); final Vector3f v3 = new Vector3f(x, y, z);
final Vector3f v3b = new Vector3f(x, y, -z); final Vector3f v3b = new Vector3f(x, y, -z);
tmpVertices.add(v2); tmpVertices.add(v2);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v3b); tmpVertices.add(v3b);
tmpVertices.add(v2); tmpVertices.add(v2);
tmpVertices.add(v3b); tmpVertices.add(v3b);
tmpVertices.add(v2b); tmpVertices.add(v2b);
@ -214,18 +233,18 @@ public class ResourceColored3DObject extends Resource {
final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats); final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats);
final float z0 = radius * (float) Math.sin(lat0); final float z0 = radius * (float) Math.sin(lat0);
final float zr0 = radius * (float) Math.cos(lat0); final float zr0 = radius * (float) Math.cos(lat0);
final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats); final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats);
final float z1 = radius * (float) Math.sin(lat1); final float z1 = radius * (float) Math.sin(lat1);
final float zr1 = radius * (float) Math.cos(lat1); final float zr1 = radius * (float) Math.cos(lat1);
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
float x = (float) Math.cos(lng); float x = (float) Math.cos(lng);
float y = (float) Math.sin(lng); float y = (float) Math.sin(lng);
final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1 + offset); final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1 + offset);
final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0 + offset); final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0 + offset);
lng = 2 * (float) Math.PI * (jjj) / longs; lng = 2 * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng); x = (float) Math.cos(lng);
y = (float) Math.sin(lng); y = (float) Math.sin(lng);
@ -234,7 +253,7 @@ public class ResourceColored3DObject extends Resource {
tmpVertices.add(v1); tmpVertices.add(v1);
tmpVertices.add(v2); tmpVertices.add(v2);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v1); tmpVertices.add(v1);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v4); tmpVertices.add(v4);
@ -242,18 +261,24 @@ public class ResourceColored3DObject extends Resource {
} }
draw(tmpVertices, tmpColor, transformationMatrix, true, true); draw(tmpVertices, tmpColor, transformationMatrix, true, true);
} }
public void drawCone(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) { public void drawCone(
final float radius,
final float size,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>(); final List<Vector3f> tmpVertices = new ArrayList<>();
// center to border (TOP) // center to border (TOP)
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, -size / 2); final Vector3f v1 = new Vector3f(0.0f, 0.0f, -size / 2);
float x = (float) Math.cos(lng) * radius; float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius; float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, size / 2); final Vector3f v2 = new Vector3f(x, y, size / 2);
lng = 2.0f * (float) Math.PI * (jjj) / longs; lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius; x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius; y = (float) Math.sin(lng) * radius;
@ -265,13 +290,13 @@ public class ResourceColored3DObject extends Resource {
// center to border (BUTTOM) // center to border (BUTTOM)
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, size / 2); final Vector3f v1 = new Vector3f(0.0f, 0.0f, size / 2);
float x = (float) Math.cos(lng) * radius; float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius; float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, size / 2); final Vector3f v2 = new Vector3f(x, y, size / 2);
lng = 2.0f * (float) Math.PI * (jjj) / longs; lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius; x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius; y = (float) Math.sin(lng) * radius;
@ -282,67 +307,86 @@ public class ResourceColored3DObject extends Resource {
} }
draw(tmpVertices, tmpColor, transformationMatrix, true, true); draw(tmpVertices, tmpColor, transformationMatrix, true, true);
} }
public void drawCubeLine(final Vector3f min, final Vector3f max, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) { public void drawCubeLine(
final Vector3f min,
final Vector3f max,
final Color color,
final Matrix4f transformationMatrix,
final boolean updateDepthBuffer,
final boolean depthtest) {
final List<Vector3f> vertices = new ArrayList<>(); final List<Vector3f> vertices = new ArrayList<>();
vertices.add(new Vector3f(min.x(), min.y(), min.z())); vertices.add(new Vector3f(min.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), min.z())); vertices.add(new Vector3f(max.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), min.z())); vertices.add(new Vector3f(max.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), max.z())); vertices.add(new Vector3f(max.x(), min.y(), max.z()));
vertices.add(new Vector3f(max.x(), min.y(), max.z())); vertices.add(new Vector3f(max.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), max.z())); vertices.add(new Vector3f(min.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), max.z())); vertices.add(new Vector3f(min.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), min.z())); vertices.add(new Vector3f(min.x(), min.y(), min.z()));
vertices.add(new Vector3f(min.x(), max.y(), min.z())); vertices.add(new Vector3f(min.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), min.z())); vertices.add(new Vector3f(max.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), min.z())); vertices.add(new Vector3f(max.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), max.z())); vertices.add(new Vector3f(max.x(), max.y(), max.z()));
vertices.add(new Vector3f(max.x(), max.y(), max.z())); vertices.add(new Vector3f(max.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), max.z())); vertices.add(new Vector3f(min.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), max.z())); vertices.add(new Vector3f(min.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), min.z())); vertices.add(new Vector3f(min.x(), max.y(), min.z()));
vertices.add(new Vector3f(min.x(), min.y(), min.z())); vertices.add(new Vector3f(min.x(), min.y(), min.z()));
vertices.add(new Vector3f(min.x(), max.y(), min.z())); vertices.add(new Vector3f(min.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), min.z())); vertices.add(new Vector3f(max.x(), min.y(), min.z()));
vertices.add(new Vector3f(max.x(), max.y(), min.z())); vertices.add(new Vector3f(max.x(), max.y(), min.z()));
vertices.add(new Vector3f(max.x(), min.y(), max.z())); vertices.add(new Vector3f(max.x(), min.y(), max.z()));
vertices.add(new Vector3f(max.x(), max.y(), max.z())); vertices.add(new Vector3f(max.x(), max.y(), max.z()));
vertices.add(new Vector3f(min.x(), min.y(), max.z())); vertices.add(new Vector3f(min.x(), min.y(), max.z()));
vertices.add(new Vector3f(min.x(), max.y(), max.z())); vertices.add(new Vector3f(min.x(), max.y(), max.z()));
drawLine(vertices, color, transformationMatrix, updateDepthBuffer, depthtest); drawLine(vertices, color, transformationMatrix, updateDepthBuffer, depthtest);
} }
public void drawCylinder(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) { public void drawCylinder(
final float radius,
final float size,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
drawCylinder(radius, size, lats, longs, transformationMatrix, tmpColor, true, true); drawCylinder(radius, size, lats, longs, transformationMatrix, tmpColor, true, true);
} }
public void drawCylinder(final float radius, final float size, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor, final boolean updateDepthBuffer, public void drawCylinder(
final float radius,
final float size,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor,
final boolean updateDepthBuffer,
final boolean depthtest) { final boolean depthtest) {
final List<Vector3f> tmpVertices = new ArrayList<>(); final List<Vector3f> tmpVertices = new ArrayList<>();
// center to border (TOP) // center to border (TOP)
// center to border (TOP) // center to border (TOP)
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * 0.5f; final float z = size * 0.5f;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, z); final Vector3f v1 = new Vector3f(0.0f, 0.0f, z);
float x = (float) Math.cos(lng) * radius; float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius; float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z); final Vector3f v2 = new Vector3f(x, y, z);
lng = 2.0f * (float) Math.PI * (jjj) / longs; lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius; x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius; y = (float) Math.sin(lng) * radius;
@ -354,24 +398,24 @@ public class ResourceColored3DObject extends Resource {
// Cylinder // Cylinder
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * 0.5f; final float z = size * 0.5f;
float x = (float) Math.cos(lng) * radius; float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius; float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z); final Vector3f v2 = new Vector3f(x, y, z);
final Vector3f v2b = new Vector3f(x, y, -z); final Vector3f v2b = new Vector3f(x, y, -z);
lng = 2.0f * (float) Math.PI * (jjj) / longs; lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius; x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius; y = (float) Math.sin(lng) * radius;
final Vector3f v3 = new Vector3f(x, y, z); final Vector3f v3 = new Vector3f(x, y, z);
final Vector3f v3b = new Vector3f(x, y, -z); final Vector3f v3b = new Vector3f(x, y, -z);
tmpVertices.add(v2); tmpVertices.add(v2);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v3b); tmpVertices.add(v3b);
tmpVertices.add(v2); tmpVertices.add(v2);
tmpVertices.add(v3b); tmpVertices.add(v3b);
tmpVertices.add(v2b); tmpVertices.add(v2b);
@ -379,14 +423,14 @@ public class ResourceColored3DObject extends Resource {
// center to border (BUTTOM) // center to border (BUTTOM)
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
final float z = size * -0.5f; final float z = size * -0.5f;
final Vector3f v1 = new Vector3f(0.0f, 0.0f, z); final Vector3f v1 = new Vector3f(0.0f, 0.0f, z);
float x = (float) Math.cos(lng) * radius; float x = (float) Math.cos(lng) * radius;
float y = (float) Math.sin(lng) * radius; float y = (float) Math.sin(lng) * radius;
final Vector3f v2 = new Vector3f(x, y, z); final Vector3f v2 = new Vector3f(x, y, z);
lng = 2.0f * (float) Math.PI * (jjj) / longs; lng = 2.0f * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng) * radius; x = (float) Math.cos(lng) * radius;
y = (float) Math.sin(lng) * radius; y = (float) Math.sin(lng) * radius;
@ -397,13 +441,18 @@ public class ResourceColored3DObject extends Resource {
} }
draw(tmpVertices, tmpColor, transformationMatrix, updateDepthBuffer, depthtest); draw(tmpVertices, tmpColor, transformationMatrix, updateDepthBuffer, depthtest);
} }
public void drawLine(final List<Vector3f> vertices, final Color color, final Matrix4f transformationMatrix, final boolean updateDepthBuffer, final boolean depthtest) { public void drawLine(
final List<Vector3f> vertices,
final Color color,
final Matrix4f transformationMatrix,
final boolean updateDepthBuffer,
final boolean depthtest) {
if (vertices.size() <= 0) { if (vertices.size() <= 0) {
return; return;
} }
if (this.program == null) { if (this.program == null) {
Log.error("No shader ..."); LOGGER.error("No shader ...");
return; return;
} }
if (depthtest) { if (depthtest) {
@ -412,7 +461,7 @@ public class ResourceColored3DObject extends Resource {
OpenGL.setDeathMask(false); OpenGL.setDeathMask(false);
} }
} }
//Log.debug(" display " << this.coord.size() << " elements" ); //LOGGER.debug(" display " << this.coord.size() << " elements" );
this.program.use(); this.program.use();
// set Matrix: translation/positionMatrix // set Matrix: translation/positionMatrix
final Matrix4f projectionMatrix = OpenGL.getMatrix(); final Matrix4f projectionMatrix = OpenGL.getMatrix();
@ -441,35 +490,40 @@ public class ResourceColored3DObject extends Resource {
OpenGL.disable(OpenGL.Flag.flag_depthTest); OpenGL.disable(OpenGL.Flag.flag_depthTest);
} }
} }
public void drawSphere(final float radius, final int lats, final int longs, final Matrix4f transformationMatrix, final Color tmpColor) { public void drawSphere(
final float radius,
final int lats,
final int longs,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>(); final List<Vector3f> tmpVertices = new ArrayList<>();
for (int iii = 0; iii <= lats; ++iii) { for (int iii = 0; iii <= lats; ++iii) {
final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats); final float lat0 = (float) Math.PI * (-0.5f + (float) (iii - 1) / lats);
final float z0 = radius * (float) Math.sin(lat0); final float z0 = radius * (float) Math.sin(lat0);
final float zr0 = radius * (float) Math.cos(lat0); final float zr0 = radius * (float) Math.cos(lat0);
final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats); final float lat1 = (float) Math.PI * (-0.5f + (float) (iii) / lats);
final float z1 = radius * (float) Math.sin(lat1); final float z1 = radius * (float) Math.sin(lat1);
final float zr1 = radius * (float) Math.cos(lat1); final float zr1 = radius * (float) Math.cos(lat1);
for (int jjj = 0; jjj < longs; ++jjj) { for (int jjj = 0; jjj < longs; ++jjj) {
float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs; float lng = 2.0f * (float) Math.PI * (jjj - 1) / longs;
float x = (float) Math.cos(lng); float x = (float) Math.cos(lng);
float y = (float) Math.sin(lng); float y = (float) Math.sin(lng);
final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1); final Vector3f v1 = new Vector3f(x * zr1, y * zr1, z1);
final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0); final Vector3f v4 = new Vector3f(x * zr0, y * zr0, z0);
lng = 2 * (float) Math.PI * (jjj) / longs; lng = 2 * (float) Math.PI * (jjj) / longs;
x = (float) Math.cos(lng); x = (float) Math.cos(lng);
y = (float) Math.sin(lng); y = (float) Math.sin(lng);
final Vector3f v2 = new Vector3f(x * zr1, y * zr1, z1); final Vector3f v2 = new Vector3f(x * zr1, y * zr1, z1);
final Vector3f v3 = new Vector3f(x * zr0, y * zr0, z0); final Vector3f v3 = new Vector3f(x * zr0, y * zr0, z0);
tmpVertices.add(v1); tmpVertices.add(v1);
tmpVertices.add(v2); tmpVertices.add(v2);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v1); tmpVertices.add(v1);
tmpVertices.add(v3); tmpVertices.add(v3);
tmpVertices.add(v4); tmpVertices.add(v4);
@ -477,12 +531,15 @@ public class ResourceColored3DObject extends Resource {
} }
draw(tmpVertices, tmpColor, transformationMatrix, true, true); draw(tmpVertices, tmpColor, transformationMatrix, true, true);
} }
public void drawSquare(final Vector3f size, final Matrix4f transformationMatrix, final Color tmpColor) { public void drawSquare(final Vector3f size, final Matrix4f transformationMatrix, final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>(); final List<Vector3f> 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 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,
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()), 6, 7, 2, 3, 7, 6, 2 };
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()), 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()) }; new Vector3f(-size.x(), -size.y(), -size.z()) };
tmpVertices.clear(); tmpVertices.clear();
for (int iii = 0; iii < 36; iii += 3) { for (int iii = 0; iii < 36; iii += 3) {
@ -495,33 +552,47 @@ public class ResourceColored3DObject extends Resource {
} }
draw(tmpVertices, tmpColor, transformationMatrix, true, true); draw(tmpVertices, tmpColor, transformationMatrix, true, true);
} }
public void drawTriangle(final Vector3f p1, final Vector3f p2, final Vector3f p3, final Matrix4f transformationMatrix, final Color tmpColor) { public void drawTriangle(
final Vector3f p1,
final Vector3f p2,
final Vector3f p3,
final Matrix4f transformationMatrix,
final Color tmpColor) {
final List<Vector3f> tmpVertices = new ArrayList<>(); final List<Vector3f> tmpVertices = new ArrayList<>();
tmpVertices.add(p1); tmpVertices.add(p1);
tmpVertices.add(p2); tmpVertices.add(p2);
tmpVertices.add(p3); tmpVertices.add(p3);
//Log.info("display " << tmpVertices.size() << " vertices form " << indice.size()); //LOGGER.info("display " << tmpVertices.size() << " vertices form " << indice.size());
draw(tmpVertices, tmpColor, transformationMatrix, true, true); draw(tmpVertices, tmpColor, transformationMatrix, true, true);
} }
public void drawTriangles(final List<Vector3f> vertex, final List<Integer> indice, final Matrix4f transformationMatrix, final Color tmpColor) { public void drawTriangles(
final List<Vector3f> vertex,
final List<Integer> indice,
final Matrix4f transformationMatrix,
final Color tmpColor) {
drawTriangles(vertex, indice, transformationMatrix, tmpColor, new Vector3f(0.0f, 0.0f, 0.1f)); drawTriangles(vertex, indice, transformationMatrix, tmpColor, new Vector3f(0.0f, 0.0f, 0.1f));
} }
public void drawTriangles(final List<Vector3f> vertex, final List<Integer> indice, final Matrix4f transformationMatrix, final Color tmpColor, final Vector3f offset) { public void drawTriangles(
final List<Vector3f> vertex,
final List<Integer> indice,
final Matrix4f transformationMatrix,
final Color tmpColor,
final Vector3f offset) {
final List<Vector3f> tmpVertices = new ArrayList<>(); final List<Vector3f> tmpVertices = new ArrayList<>();
for (int iii = 0; iii < indice.size() / 3; ++iii) { for (int iii = 0; iii < indice.size() / 3; ++iii) {
tmpVertices.add(vertex.get(indice.get(iii * 3 + 0)).add(offset)); tmpVertices.add(vertex.get(indice.get(iii * 3 + 0)).add(offset));
tmpVertices.add(vertex.get(indice.get(iii * 3 + 1)).add(offset)); tmpVertices.add(vertex.get(indice.get(iii * 3 + 1)).add(offset));
tmpVertices.add(vertex.get(indice.get(iii * 3 + 2)).add(offset)); tmpVertices.add(vertex.get(indice.get(iii * 3 + 2)).add(offset));
//Log.info(" indices " << indice[iii*3 + 0] << " " << indice[iii*3 + 1] << " " << indice[iii*3 + 2]); //LOGGER.info(" indices " << indice[iii*3 + 0] << " " << indice[iii*3 + 1] << " " << indice[iii*3 + 2]);
//Log.info(" triangle " << vertex[indice[iii*3 + 0]] << " " << vertex[indice[iii*3 + 1]] << " " << vertex[indice[iii*3 + 2]]); //LOGGER.info(" triangle " << vertex[indice[iii*3 + 0]] << " " << vertex[indice[iii*3 + 1]] << " " << vertex[indice[iii*3 + 2]]);
} }
//Log.info("display " << tmpVertices.size() << " vertices form " << indice.size()); //LOGGER.info("display " << tmpVertices.size() << " vertices form " << indice.size());
draw(tmpVertices, tmpColor, transformationMatrix, true, true); draw(tmpVertices, tmpColor, transformationMatrix, true, true);
} }
private FloatBuffer storeDataInFloatBuffer(final float[] data) { private FloatBuffer storeDataInFloatBuffer(final float[] data) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length); final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data); buffer.put(data);

View File

@ -4,22 +4,24 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.atriasoft.etk.Uri; import org.atriasoft.etk.Uri;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceManager { public class ResourceManager {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceManager.class);
private static final int MAX_RESOURCE_LEVEL = 9; private static final int MAX_RESOURCE_LEVEL = 9;
private final List<Resource> resourceList = new ArrayList<>(); private final List<Resource> resourceList = new ArrayList<>();
private List<Resource> resourceListToUpdate = new ArrayList<>(); private List<Resource> resourceListToUpdate = new ArrayList<>();
private boolean contextHasBeenRemoved = true; private boolean contextHasBeenRemoved = true;
private boolean exiting = false; private boolean exiting = false;
/** /**
* initialize the internal variable * initialize the internal variable
*/ */
public ResourceManager() { public ResourceManager() {
} }
/** /**
* special end of application * special end of application
*/ */
@ -27,9 +29,9 @@ public class ResourceManager {
contextHasBeenDestroyed(); contextHasBeenDestroyed();
this.exiting = true; this.exiting = true;
} }
public synchronized void cleanInternalRemoved() { public synchronized void cleanInternalRemoved() {
//Log.info("remove object in Manager"); //LOGGER.info("remove object in Manager");
updateContext(); updateContext();
// TODO ... // TODO ...
// for (auto it(this.resourceList.begin()); it!=this.resourceList.end(); ++it) { // for (auto it(this.resourceList.begin()); it!=this.resourceList.end(); ++it) {
@ -39,7 +41,7 @@ public class ResourceManager {
// } // }
// } // }
} }
/** /**
* This is to inform the resources manager that we have no more openGl context ... * This is to inform the resources manager that we have no more openGl context ...
*/ */
@ -54,33 +56,34 @@ public class ResourceManager {
// no context preent ... // no context preent ...
this.contextHasBeenRemoved = true; this.contextHasBeenRemoved = true;
} }
/** /**
* display in the log all the resources loaded ... * display in the log all the resources loaded ...
*/ */
public synchronized void display() { public synchronized void display() {
Log.info("Resources loaded : "); LOGGER.info("Resources loaded : ");
// remove all resources ... // remove all resources ...
synchronized (this.resourceList) { synchronized (this.resourceList) {
for (final Resource it : this.resourceList) { for (final Resource it : this.resourceList) {
Log.info(" [" + it.getId() + "]" + it.getClass().getCanonicalName() + "='" + it.getName() + "' " + it.getCount() + " elements"); LOGGER.info(" [" + it.getId() + "]" + it.getClass().getCanonicalName() + "='" + it.getName() + "' "
+ it.getCount() + " elements");
} }
} }
Log.info("Resources ---"); LOGGER.info("Resources ---");
} }
public synchronized void localAdd(final Resource object) { public synchronized void localAdd(final Resource object) {
// add at the end if no slot is free // add at the end if no slot is free
synchronized (this.resourceList) { synchronized (this.resourceList) {
this.resourceList.add(object); this.resourceList.add(object);
} }
} }
// internal API to extent eResources in extern Soft // internal API to extent eResources in extern Soft
public synchronized Resource localKeep(final String filename) { public synchronized Resource localKeep(final String filename) {
synchronized (this.resourceList) { synchronized (this.resourceList) {
Log.verbose("KEEP (DEFAULT) : file : '" + filename + "' in " + this.resourceList.size() + " resources"); LOGGER.trace("KEEP (DEFAULT) : file : '" + filename + "' in " + this.resourceList.size() + " resources");
for (final Resource it : this.resourceList) { for (final Resource it : this.resourceList) {
if (it == null) { if (it == null) {
continue; continue;
@ -88,7 +91,7 @@ public class ResourceManager {
if (it.getName() == null) { if (it.getName() == null) {
continue; continue;
} }
//Log.verbose("compare : " + filename + " ==???== " + it.getName()); //LOGGER.trace("compare : " + filename + " ==???== " + it.getName());
if (it.getName().contentEquals(Resource.NO_NAME_RESOURCE)) { if (it.getName().contentEquals(Resource.NO_NAME_RESOURCE)) {
continue; continue;
} }
@ -99,27 +102,27 @@ public class ResourceManager {
} }
return null; return null;
} }
public synchronized Resource localKeep(final Uri uri) { public synchronized Resource localKeep(final Uri uri) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return localKeep(uri.toString()); return localKeep(uri.toString());
} }
/** /**
* Reload all resources from files, and send there in openGL card if needed. * 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 * @note If file is reference at THEMEXXX:///filename if the Theme change the file will reload the newOne
*/ */
public synchronized void reLoadResources() { public synchronized void reLoadResources() {
Log.info("------------- Resources re-loaded -------------"); LOGGER.info("------------- Resources re-loaded -------------");
// remove all resources ... // remove all resources ...
for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) { for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) {
Log.info(" Reload level : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1)); LOGGER.info(" Reload level : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1));
synchronized (this.resourceList) { synchronized (this.resourceList) {
for (final Resource it : this.resourceList) { for (final Resource it : this.resourceList) {
if (jjj == it.getResourceLevel()) { if (jjj == it.getResourceLevel()) {
if (it.getCount() > 0) { if (it.getCount() > 0) {
it.reload(); it.reload();
Log.info(" [" + it.getId() + "]=" + it.getClass().getCanonicalName()); LOGGER.info(" [" + it.getId() + "]=" + it.getClass().getCanonicalName());
} }
} }
} }
@ -127,9 +130,9 @@ public class ResourceManager {
} }
// TODO UNderstand why it is set here ... // TODO UNderstand why it is set here ...
//gale::requestUpdateSize(); //gale::requestUpdateSize();
Log.info("------------- Resources -------------"); LOGGER.info("------------- Resources -------------");
} }
/** /**
* Uninitiamize the resource manager, free all resources previously requested * Uninitiamize the resource manager, free all resources previously requested
* @note when not free == > generate warning, because the segfault can appear after... * @note when not free == > generate warning, because the segfault can appear after...
@ -144,12 +147,13 @@ public class ResourceManager {
// remove all resources ... // remove all resources ...
synchronized (this.resourceList) { synchronized (this.resourceList) {
for (final Resource it : this.resourceList) { for (final Resource it : this.resourceList) {
Log.warning("Find a resource that is not removed : [" + it.getId() + "]" + "='" + it.getName() + "' " + it.getCount() + " elements"); LOGGER.warn("Find a resource that is not removed : [" + it.getId() + "]" + "='" + it.getName() + "' "
+ it.getCount() + " elements");
} }
this.resourceList.clear(); this.resourceList.clear();
} }
} }
/** /**
* Call by the system to send all the needed data on the graphic card chen they change ... * 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 * @param object The resources that might be updated
@ -167,16 +171,16 @@ public class ResourceManager {
this.resourceListToUpdate.add(object); this.resourceListToUpdate.add(object);
} }
} }
/** /**
* Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other .... * Call by the system chen the openGL Context has been unexpectially removed == > This reload all the texture, VBO and other ....
*/ */
public void updateContext() { public void updateContext() {
if (this.exiting) { if (this.exiting) {
Log.error("Request update after application EXIT ..."); LOGGER.error("Request update after application EXIT ...");
return; return;
} }
// TODO Check the number of call this ... Log.info("update open-gl context ... "); // TODO Check the number of call this ... LOGGER.info("update open-gl context ... ");
if (this.contextHasBeenRemoved) { if (this.contextHasBeenRemoved) {
// need to update all ... // need to update all ...
this.contextHasBeenRemoved = false; this.contextHasBeenRemoved = false;
@ -186,10 +190,11 @@ public class ResourceManager {
synchronized (this.resourceList) { synchronized (this.resourceList) {
if (this.resourceList.size() != 0) { if (this.resourceList.size() != 0) {
for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) { for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) {
Log.verbose(" updateContext level (D) : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1)); LOGGER.trace(" updateContext level (D) : " + jjj + "/"
+ (ResourceManager.MAX_RESOURCE_LEVEL - 1));
for (final Resource it : this.resourceList) { for (final Resource it : this.resourceList) {
if (jjj == it.getResourceLevel()) { if (jjj == it.getResourceLevel()) {
//Log.debug("Update context named : " + lresourceList[iii].getName()); //LOGGER.debug("Update context named : " + lresourceList[iii].getName());
if (!it.updateContext()) { if (!it.updateContext()) {
// Lock error ==> postponned // Lock error ==> postponned
synchronized (this.resourceListToUpdate) { synchronized (this.resourceListToUpdate) {
@ -209,7 +214,8 @@ public class ResourceManager {
} }
if (resourceListToUpdate.size() != 0) { if (resourceListToUpdate.size() != 0) {
for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) { for (long jjj = 0; jjj < ResourceManager.MAX_RESOURCE_LEVEL; jjj++) {
Log.verbose(" updateContext level (U) : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1)); LOGGER.trace(
" updateContext level (U) : " + jjj + "/" + (ResourceManager.MAX_RESOURCE_LEVEL - 1));
for (final Resource it : resourceListToUpdate) { for (final Resource it : resourceListToUpdate) {
if (jjj == it.getResourceLevel()) { if (jjj == it.getResourceLevel()) {
if (!it.updateContext()) { if (!it.updateContext()) {
@ -222,5 +228,5 @@ public class ResourceManager {
} }
} }
} }
} }

View File

@ -13,12 +13,12 @@ import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.etk.math.Vector3i; import org.atriasoft.etk.math.Vector3i;
import org.atriasoft.etk.math.Vector4f; import org.atriasoft.etk.math.Vector4f;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ProgAttributeElement { class ProgAttributeElement {
public String name; // !< Name of the element public String name; // !< Name of the element
@ -28,18 +28,20 @@ class ProgAttributeElement {
} }
public class ResourceProgram extends Resource { public class ResourceProgram extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceProgram.class);
static final boolean DEBUG = false; // TODO externalize this ... static final boolean DEBUG = false; // TODO externalize this ...
public static ResourceProgram create(final Uri uriVertexShader, final Uri uriFragmentShader) { public static ResourceProgram create(final Uri uriVertexShader, final Uri uriFragmentShader) {
ResourceProgram resource; ResourceProgram resource;
final String name = uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue(); final String name = uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue();
Resource resource2 = Resource.getManager().localKeep(name); final Resource resource2 = Resource.getManager().localKeep(name);
if (resource2 != null) { if (resource2 != null) {
if (resource2 instanceof ResourceProgram) { if (resource2 instanceof ResourceProgram) {
resource2.keep(); resource2.keep();
return (ResourceProgram) resource2; return (ResourceProgram) resource2;
} }
Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)"); LOGGER.error("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null; return null;
} }
resource = new ResourceProgram(uriVertexShader, uriFragmentShader); resource = new ResourceProgram(uriVertexShader, uriFragmentShader);
@ -99,19 +101,19 @@ public class ResourceProgram extends Resource {
protected ResourceProgram(final Uri uriVertexShader, final Uri uriFragmentShader) { protected ResourceProgram(final Uri uriVertexShader, final Uri uriFragmentShader) {
super(uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue()); super(uriVertexShader.getValue() + "<-->" + uriFragmentShader.getValue());
this.resourceLevel = 1; this.resourceLevel = 1;
Log.debug("OGL : load PROGRAM '" + uriVertexShader + "' && '" + uriFragmentShader + "'"); LOGGER.debug("OGL : load PROGRAM '" + uriVertexShader + "' && '" + uriFragmentShader + "'");
this.shaderVertex = ResourceShader.create(uriVertexShader); this.shaderVertex = ResourceShader.create(uriVertexShader);
if (this.shaderVertex == null) { if (this.shaderVertex == null) {
Log.error("Error while getting a specific shader filename: " + uriVertexShader); LOGGER.error("Error while getting a specific shader filename: " + uriVertexShader);
return; return;
} }
Log.debug("Add shader on program: '" + uriFragmentShader + "'"); LOGGER.debug("Add shader on program: '" + uriFragmentShader + "'");
this.shaderFragment = ResourceShader.create(uriFragmentShader); this.shaderFragment = ResourceShader.create(uriFragmentShader);
if (this.shaderFragment == null) { if (this.shaderFragment == null) {
Log.error("Error while getting a specific shader filename: " + uriFragmentShader); LOGGER.error("Error while getting a specific shader filename: " + uriFragmentShader);
return; return;
} }
Log.debug("Add shader on program : " + uriFragmentShader + "frag"); LOGGER.debug("Add shader on program : " + uriFragmentShader + "frag");
if (OpenGL.hasContext()) { if (OpenGL.hasContext()) {
updateContext(); updateContext();
} else { } else {
@ -131,14 +133,15 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || idElem > this.elementList.size()) { if (idElem < 0 || idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
return; return;
} }
Log.error("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(vboId) + " VBOindex=" + vboId); LOGGER.error("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(vboId)
+ " VBOindex=" + vboId);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo.getOpenGlId(vboId)); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo.getOpenGlId(vboId));
GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId); GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
this.listOfVBOUsed.add(this.elementList.get(idElem).elementId); this.listOfVBOUsed.add(this.elementList.get(idElem).elementId);
@ -223,10 +226,12 @@ public class ResourceProgram extends Resource {
tmp.elementId = OpenGL.programGetAttributeLocation(this.program, tmp.name); tmp.elementId = OpenGL.programGetAttributeLocation(this.program, tmp.name);
tmp.isLinked = true; tmp.isLinked = true;
if (tmp.elementId < 0) { if (tmp.elementId < 0) {
Log.warning(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\"" + tmp.name + "\") = " + tmp.elementId); LOGGER.warn(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
tmp.isLinked = false; tmp.isLinked = false;
} else { } else {
Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\"" + tmp.name + "\") = " + tmp.elementId); LOGGER.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetAttribLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
} }
} else { } else {
// program is not loaded ==> just local reister ... // program is not loaded ==> just local reister ...
@ -269,10 +274,12 @@ public class ResourceProgram extends Resource {
tmp.elementId = OpenGL.programGetUniformLocation(this.program, tmp.name); tmp.elementId = OpenGL.programGetUniformLocation(this.program, tmp.name);
tmp.isLinked = true; tmp.isLinked = true;
if (tmp.elementId < 0) { if (tmp.elementId < 0) {
Log.warning(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + tmp.name + "\") = " + tmp.elementId); LOGGER.warn(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
tmp.isLinked = false; tmp.isLinked = false;
} else { } else {
Log.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\"" + tmp.name + "\") = " + tmp.elementId); LOGGER.debug(" {" + this.program + "}[" + this.elementList.size() + "] glGetUniformLocation(\""
+ tmp.name + "\") = " + tmp.elementId);
} }
} else { } else {
// program is not loaded ==> just local reister ... // program is not loaded ==> just local reister ...
@ -293,14 +300,14 @@ public class ResourceProgram extends Resource {
public void reload() { public void reload() {
/* /*
* TODO ... etk::file file(this.name, etk::FILETYPEDATA); if (file.Exist() == * TODO ... etk::file file(this.name, etk::FILETYPEDATA); if (file.Exist() ==
* false) { Log.error("File does not Exist :"" + file + "\""); return; } * false) { LOGGER.error("File does not Exist :"" + file + "\""); return; }
* *
* int fileSize = file.size(); if (fileSize == 0) { * int fileSize = file.size(); if (fileSize == 0) {
* Log.error("This file is empty : " + file); return; } if (file.fOpenRead() == * LOGGER.error("This file is empty : " + file); return; } if (file.fOpenRead() ==
* false) { Log.error("Can not open the file : " + file); return; } // remove * false) { LOGGER.error("Can not open the file : " + file); return; } // remove
* previous data ... if (this.fileData != null) { del ete[] this.fileData; * previous data ... if (this.fileData != null) { del ete[] this.fileData;
* this.fileData = 0; } // allocate data this.fileData = ne w char[fileSize+5]; * this.fileData = 0; } // allocate data this.fileData = ne w char[fileSize+5];
* if (this.fileData == null) { Log.error("Error Memory allocation size=" + * if (this.fileData == null) { LOGGER.error("Error Memory allocation size=" +
* fileSize); return; } memset(this.fileData, 0, (fileSize+5)*sizeof(char)); // * fileSize); return; } memset(this.fileData, 0, (fileSize+5)*sizeof(char)); //
* load data from the file : file.fRead(this.fileData, 1, fileSize); // close * load data from the file : file.fRead(this.fileData, 1, fileSize); // close
* the file: file.fClose(); * the file: file.fClose();
@ -353,7 +360,7 @@ public class ResourceProgram extends Resource {
// } // }
// if ( idElem < 0 // if ( idElem < 0
// || (long)idElem > this.elementList.size()) { // || (long)idElem > this.elementList.size()) {
// Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) // LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1)
// + "]"); // + "]");
// return; // return;
// } // }
@ -362,7 +369,7 @@ public class ResourceProgram extends Resource {
// } // }
// FloatBuffer buffer = storeDataInFloatBuffer(data); // FloatBuffer buffer = storeDataInFloatBuffer(data);
// //GL40.glBindVertexArray(this.elementList.get(idElem).elementId); // //GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
// Log.error("[" + this.elementList.get(idElem).name + "] send " + data.length + // LOGGER.error("[" + this.elementList.get(idElem).name + "] send " + data.length +
// " element"); // " element");
// GL40.glVertexAttribPointer( // GL40.glVertexAttribPointer(
// this.elementList.get(idElem).elementId, // this.elementList.get(idElem).elementId,
@ -381,21 +388,26 @@ public class ResourceProgram extends Resource {
// public void sendAttribute(int idElem, List<Vector3f> data) { // public void sendAttribute(int idElem, List<Vector3f> data) {
// sendAttribute3fv(idElem, convertInFloat(data)); // sendAttribute3fv(idElem, convertInFloat(data));
// } // }
public void sendAttribute(final int idElem, final int nbElement, final FloatBuffer data, final int jumpBetweenSample) { public void sendAttribute(
final int idElem,
final int nbElement,
final FloatBuffer data,
final int jumpBetweenSample) {
if (!this.exist) { if (!this.exist) {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
return; return;
} }
// GL40.glBindVertexArray(this.elementList.get(idElem).elementId); // GL40.glBindVertexArray(this.elementList.get(idElem).elementId);
// Log.error("[" + this.elementList.get(idElem).name + "] send " + 3 + " // LOGGER.error("[" + this.elementList.get(idElem).name + "] send " + 3 + "
// element"); // element");
GL20.glVertexAttribPointer(this.elementList.get(idElem).elementId, nbElement, GL11.GL_FLOAT, false, jumpBetweenSample * 4, /* 4 is the size of float in the generic system... */ GL20.glVertexAttribPointer(this.elementList.get(idElem).elementId, nbElement, GL11.GL_FLOAT, false,
jumpBetweenSample * 4, /* 4 is the size of float in the generic system... */
data); data);
// checkGlError("glVertexAttribPointer", LINE, idElem); // checkGlError("glVertexAttribPointer", LINE, idElem);
GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId); GL20.glEnableVertexAttribArray(this.elementList.get(idElem).elementId);
@ -420,7 +432,7 @@ public class ResourceProgram extends Resource {
// } // }
// if ( idElem < 0 // if ( idElem < 0
// || (long)idElem > this.elementList.size()) { // || (long)idElem > this.elementList.size()) {
// Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1) // LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size()-1)
// + "]"); // + "]");
// return; // return;
// } // }
@ -429,17 +441,17 @@ public class ResourceProgram extends Resource {
// } // }
// // check error of the VBO goog enought ... // // check error of the VBO goog enought ...
// if (vbo.getElementSize(index) <= 0) { // if (vbo.getElementSize(index) <= 0) {
// Log.error("Can not bind a VBO Buffer with an element size of : " + // LOGGER.error("Can not bind a VBO Buffer with an element size of : " +
// vbo.getElementSize(index) + " named=" + vbo.getName()); // vbo.getElementSize(index) + " named=" + vbo.getName());
// return; // return;
// } // }
// //
// Log.verbose("[" + this.elementList.get(idElem).name + "] send " + // LOGGER.trace("[" + this.elementList.get(idElem).name + "] send " +
// vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + " // vbo.getElementSize(index) + " element on oglID=" + vbo.getGLID(index) + "
// VBOindex=" + index); // VBOindex=" + index);
// OpenGL.bindBuffer(vbo.getGLID(index)); // OpenGL.bindBuffer(vbo.getGLID(index));
// Log.verbose(" id=" + this.elementList.get(idElem).elementId); // LOGGER.trace(" id=" + this.elementList.get(idElem).elementId);
// Log.verbose(" eleme size=" + vbo.getElementSize(index)); // LOGGER.trace(" eleme size=" + vbo.getElementSize(index));
// OpenGL.bufferData(data, Usage.staticDraw); // OpenGL.bufferData(data, Usage.staticDraw);
// OpenGL.vertexAttribPointerFloat(this.elementList.get(idElem).elementId, // OpenGL.vertexAttribPointerFloat(this.elementList.get(idElem).elementId,
// vbo.getElementSize(index)); // Pointer on the buffer // vbo.getElementSize(index)); // Pointer on the buffer
@ -454,19 +466,20 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || idElem > this.elementList.size()) { if (idElem < 0 || idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
return; return;
} }
Log.verbose("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(index) + " VBOindex=" + index); LOGGER.trace("[" + this.elementList.get(idElem).name + "] send on oglID=" + vbo.getOpenGlId(index)
+ " VBOindex=" + index);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo.getOpenGlId(index)); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo.getOpenGlId(index));
// checkGlError("glBindBuffer", __LINE__, _idElem); // checkGlError("glBindBuffer", __LINE__, _idElem);
Log.verbose(" id=" + this.elementList.get(idElem).elementId); LOGGER.trace(" id=" + this.elementList.get(idElem).elementId);
Log.verbose(" jump sample=" + jumpBetweenSample); LOGGER.trace(" jump sample=" + jumpBetweenSample);
Log.verbose(" offset=" + offset); LOGGER.trace(" offset=" + offset);
GL20.glVertexAttribPointer(this.elementList.get(idElem).elementId, // attribute ID of openGL GL20.glVertexAttribPointer(this.elementList.get(idElem).elementId, // attribute ID of openGL
vbo.getElementSize(index), // number of elements per vertex, here (r,g,b,a) vbo.getElementSize(index), // number of elements per vertex, here (r,g,b,a)
GL11.GL_FLOAT, // the type of each element GL11.GL_FLOAT, // the type of each element
@ -525,7 +538,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -539,7 +552,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -547,6 +560,7 @@ public class ResourceProgram extends Resource {
} }
OpenGL.programLoadUniformColorRGB(this.elementList.get(idElem).elementId, value); OpenGL.programLoadUniformColorRGB(this.elementList.get(idElem).elementId, value);
} }
/** /**
* Send 1 float uniform element to the spefified ID (not send if does not * Send 1 float uniform element to the spefified ID (not send if does not
* really exist in the openGL program) * really exist in the openGL program)
@ -558,7 +572,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -580,7 +594,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -603,7 +617,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -621,13 +635,18 @@ public class ResourceProgram extends Resource {
* @param value3 Value to send at the Uniform * @param value3 Value to send at the Uniform
* @param value4 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) { public void uniformFloat(
final int idElem,
final float value1,
final float value2,
final float value3,
final float value4) {
if (!this.exist) { if (!this.exist) {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -648,7 +667,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -670,7 +689,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -693,7 +712,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -717,7 +736,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -744,13 +763,13 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
return; return;
} }
// Log.error("[" + this.elementList.get(idElem).name + "] send 1 matrix"); // LOGGER.error("[" + this.elementList.get(idElem).name + "] send 1 matrix");
// note : Android des not supported the transposition of the matrix, then we // note : Android des not supported the transposition of the matrix, then we
// will done it oursef: // will done it oursef:
/* /*
@ -762,13 +781,12 @@ public class ResourceProgram extends Resource {
OpenGL.programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix, transpose); OpenGL.programLoadUniformMatrix(this.elementList.get(idElem).elementId, matrix, transpose);
} }
public void uniformVector(final int idElem, final Vector2f value) { public void uniformVector(final int idElem, final Vector2f value) {
if (!this.exist) { if (!this.exist) {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -782,7 +800,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -796,7 +814,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -810,7 +828,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -824,7 +842,7 @@ public class ResourceProgram extends Resource {
return; return;
} }
if (idElem < 0 || (long) idElem > this.elementList.size()) { if (idElem < 0 || (long) idElem > this.elementList.size()) {
Log.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]"); LOGGER.error("idElem = " + idElem + " not in [0.." + (this.elementList.size() - 1) + "]");
return; return;
} }
if (!this.elementList.get(idElem).isLinked) { if (!this.elementList.get(idElem).isLinked) {
@ -837,7 +855,7 @@ public class ResourceProgram extends Resource {
* Stop the processing of this program * Stop the processing of this program
*/ */
public void unUse() { public void unUse() {
// Log.verbose("Will UN-use program : " + this.program); // LOGGER.trace("Will UN-use program : " + this.program);
if (!this.exist) { if (!this.exist) {
return; return;
@ -860,7 +878,7 @@ public class ResourceProgram extends Resource {
// Do nothing == > too dangerous ... // Do nothing == > too dangerous ...
} else { } else {
// create the Shader // create the Shader
Log.debug("Create the Program ...'" + this.name + "'"); LOGGER.debug("Create the Program ...'" + this.name + "'");
this.program = OpenGL.programCreate(); this.program = OpenGL.programCreate();
if (this.program < 0) { if (this.program < 0) {
return true; return true;
@ -874,12 +892,13 @@ public class ResourceProgram extends Resource {
} }
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, "in_position"); OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, "in_position");
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, "in_extureCoords"); OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES,
"in_extureCoords");
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_NORMALS, "in_normal"); OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_NORMALS, "in_normal");
OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_COLORS, "in_colors"); OpenGL.programBindAttribute(this.program, ResourceVirtualArrayObject.INDICE_VBO_COLORS, "in_colors");
if (!OpenGL.programCompile(this.program)) { if (!OpenGL.programCompile(this.program)) {
Log.error("Could not compile'PROGRAM':'" + this.name + "'"); LOGGER.error("Could not compile'PROGRAM':'" + this.name + "'");
OpenGL.programRemove(this.program); OpenGL.programRemove(this.program);
return true; return true;
} }
@ -890,19 +909,23 @@ public class ResourceProgram extends Resource {
it.elementId = OpenGL.programGetAttributeLocation(this.program, it.name); it.elementId = OpenGL.programGetAttributeLocation(this.program, it.name);
it.isLinked = true; it.isLinked = true;
if (it.elementId < 0) { if (it.elementId < 0) {
Log.warning(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId); LOGGER.warn(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name
+ "\") = " + it.elementId);
it.isLinked = false; it.isLinked = false;
} else { } else {
Log.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name + "\") = " + it.elementId); LOGGER.debug(" {" + this.program + "}[" + iii + "] openGL::getAttributeLocation(\"" + it.name
+ "\") = " + it.elementId);
} }
} else { } else {
it.elementId = OpenGL.programGetUniformLocation(this.program, it.name); it.elementId = OpenGL.programGetUniformLocation(this.program, it.name);
it.isLinked = true; it.isLinked = true;
if (it.elementId < 0) { if (it.elementId < 0) {
Log.warning(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId); LOGGER.warn(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name
+ "\") = " + it.elementId);
it.isLinked = false; it.isLinked = false;
} else { } else {
Log.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name + "\") = " + it.elementId); LOGGER.debug(" {" + this.program + "}[" + iii + "] openGL::getUniformLocation(\"" + it.name
+ "\") = " + it.elementId);
} }
} }
iii++; iii++;
@ -917,7 +940,7 @@ public class ResourceProgram extends Resource {
* Request the processing of this program * Request the processing of this program
*/ */
public void use() { public void use() {
// Log.verbose("Will use program : " + this.program); // LOGGER.trace("Will use program : " + this.program);
// event if it was 0 == > set it to prevent other use of the previous shader // event if it was 0 == > set it to prevent other use of the previous shader
// display ... // display ...
OpenGL.programUse(this.program); OpenGL.programUse(this.program);

View File

@ -3,9 +3,11 @@ package org.atriasoft.gale.resource;
import org.atriasoft.etk.Uri; import org.atriasoft.etk.Uri;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.ShaderType; import org.atriasoft.gale.backend3d.OpenGL.ShaderType;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceShader extends Resource { public class ResourceShader extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceShader.class);
public static ResourceShader create(final Uri uriShader) { public static ResourceShader create(final Uri uriShader) {
ResourceShader resource; ResourceShader resource;
@ -14,7 +16,7 @@ public class ResourceShader extends Resource {
if (!name.isEmpty() && !name.equals("---")) { if (!name.isEmpty() && !name.equals("---")) {
resource2 = getManager().localKeep(name); resource2 = getManager().localKeep(name);
} else { } else {
Log.error("Can not create a shader without a filaname"); LOGGER.error("Can not create a shader without a filaname");
return null; return null;
} }
if (resource2 != null) { if (resource2 != null) {
@ -22,7 +24,8 @@ public class ResourceShader extends Resource {
resource2.keep(); resource2.keep();
return (ResourceShader) resource2; return (ResourceShader) resource2;
} }
Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)"); LOGGER.error("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null; return null;
} }
resource = new ResourceShader(uriShader); resource = new ResourceShader(uriShader);
@ -43,7 +46,7 @@ public class ResourceShader extends Resource {
super(uri); super(uri);
this.uri = uri; this.uri = uri;
this.resourceLevel = 0; this.resourceLevel = 0;
Log.debug("OGL : load SHADER '" + uri + "'"); LOGGER.debug("OGL : load SHADER '" + uri + "'");
// load data from file "all the time ..." // load data from file "all the time ..."
if (uri.get().endsWith(".frag")) { if (uri.get().endsWith(".frag")) {
@ -51,7 +54,9 @@ public class ResourceShader extends Resource {
} else if (uri.get().endsWith(".vert")) { } else if (uri.get().endsWith(".vert")) {
this.type = ShaderType.VERTEX; this.type = ShaderType.VERTEX;
} else { } else {
Log.error("File does not have extention '.vert' for Vertex Shader or '.frag' for Fragment Shader. but : \"" + uri + "\""); LOGGER.error(
"File does not have extention '.vert' for Vertex Shader or '.frag' for Fragment Shader. but : \""
+ uri + "\"");
this.type = ShaderType.VERTEX; this.type = ShaderType.VERTEX;
return; return;
} }
@ -90,15 +95,16 @@ public class ResourceShader extends Resource {
@Override @Override
public void reload() { public void reload() {
//!< A copy of the data loaded from the file (useful only when opengl context is removed) //!< A copy of the data loaded from the file (useful only when opengl context is removed)
String fileData = ""; final String fileData = "";
Log.verbose("load shader:\n-----------------------------------------------------------------\n" + fileData + "\n-----------------------------------------------------------------"); LOGGER.trace("load shader:\n-----------------------------------------------------------------\n" + fileData
+ "\n-----------------------------------------------------------------");
// now change the OGL context ... // now change the OGL context ...
if (OpenGL.hasContext()) { if (OpenGL.hasContext()) {
Log.debug("OGL : load SHADER '" + this.name + "' ==> call update context (direct)"); LOGGER.debug("OGL : load SHADER '" + this.name + "' ==> call update context (direct)");
removeContext(); removeContext();
updateContext(); updateContext();
} else { } else {
Log.debug("OGL : load SHADER '" + this.name + "' ==> tagged has update context needed"); LOGGER.debug("OGL : load SHADER '" + this.name + "' ==> tagged has update context needed");
// TODO Check this, this is a leek ==> in the GPU ... really bad ... // TODO Check this, this is a leek ==> in the GPU ... really bad ...
this.exist = false; this.exist = false;
this.shader = 0; this.shader = 0;

View File

@ -6,29 +6,35 @@ import org.atriasoft.egami.ImageByteRGBA;
import org.atriasoft.etk.Uri; import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Vector2i; import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.gale.tools.ImageLoader; import org.atriasoft.gale.tools.ImageLoader;
import org.atriasoft.gale.tools.ImageRawData; import org.atriasoft.gale.tools.ImageRawData;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Deprecated @Deprecated
public class ResourceTexture extends Resource { public class ResourceTexture extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceTexture.class);
public enum TextureColorMode { public enum TextureColorMode {
rgb, //!< red/green/blue data rgb, //!< red/green/blue data
rgba //!< red/green/blue/alpha data rgba //!< red/green/blue/alpha data
} }
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, private static int[] textureIdBinding = { GL13.GL_TEXTURE0, GL13.GL_TEXTURE1, GL13.GL_TEXTURE2, GL13.GL_TEXTURE3,
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_TEXTURE4, GL13.GL_TEXTURE5, GL13.GL_TEXTURE6, GL13.GL_TEXTURE7, GL13.GL_TEXTURE8, GL13.GL_TEXTURE9,
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_TEXTURE10, GL13.GL_TEXTURE11, GL13.GL_TEXTURE12, GL13.GL_TEXTURE13, GL13.GL_TEXTURE14,
GL13.GL_TEXTURE27, GL13.GL_TEXTURE28, GL13.GL_TEXTURE29, GL13.GL_TEXTURE30, GL13.GL_TEXTURE31 };; 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) { public static ResourceTexture createFromPng(final Uri uriTexture) {
return createFromPng(uriTexture, 1); return createFromPng(uriTexture, 1);
} }
public static ResourceTexture createFromPng(final Uri uriTexture, final int textureUnit) { public static ResourceTexture createFromPng(final Uri uriTexture, final int textureUnit) {
ResourceTexture resource; ResourceTexture resource;
Resource resource2; Resource resource2;
@ -36,7 +42,7 @@ public class ResourceTexture extends Resource {
if (!name.isEmpty() && !name.equals("---")) { if (!name.isEmpty() && !name.equals("---")) {
resource2 = getManager().localKeep(name); resource2 = getManager().localKeep(name);
} else { } else {
Log.error("Can not create a shader without a filaname"); LOGGER.error("Can not create a shader without a filaname");
return null; return null;
} }
if (resource2 != null) { if (resource2 != null) {
@ -44,14 +50,15 @@ public class ResourceTexture extends Resource {
resource2.keep(); resource2.keep();
return (ResourceTexture) resource2; return (ResourceTexture) resource2;
} }
Log.critical("Request resource file : '" + name + "' With the wrong type (dynamic cast error)"); LOGGER.error("Request resource file : '" + name + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null; return null;
} }
resource = new ResourceTexture(uriTexture, textureUnit); resource = new ResourceTexture(uriTexture, textureUnit);
final ImageRawData decodedData = ImageLoader.decodePngFile(uriTexture); final ImageRawData decodedData = ImageLoader.decodePngFile(uriTexture);
ImageByteRGBA img = new ImageByteRGBA(decodedData.getWidth(), decodedData.getHeight()); final ImageByteRGBA img = new ImageByteRGBA(decodedData.getWidth(), decodedData.getHeight());
ByteBuffer mlklmklm = decodedData.getBuffer(); final ByteBuffer mlklmklm = decodedData.getBuffer();
byte[] elemData = new byte[mlklmklm.remaining()]; final byte[] elemData = new byte[mlklmklm.remaining()];
mlklmklm.get(elemData); mlklmklm.get(elemData);
if (decodedData.isHasAlpha()) { if (decodedData.isHasAlpha()) {
for (int yyy = 0; yyy < decodedData.getHeight(); yyy++) { for (int yyy = 0; yyy < decodedData.getHeight(); yyy++) {
@ -65,18 +72,19 @@ public class ResourceTexture extends Resource {
} else { } else {
for (int yyy = 0; yyy < decodedData.getHeight(); yyy++) { for (int yyy = 0; yyy < decodedData.getHeight(); yyy++) {
for (int xxx = 0; xxx < decodedData.getWidth(); xxx++) { for (int xxx = 0; xxx < decodedData.getWidth(); xxx++) {
img.setAByte(xxx, yyy, (byte)0xFF); img.setAByte(xxx, yyy, (byte) 0xFF);
img.setRByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 0]); img.setRByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 0]);
img.setGByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 1]); img.setGByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 1]);
img.setBByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 2]); img.setBByte(xxx, yyy, elemData[(yyy * decodedData.getWidth() + xxx) * 3 + 2]);
} }
} }
} }
resource.setTexture(img, new Vector2i(decodedData.getWidth(), decodedData.getHeight()), (decodedData.isHasAlpha() ? TextureColorMode.rgba : TextureColorMode.rgb), textureUnit); resource.setTexture(img, new Vector2i(decodedData.getWidth(), decodedData.getHeight()),
(decodedData.isHasAlpha() ? TextureColorMode.rgba : TextureColorMode.rgb), textureUnit);
resource.flush(); resource.flush();
return resource; return resource;
} }
/** /**
* get the next power 2 if the input * get the next power 2 if the input
* @param value Value that we want the next power of 2 * @param value Value that we want the next power of 2
@ -90,10 +98,11 @@ public class ResourceTexture extends Resource {
} }
val *= 2; val *= 2;
} }
Log.critical("impossible CASE...."); LOGGER.error("impossible CASE....");
System.exit(-1);
return val; return val;
} }
protected int texId = -1; //!< openGl textureID. 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. // 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 Vector2i endPointSize = new Vector2i(-1, -1); protected Vector2i endPointSize = new Vector2i(-1, -1);
@ -109,16 +118,14 @@ public class ResourceTexture extends Resource {
private TextureColorMode dataColorSpace = TextureColorMode.rgb; private TextureColorMode dataColorSpace = TextureColorMode.rgb;
// number of lines and colomns in the texture (multiple texturing in a single texture) // number of lines and colomns in the texture (multiple texturing in a single texture)
private int textureUnit = 0; private int textureUnit = 0;
protected ResourceTexture() { protected ResourceTexture() {}
super();
}
protected ResourceTexture(final Uri filename, final int textureUnit) { protected ResourceTexture(final Uri filename, final int textureUnit) {
super(filename.toString() + "__" + textureUnit); super(filename.toString() + "__" + textureUnit);
this.textureUnit = textureUnit; this.textureUnit = textureUnit;
} }
public void bindForRendering(final int idTexture) { public void bindForRendering(final int idTexture) {
if (!this.loaded) { if (!this.loaded) {
return; return;
@ -130,49 +137,53 @@ public class ResourceTexture extends Resource {
OpenGL.enable(OpenGL.Flag.flag_back); OpenGL.enable(OpenGL.Flag.flag_back);
} }
} }
@Override @Override
public void cleanUp() { public void cleanUp() {
removeContext(); removeContext();
} }
// Flush the data to send it at the openGl system // Flush the data to send it at the openGl system
public synchronized void flush() { public synchronized void flush() {
// request to the manager to be call at the next update ... // request to the manager to be call at the next update ...
Log.verbose("Request UPDATE of Element"); LOGGER.trace("Request UPDATE of Element");
getManager().update(this); getManager().update(this);
} }
public Vector2i getOpenGlSize() { public Vector2i getOpenGlSize() {
return this.size; return this.size;
}; };
public int getRendererId() { public int getRendererId() {
return this.texId; return this.texId;
} }
public Vector2i getUsableSize() { public Vector2i getUsableSize() {
return this.endPointSize; return this.endPointSize;
} }
@Override @Override
public synchronized void removeContext() { public synchronized void removeContext() {
if (this.loaded) { if (this.loaded) {
// Request remove texture ... // Request remove texture ...
Log.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId); LOGGER.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
// TODO Check if we are in the correct thread // TODO Check if we are in the correct thread
OpenGL.glDeleteTextures(this.texId); OpenGL.glDeleteTextures(this.texId);
this.loaded = false; this.loaded = false;
} }
} }
@Override @Override
public synchronized void removeContextToLate() { public synchronized void removeContextToLate() {
this.loaded = false; this.loaded = false;
this.texId = -1; this.texId = -1;
} }
public void setTexture(final ImageByteRGBA data, final Vector2i size, final TextureColorMode dataColorSpace, final int textureUnit) { public void setTexture(
final ImageByteRGBA data,
final Vector2i size,
final TextureColorMode dataColorSpace,
final int textureUnit) {
this.data = data; this.data = data;
this.size = size; this.size = size;
this.textureUnit = textureUnit; this.textureUnit = textureUnit;
@ -180,7 +191,7 @@ public class ResourceTexture extends Resource {
this.dataColorSpace = dataColorSpace; this.dataColorSpace = dataColorSpace;
flush(); flush();
} }
public void unBindForRendering() { public void unBindForRendering() {
if (!this.loaded) { if (!this.loaded) {
return; return;
@ -190,7 +201,7 @@ public class ResourceTexture extends Resource {
OpenGL.disable(OpenGL.Flag.flag_back); OpenGL.disable(OpenGL.Flag.flag_back);
} }
} }
// Gale internal API: // Gale internal API:
@Override @Override
public boolean updateContext() { public boolean updateContext() {
@ -201,24 +212,26 @@ public class ResourceTexture extends Resource {
this.texId = GL11.glGenTextures(); this.texId = GL11.glGenTextures();
GL13.glActiveTexture(this.textureUnit); GL13.glActiveTexture(this.textureUnit);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texId); GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texId);
// All RGB bytes are aligned to each other and each component is 1 byte // All RGB bytes are aligned to each other and each component is 1 byte
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
Log.info("TEXTURE: add [" + getId() + "]=" + this.size + " OGlId=" + this.texId); LOGGER.info("TEXTURE: add [" + getId() + "]=" + this.size + " OGlId=" + this.texId);
if (this.dataColorSpace == TextureColorMode.rgb) { if (this.dataColorSpace == TextureColorMode.rgb) {
OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, this.data.getRaw()); OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE,
//The local image has not RGB but only RGBA data ... this.data.getRaw());
//The local image has not RGB but only RGBA data ...
//OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, this.data.getRaw()); //OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, this.data.getRaw());
} else { } else {
OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, this.data.getRaw()); OpenGL.glTexImage2D(0, GL11.GL_RGBA, this.size.x(), this.size.y(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE,
this.data.getRaw());
} }
// generate multi-texture mapping // generate multi-texture mapping
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
// Setup the ST coordinate system // 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_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, 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 // 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_MAG_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);

View File

@ -12,59 +12,64 @@ import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Vector2i; import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.gale.TextureFilter; import org.atriasoft.gale.TextureFilter;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceTexture2 extends Resource { public class ResourceTexture2 extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceTexture2.class);
public enum TextureColorMode { public enum TextureColorMode {
rgb, // !< red/green/blue data rgb, // !< red/green/blue data
rgba // !< red/green/blue/alpha data rgba // !< red/green/blue/alpha data
} }
public static ResourceTexture2 create() { public static ResourceTexture2 create() {
Log.verbose("KEEP: Resource Texture Dynamic: "); LOGGER.trace("KEEP: Resource Texture Dynamic: ");
return new ResourceTexture2(); return new ResourceTexture2();
} }
public static ResourceTexture2 create(final Uri uri) { public static ResourceTexture2 create(final Uri uri) {
Log.verbose("KEEP: Resource Texture: " + uri); LOGGER.trace("KEEP: Resource Texture: " + uri);
final Resource object2 = Resource.getManager().localKeep(uri); final Resource object2 = Resource.getManager().localKeep(uri);
if (object2 != null) { if (object2 != null) {
if (object2 instanceof ResourceTexture2 tmpp) { if (object2 instanceof final ResourceTexture2 tmpp) {
return tmpp; return tmpp;
} }
Log.critical("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)"); LOGGER.error("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null; return null;
} }
Log.verbose("CREATE: new Texture: " + uri); LOGGER.trace("CREATE: new Texture: " + uri);
return new ResourceTexture2(uri); return new ResourceTexture2(uri);
} }
public static ResourceTexture2 createNamed(final String uri) { public static ResourceTexture2 createNamed(final String uri) {
Log.verbose("KEEP: Resource Texture Named: " + uri); LOGGER.trace("KEEP: Resource Texture Named: " + uri);
final Resource object2 = Resource.getManager().localKeep(uri); final Resource object2 = Resource.getManager().localKeep(uri);
if (object2 != null) { if (object2 != null) {
if (object2 instanceof ResourceTexture2 tmpp) { if (object2 instanceof final ResourceTexture2 tmpp) {
return tmpp; return tmpp;
} }
Log.critical("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)"); LOGGER.error("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null; return null;
} }
Log.debug("CREATE: new Texture Named: " + uri); LOGGER.debug("CREATE: new Texture Named: " + uri);
return new ResourceTexture2(uri); return new ResourceTexture2(uri);
} }
/* /*
* public static ResourceTexture2 createFromPng(final Uri uriTexture) { return * public static ResourceTexture2 createFromPng(final Uri uriTexture) { return
* createFromPng(uriTexture, 1); } * createFromPng(uriTexture, 1); }
* *
* public static ResourceTexture2 createFromPng(final Uri uriTexture, final int * public static ResourceTexture2 createFromPng(final Uri uriTexture, final int
* textureUnit) { ResourceTexture2 resource; Resource resource2; final String * textureUnit) { ResourceTexture2 resource; Resource resource2; final String
* name = uriTexture.getValue(); if (name.isEmpty() == false && name != "---") { * name = uriTexture.getValue(); if (name.isEmpty() == false && name != "---") {
* resource2 = getManager().localKeep(name); } else { * resource2 = getManager().localKeep(name); } else {
* Log.error("Can not create a shader without a filaname"); return null; } if * LOGGER.error("Can not create a shader without a filaname"); return null; } if
* (resource2 != null) { if (resource2 instanceof ResourceTexture2) { * (resource2 != null) { if (resource2 instanceof ResourceTexture2) {
* resource2.keep(); return (ResourceTexture2) resource2; } * resource2.keep(); return (ResourceTexture2) resource2; }
* Log.critical("Request resource file : '" + name + * LOGGER.critical("Request resource file : '" + name +
* "' With the wrong type (dynamic cast error)"); return null; } resource = new * "' With the wrong type (dynamic cast error)"); return null; } resource = new
* ResourceTexture2(uriTexture, textureUnit); final ImageRawData decodedData = * ResourceTexture2(uriTexture, textureUnit); final ImageRawData decodedData =
* ImageLoader.decodePngFile(uriTexture); * ImageLoader.decodePngFile(uriTexture);
@ -133,7 +138,7 @@ public class ResourceTexture2 extends Resource {
// Flush the data to send it at the openGl system // Flush the data to send it at the openGl system
public synchronized void flush() { public synchronized void flush() {
// request to the manager to be call at the next update ... // request to the manager to be call at the next update ...
Log.verbose("Request UPDATE of Element"); LOGGER.trace("Request UPDATE of Element");
Resource.getManager().update(this); Resource.getManager().update(this);
} }
@ -158,7 +163,7 @@ public class ResourceTexture2 extends Resource {
public synchronized void removeContext() { public synchronized void removeContext() {
if (this.loaded) { if (this.loaded) {
// Request remove texture ... // Request remove texture ...
Log.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId); LOGGER.info("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
// TODO Check if we are in the correct thread // TODO Check if we are in the correct thread
OpenGL.glDeleteTextures(this.texId); OpenGL.glDeleteTextures(this.texId);
this.loaded = false; this.loaded = false;
@ -177,16 +182,16 @@ public class ResourceTexture2 extends Resource {
* @param image Image to set. * @param image Image to set.
*/ */
public synchronized void set(final ImageByte image) { public synchronized void set(final ImageByte image) {
Log.debug("Set a new image in a texture:"); LOGGER.debug("Set a new image in a texture:");
Log.debug(" size=" + image.getSize()); LOGGER.debug(" size=" + image.getSize());
this.data = image; this.data = image;
this.realImageSize = this.data.getSize(); this.realImageSize = this.data.getSize();
// Disable compatibility size for embended ... // Disable compatibility size for embended ...
// final Vector2i compatibilityHWSize = new Vector2i(Tools.nextP2(this.realImageSize.x()), Tools.nextP2(this.realImageSize.y())); // final Vector2i compatibilityHWSize = new Vector2i(Tools.nextP2(this.realImageSize.x()), Tools.nextP2(this.realImageSize.y()));
// if (!this.realImageSize.equals(compatibilityHWSize)) { // if (!this.realImageSize.equals(compatibilityHWSize)) {
// Log.warning("RESIZE Image for HArwareCompatibility:" + this.realImageSize + " => " + compatibilityHWSize); // LOGGER.warn("RESIZE Image for HArwareCompatibility:" + this.realImageSize + " => " + compatibilityHWSize);
// this.data.resize(compatibilityHWSize.x(), compatibilityHWSize.y()); // this.data.resize(compatibilityHWSize.x(), compatibilityHWSize.y());
// } // }
flush(); flush();
} }
@ -225,7 +230,7 @@ public class ResourceTexture2 extends Resource {
@Override @Override
public synchronized boolean updateContext() { public synchronized boolean updateContext() {
Log.verbose("updateContext [START]"); LOGGER.trace("updateContext [START]");
//final Steady tic = Steady.now(); //final Steady tic = Steady.now();
/* /*
* TODO : use unlockable synchronized ... if (lock.tryLock() == false) { //Lock * TODO : use unlockable synchronized ... if (lock.tryLock() == false) { //Lock
@ -234,8 +239,9 @@ public class ResourceTexture2 extends Resource {
final int typeObject = this.data.hasAlpha() ? OpenGL.GL_RGBA : OpenGL.GL_RGB; final int typeObject = this.data.hasAlpha() ? OpenGL.GL_RGBA : OpenGL.GL_RGB;
final int sizeObject = OpenGL.GL_UNSIGNED_BYTE; final int sizeObject = OpenGL.GL_UNSIGNED_BYTE;
if (this.loaded) { if (this.loaded) {
if (this.lastTypeObject != typeObject || this.lastSizeObject != sizeObject || !this.lastSize.equals(this.data.getSize())) { if (this.lastTypeObject != typeObject || this.lastSizeObject != sizeObject
Log.warning("TEXTURE: Rm [" + getId() + "] texId=" + this.texId); || !this.lastSize.equals(this.data.getSize())) {
LOGGER.warn("TEXTURE: Rm [" + getId() + "] texId=" + this.texId);
OpenGL.glDeleteTextures(this.texId); OpenGL.glDeleteTextures(this.texId);
this.loaded = false; this.loaded = false;
} }
@ -246,9 +252,11 @@ public class ResourceTexture2 extends Resource {
this.lastSize = this.data.getSize(); this.lastSize = this.data.getSize();
this.lastTypeObject = typeObject; this.lastTypeObject = typeObject;
this.lastSizeObject = sizeObject; this.lastSizeObject = sizeObject;
Log.debug("TEXTURE: add [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize() + " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName()); LOGGER.debug("TEXTURE: add [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize()
+ " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName());
} else { } else {
Log.debug("TEXTURE: update [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize() + " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName()); LOGGER.debug("TEXTURE: update [" + getId() + "]=" + this.data.getSize() + "=>" + this.data.getGPUSize()
+ " OGlId=" + this.texId + " type=" + this.data.getClass().getCanonicalName());
} }
// in all case we set the texture properties : // in all case we set the texture properties :
// TODO check error ??? // TODO check error ???
@ -268,7 +276,7 @@ public class ResourceTexture2 extends Resource {
} }
// glPixelStorei(GLUNPACKALIGNMENT,1); // glPixelStorei(GLUNPACKALIGNMENT,1);
//final Steady toc1 = Steady.now(); //final Steady toc1 = Steady.now();
//Log.verbose(" BIND ==> " + toc1.less(tic)); //LOGGER.trace(" BIND ==> " + toc1.less(tic));
// egami::store(this.data, String("~/texture") + etk::toString(getId()) + ".bmp"); // egami::store(this.data, String("~/texture") + etk::toString(getId()) + ".bmp");
if (!this.loaded) { if (!this.loaded) {
OpenGL.glTexImage2D(0, // Level OpenGL.glTexImage2D(0, // Level
@ -289,7 +297,7 @@ public class ResourceTexture2 extends Resource {
// now the data is loaded // now the data is loaded
this.loaded = true; this.loaded = true;
// final Steady toc = Steady.now(); // final Steady toc = Steady.now();
// Log.error(" updateContext [STOP] ==> " + (toc - toc1)); // LOGGER.error(" updateContext [STOP] ==> " + (toc - toc1));
return true; return true;
} }

View File

@ -4,12 +4,14 @@ import org.atriasoft.egami.ImageByte;
import org.atriasoft.etk.Tools; import org.atriasoft.etk.Tools;
import org.atriasoft.etk.Uri; import org.atriasoft.etk.Uri;
import org.atriasoft.etk.math.Vector2i; import org.atriasoft.etk.math.Vector2i;
import org.atriasoft.gale.internal.Log;
import org.atriasoft.iogami.IOgami; import org.atriasoft.iogami.IOgami;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// TODO : Change tis file name ... // TODO : Change tis file name ...
public class ResourceTextureFile extends ResourceTexture2 { public class ResourceTextureFile extends ResourceTexture2 {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceTextureFile.class);
public static Vector2i sizeAuto = new Vector2i(-1, -1); public static Vector2i sizeAuto = new Vector2i(-1, -1);
public static Vector2i sizeDefault = Vector2i.ZERO; public static Vector2i sizeDefault = Vector2i.ZERO;
@ -32,24 +34,24 @@ public class ResourceTextureFile extends ResourceTexture2 {
* @return pointer on the resource or null if an error occured. * @return pointer on the resource or null if an error occured.
*/ */
public static ResourceTextureFile create(final Uri uri, final Vector2i inSize, final Vector2i sizeRegister) { public static ResourceTextureFile create(final Uri uri, final Vector2i inSize, final Vector2i sizeRegister) {
Log.verbose("KEEP: TextureFile: '" + uri + "' size=" + inSize + " sizeRegister=" + sizeRegister); LOGGER.trace("KEEP: TextureFile: '" + uri + "' size=" + inSize + " sizeRegister=" + sizeRegister);
Vector2i size = inSize; Vector2i size = inSize;
if (uri == null) { if (uri == null) {
return new ResourceTextureFile(); return new ResourceTextureFile();
} }
if (size.x() == 0) { if (size.x() == 0) {
size = size.withX(-1); size = size.withX(-1);
// Log.error("Error Request the image size.x() =0 ???"); // LOGGER.error("Error Request the image size.x() =0 ???");
} }
if (size.y() == 0) { if (size.y() == 0) {
size = size.withY(-1); size = size.withY(-1);
// Log.error("Error Request the image size.y() =0 ???"); // LOGGER.error("Error Request the image size.y() =0 ???");
} }
if (!uri.getExtention().toLowerCase().contentEquals("svg")) { if (!uri.getExtention().toLowerCase().contentEquals("svg")) {
size = ResourceTextureFile.sizeAuto; size = ResourceTextureFile.sizeAuto;
} }
if (size.x() > 0 && size.y() > 0) { if (size.x() > 0 && size.y() > 0) {
Log.verbose(" == > specific size : " + size); LOGGER.trace(" == > specific size : " + size);
size = new Vector2i(Tools.nextP2(size.x()), Tools.nextP2(size.y())); size = new Vector2i(Tools.nextP2(size.x()), Tools.nextP2(size.y()));
if (!sizeRegister.equals(ResourceTextureFile.sizeAuto)) { if (!sizeRegister.equals(ResourceTextureFile.sizeAuto)) {
if (!sizeRegister.equals(ResourceTextureFile.sizeDefault)) { if (!sizeRegister.equals(ResourceTextureFile.sizeDefault)) {
@ -59,19 +61,20 @@ public class ResourceTextureFile extends ResourceTexture2 {
} }
} }
Log.verbose("KEEP: TextureFile: '" + uri + "' new size=" + size); LOGGER.trace("KEEP: TextureFile: '" + uri + "' new size=" + size);
final Resource object2 = Resource.getManager().localKeep(uri.toString()); final Resource object2 = Resource.getManager().localKeep(uri.toString());
if (object2 != null) { if (object2 != null) {
if (object2 instanceof ResourceTextureFile out) { if (object2 instanceof final ResourceTextureFile out) {
object2.keep(); object2.keep();
return out; return out;
} }
Log.critical("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)"); LOGGER.error("Request resource file : '" + uri + "' With the wrong type (dynamic cast error)");
System.exit(-1);
return null; return null;
} }
Log.debug("CREATE: TextureFile: '" + uri + "' size=" + size); LOGGER.debug("CREATE: TextureFile: '" + uri + "' size=" + size);
// need to crate a new one ... // need to crate a new one ...
ResourceTextureFile object = new ResourceTextureFile(uri.toString(), uri, size); final ResourceTextureFile object = new ResourceTextureFile(uri.toString(), uri, size);
Resource.getManager().localAdd(object); Resource.getManager().localAdd(object);
return object; return object;
} }
@ -80,10 +83,10 @@ public class ResourceTextureFile extends ResourceTexture2 {
protected ResourceTextureFile(final String genName, final Uri uri, final Vector2i size) { protected ResourceTextureFile(final String genName, final Uri uri, final Vector2i size) {
super(genName); super(genName);
Log.debug("create a new resource::Image : genName=" + genName + " uri=" + uri + " size=" + size); LOGGER.debug("create a new resource::Image : genName=" + genName + " uri=" + uri + " size=" + size);
final ImageByte tmp = IOgami.load(uri, size); final ImageByte tmp = IOgami.load(uri, size);
if (tmp == null) { if (tmp == null) {
Log.error("Can not load the file : " + uri); LOGGER.error("Can not load the file : " + uri);
return; return;
} }
set(tmp); set(tmp);

View File

@ -12,99 +12,118 @@ import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.RenderMode; import org.atriasoft.gale.backend3d.OpenGL.RenderMode;
import org.atriasoft.gale.backend3d.OpenGL.Usage; import org.atriasoft.gale.backend3d.OpenGL.Usage;
import org.atriasoft.gale.internal.Log;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import models.RawModel; //import models.RawModel;
public class ResourceVirtualArrayObject extends Resource { public class ResourceVirtualArrayObject extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceVirtualArrayObject.class);
public static final int INDICE_VBO_POSITIONS = 0; public static final int INDICE_VBO_POSITIONS = 0;
public static final int INDICE_VBO_TEXTURE_COORDINATES = 1; public static final int INDICE_VBO_TEXTURE_COORDINATES = 1;
public static final int INDICE_VBO_NORMALS = 2; public static final int INDICE_VBO_NORMALS = 2;
public static final int INDICE_VBO_COLORS = 3; public static final int INDICE_VBO_COLORS = 3;
public static int[] convertIntegers(final List<Integer> integers) { public static int[] convertIntegers(final List<Integer> integers) {
int[] ret = new int[integers.size()]; final int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator(); final Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++) { for (int i = 0; i < ret.length; i++) {
ret[i] = iterator.next().intValue(); ret[i] = iterator.next().intValue();
} }
return ret; return ret;
} }
public static ResourceVirtualArrayObject create(final float[] positions, final float[] colors, final float[] textureCoordinates, final float[] normals, final int[] indices) { public static ResourceVirtualArrayObject create(
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, textureCoordinates, normals, indices, indices.length); 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);
Resource.getManager().localAdd(resource); Resource.getManager().localAdd(resource);
return resource; return resource;
} }
public static ResourceVirtualArrayObject create(final float[] positions, final float[] textureCoordinates, final float[] normals, final int[] indices) { public static ResourceVirtualArrayObject create(
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, textureCoordinates, normals, indices, indices.length); final float[] positions,
final float[] textureCoordinates,
final float[] normals,
final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, textureCoordinates,
normals, indices, indices.length);
Resource.getManager().localAdd(resource); Resource.getManager().localAdd(resource);
return resource; return resource;
} }
public static ResourceVirtualArrayObject create(final float[] positions, final float[] colors, final int[] indices) { public static ResourceVirtualArrayObject create(
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, null, null, indices, indices.length); final float[] positions,
final float[] colors,
final int[] indices) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, colors, null, null,
indices, indices.length);
Resource.getManager().localAdd(resource); Resource.getManager().localAdd(resource);
return resource; return resource;
} }
public static ResourceVirtualArrayObject create(final float[] positions, final int dimentions) { public static ResourceVirtualArrayObject create(final float[] positions, final int dimentions) {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, null, null, null, positions.length / dimentions); final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(positions, null, null, null, null,
positions.length / dimentions);
Resource.getManager().localAdd(resource); Resource.getManager().localAdd(resource);
return resource; return resource;
} }
public static ResourceVirtualArrayObject createDynamic() { public static ResourceVirtualArrayObject createDynamic() {
final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject(); final ResourceVirtualArrayObject resource = new ResourceVirtualArrayObject();
Resource.getManager().localAdd(resource); Resource.getManager().localAdd(resource);
return resource; return resource;
} }
public static FloatBuffer storeDataInFloatBuffer(final float[] data) { public static FloatBuffer storeDataInFloatBuffer(final float[] data) {
final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length); final FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data); buffer.put(data);
buffer.flip(); buffer.flip();
return buffer; return buffer;
} }
public static IntBuffer storeDataInIntBuffer(final int[] data) { public static IntBuffer storeDataInIntBuffer(final int[] data) {
final IntBuffer buffer = BufferUtils.createIntBuffer(data.length); final IntBuffer buffer = BufferUtils.createIntBuffer(data.length);
buffer.put(data); buffer.put(data);
buffer.flip(); buffer.flip();
return buffer; return buffer;
} }
private boolean dynamic = false; private boolean dynamic = false;
private int vaoID = -1; private int vaoID = -1;
private boolean exist = false; //!< This data is availlable in the Graphic card private boolean exist = false; //!< This data is availlable in the Graphic card
private final List<Integer> vbo = new ArrayList<>(); private final List<Integer> vbo = new ArrayList<>();
Object positions = null; Object positions = null;
Object colors = null; Object colors = null;
Object textureCoordinates = null; Object textureCoordinates = null;
Object normals = null; Object normals = null;
int[] indices = null; int[] indices = null;
int vertexCount = -1; int vertexCount = -1;
protected ResourceVirtualArrayObject() { protected ResourceVirtualArrayObject() {
this.resourceLevel = 3; this.resourceLevel = 3;
this.dynamic = true; this.dynamic = true;
Log.debug("OGL: load VBO count (dynamic)"); LOGGER.debug("OGL: load VBO count (dynamic)");
} }
protected ResourceVirtualArrayObject(final float[] positions, final float[] colors, final float[] textureCoordinates, final float[] normals, final int[] indices, final int vertexCount) { protected ResourceVirtualArrayObject(final float[] positions, final float[] colors,
final float[] textureCoordinates, final float[] normals, final int[] indices, final int vertexCount) {
this.resourceLevel = 3; this.resourceLevel = 3;
this.positions = positions; this.positions = positions;
this.colors = colors; this.colors = colors;
@ -112,9 +131,9 @@ public class ResourceVirtualArrayObject extends Resource {
this.normals = normals; this.normals = normals;
this.indices = indices; this.indices = indices;
this.vertexCount = vertexCount; this.vertexCount = vertexCount;
Log.debug("OGL: load VBO count"); LOGGER.debug("OGL: load VBO count");
} }
public void bindForRendering() { public void bindForRendering() {
if (!this.exist) { if (!this.exist) {
return; return;
@ -122,7 +141,7 @@ public class ResourceVirtualArrayObject extends Resource {
GL30.glBindVertexArray(this.vaoID); GL30.glBindVertexArray(this.vaoID);
if (this.positions != null) { if (this.positions != null) {
GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS); GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS);
//Log.info("unbind POSITION"); //LOGGER.info("unbind POSITION");
} }
if (this.textureCoordinates != null) { if (this.textureCoordinates != null) {
GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES); GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES);
@ -134,7 +153,7 @@ public class ResourceVirtualArrayObject extends Resource {
GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_COLORS); GL20.glEnableVertexAttribArray(ResourceVirtualArrayObject.INDICE_VBO_COLORS);
} }
} }
private void bindIndicesBuffer(final int[] indices) { private void bindIndicesBuffer(final int[] indices) {
final int vboId = OpenGL.genBuffers(); final int vboId = OpenGL.genBuffers();
this.vbo.add(vboId); this.vbo.add(vboId);
@ -146,7 +165,7 @@ public class ResourceVirtualArrayObject extends Resource {
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
} }
} }
/** /**
* Destructor of this VBO. * Destructor of this VBO.
*/ */
@ -154,12 +173,12 @@ public class ResourceVirtualArrayObject extends Resource {
public void cleanUp() { public void cleanUp() {
removeContext(); removeContext();
} }
/** /**
* clear buffers * clear buffers
*/ */
public void clear() { public void clear() {
//Log.verbose(" Clear: [" + getId() + "] '" + getName() + "' (size=" + buffer.get(0).length + ")"); //LOGGER.trace(" Clear: [" + getId() + "] '" + getName() + "' (size=" + buffer.get(0).length + ")");
this.positions = null; this.positions = null;
this.colors = null; this.colors = null;
this.textureCoordinates = null; this.textureCoordinates = null;
@ -167,22 +186,22 @@ public class ResourceVirtualArrayObject extends Resource {
this.indices = null; this.indices = null;
this.vertexCount = -1; this.vertexCount = -1;
} }
private void createVAO() { private void createVAO() {
Log.verbose("create VAO..."); LOGGER.trace("create VAO...");
this.vaoID = GL30.glGenVertexArrays(); this.vaoID = GL30.glGenVertexArrays();
GL30.glBindVertexArray(this.vaoID); GL30.glBindVertexArray(this.vaoID);
} }
/** /**
* Send the data to the graphic card. * Send the data to the graphic card.
*/ */
public void flush() { public void flush() {
// request to the manager to be call at the next update ... // request to the manager to be call at the next update ...
Resource.getManager().update(this); Resource.getManager().update(this);
Log.verbose("Request flush of VAO: [" + getId() + "] '" + getName() + "'"); LOGGER.trace("Request flush of VAO: [" + getId() + "] '" + getName() + "'");
} }
/** /**
* get the real openGL ID. * get the real openGL ID.
* @return the Ogl id reference of this VBO. * @return the Ogl id reference of this VBO.
@ -190,63 +209,65 @@ public class ResourceVirtualArrayObject extends Resource {
public int getGLID() { public int getGLID() {
return this.vaoID; return this.vaoID;
} }
public int getVertexCount() { public int getVertexCount() {
return this.vertexCount; return this.vertexCount;
} }
public void loadAgainToVAO() { public void loadAgainToVAO() {
GL30.glBindVertexArray(this.vaoID); GL30.glBindVertexArray(this.vaoID);
Log.verbose("push VAO: [" + getId() + "] '" + getName() + "'"); LOGGER.trace("push VAO: [" + getId() + "] '" + getName() + "'");
if (this.indices != null) { if (this.indices != null) {
Log.verbose("Set indices"); LOGGER.trace("Set indices");
bindIndicesBuffer(this.indices); bindIndicesBuffer(this.indices);
} }
if (this.positions != null) { if (this.positions != null) {
Log.verbose("Set positions"); LOGGER.trace("Set positions");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, 3, this.positions); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, 3, this.positions);
} }
if (this.textureCoordinates != null) { if (this.textureCoordinates != null) {
Log.verbose("Set textureCoordinates"); LOGGER.trace("Set textureCoordinates");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2, this.textureCoordinates); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2,
this.textureCoordinates);
} }
if (this.normals != null) { if (this.normals != null) {
Log.verbose("Set normals"); LOGGER.trace("Set normals");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_NORMALS, 3, this.normals); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_NORMALS, 3, this.normals);
} }
if (this.colors != null) { if (this.colors != null) {
Log.verbose("Set colors"); LOGGER.trace("Set colors");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_COLORS, 4, this.colors); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_COLORS, 4, this.colors);
} }
unbindVAO(); unbindVAO();
} }
public void loadToVAO() { public void loadToVAO() {
createVAO(); createVAO();
Log.verbose("push VAO: [" + getId() + "] '" + getName() + "'"); LOGGER.trace("push VAO: [" + getId() + "] '" + getName() + "'");
if (this.indices != null) { if (this.indices != null) {
Log.verbose("Set indices"); LOGGER.trace("Set indices");
bindIndicesBuffer(this.indices); bindIndicesBuffer(this.indices);
} }
if (this.positions != null) { if (this.positions != null) {
Log.verbose("Set positions"); LOGGER.trace("Set positions");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, 3, this.positions); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_POSITIONS, 3, this.positions);
} }
if (this.textureCoordinates != null) { if (this.textureCoordinates != null) {
Log.verbose("Set textureCoordinates"); LOGGER.trace("Set textureCoordinates");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2, this.textureCoordinates); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_TEXTURE_COORDINATES, 2,
this.textureCoordinates);
} }
if (this.normals != null) { if (this.normals != null) {
Log.verbose("Set normals"); LOGGER.trace("Set normals");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_NORMALS, 3, this.normals); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_NORMALS, 3, this.normals);
} }
if (this.colors != null) { if (this.colors != null) {
Log.verbose("Set colors"); LOGGER.trace("Set colors");
storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_COLORS, 4, this.colors); storeDataInAttributeList(ResourceVirtualArrayObject.INDICE_VBO_COLORS, 4, this.colors);
} }
unbindVAO(); unbindVAO();
} }
/** /**
* Relode the shader from the file. used when a request of resouces reload is done. * 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. * @note this is really usefull when we tested the new themes or shader developpements.
@ -256,7 +277,7 @@ public class ResourceVirtualArrayObject extends Resource {
removeContext(); removeContext();
updateContext(); updateContext();
} }
/** /**
* remove the data from the opengl context. * remove the data from the opengl context.
*/ */
@ -267,7 +288,7 @@ public class ResourceVirtualArrayObject extends Resource {
this.exist = false; this.exist = false;
} }
} }
/** /**
* Special android spec! It inform us that all context is removed and after notify us... * Special android spec! It inform us that all context is removed and after notify us...
*/ */
@ -278,84 +299,84 @@ public class ResourceVirtualArrayObject extends Resource {
// this.vbo[iii] = 0; // this.vbo[iii] = 0;
// } // }
} }
public void render(final RenderMode mode) { public void render(final RenderMode mode) {
Log.verbose("request rendering indices : " + this.vertexCount); LOGGER.trace("request rendering indices : " + this.vertexCount);
OpenGL.drawElements(mode, this.vertexCount); OpenGL.drawElements(mode, this.vertexCount);
} }
public void render(final RenderMode mode, final int start, final int stop) { public void render(final RenderMode mode, final int start, final int stop) {
OpenGL.drawArrays(mode, start, stop); OpenGL.drawArrays(mode, start, stop);
} }
public void renderArrays(final RenderMode mode) { public void renderArrays(final RenderMode mode) {
Log.verbose("request rendering direct : " + this.vertexCount); LOGGER.trace("request rendering direct : " + this.vertexCount);
OpenGL.drawArrays(mode, 0, this.vertexCount); OpenGL.drawArrays(mode, 0, this.vertexCount);
} }
public void setColors(final Color[] colors) { public void setColors(final Color[] colors) {
this.colors = colors; this.colors = colors;
} }
public void setColors(final float[] colors) { public void setColors(final float[] colors) {
this.colors = colors; this.colors = colors;
} }
public void setColors(final List<Color> colors) { public void setColors(final List<Color> colors) {
setColors(colors.toArray(Color[]::new)); setColors(colors.toArray(Color[]::new));
} }
public void setIndices(final int[] indices) { public void setIndices(final int[] indices) {
this.indices = indices; this.indices = indices;
} }
public void setIndices(final List<Integer> indices) { public void setIndices(final List<Integer> indices) {
this.indices = ResourceVirtualArrayObject.convertIntegers(indices); this.indices = ResourceVirtualArrayObject.convertIntegers(indices);
this.vertexCount = this.indices.length; this.vertexCount = this.indices.length;
} }
public void setNormals(final float[] normals) { public void setNormals(final float[] normals) {
this.normals = normals; this.normals = normals;
} }
public void setNormals(final List<Vector3f> normals) { public void setNormals(final List<Vector3f> normals) {
setNormals(normals.toArray(Vector3f[]::new)); setNormals(normals.toArray(Vector3f[]::new));
} }
public void setNormals(final Vector3f[] normals) { public void setNormals(final Vector3f[] normals) {
this.normals = normals; this.normals = normals;
} }
public void setPosition(final float[] positions) { public void setPosition(final float[] positions) {
this.positions = positions; this.positions = positions;
} }
public void setPosition(final List<Vector3f> outPosition) { public void setPosition(final List<Vector3f> outPosition) {
setPosition(outPosition.toArray(Vector3f[]::new)); setPosition(outPosition.toArray(Vector3f[]::new));
} }
public void setPosition(final Vector3f[] positions) { public void setPosition(final Vector3f[] positions) {
this.positions = positions; this.positions = positions;
} }
public void setTextureCoordinate(final float[] textureCoordinates) { public void setTextureCoordinate(final float[] textureCoordinates) {
this.textureCoordinates = textureCoordinates; this.textureCoordinates = textureCoordinates;
} }
public void setTextureCoordinate(final List<Vector2f> outTexturePosition) { public void setTextureCoordinate(final List<Vector2f> outTexturePosition) {
setTextureCoordinate(outTexturePosition.toArray(Vector2f[]::new)); setTextureCoordinate(outTexturePosition.toArray(Vector2f[]::new));
} }
public void setTextureCoordinate(final Vector2f[] textureCoordinates) { public void setTextureCoordinate(final Vector2f[] textureCoordinates) {
this.textureCoordinates = textureCoordinates; this.textureCoordinates = textureCoordinates;
} }
public void setVertexCount(final int vertexCount) { public void setVertexCount(final int vertexCount) {
this.vertexCount = vertexCount; this.vertexCount = vertexCount;
} }
private void storeDataInAttributeList(final int attributeNumber, final int coordinateSize, final Object data) { private void storeDataInAttributeList(final int attributeNumber, final int coordinateSize, final Object data) {
final int vboID = GL15.glGenBuffers(); final int vboID = GL15.glGenBuffers();
this.vbo.add(vboID); this.vbo.add(vboID);
@ -365,23 +386,23 @@ public class ResourceVirtualArrayObject extends Resource {
usage = Usage.streamDraw; usage = Usage.streamDraw;
} }
// select the buffer to set data inside it ... // select the buffer to set data inside it ...
if (data instanceof float[] buffer) { if (data instanceof final float[] buffer) {
OpenGL.bufferData(buffer, usage); OpenGL.bufferData(buffer, usage);
} else if (data instanceof int[] buffer) { } else if (data instanceof final int[] buffer) {
OpenGL.bufferData(buffer, usage); OpenGL.bufferData(buffer, usage);
} else if (data instanceof Vector2f[] buffer) { } else if (data instanceof final Vector2f[] buffer) {
OpenGL.bufferData(buffer, usage); OpenGL.bufferData(buffer, usage);
} else if (data instanceof Vector3f[] buffer) { } else if (data instanceof final Vector3f[] buffer) {
OpenGL.bufferData(buffer, usage); OpenGL.bufferData(buffer, usage);
} else if (data instanceof Color[] buffer) { } else if (data instanceof final Color[] buffer) {
OpenGL.bufferData(buffer, usage); OpenGL.bufferData(buffer, usage);
} else { } else {
Log.error("Not managed VBO model : " + data.getClass().getCanonicalName()); LOGGER.error("Not managed VBO model : " + data.getClass().getCanonicalName());
} }
GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0); GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
} }
public void unBindForRendering() { public void unBindForRendering() {
if (!this.exist) { if (!this.exist) {
return; return;
@ -400,33 +421,34 @@ public class ResourceVirtualArrayObject extends Resource {
} }
GL30.glBindVertexArray(0); GL30.glBindVertexArray(0);
} }
private void unbindVAO() { private void unbindVAO() {
Log.verbose("Unbind VAO ..."); LOGGER.trace("Unbind VAO ...");
GL30.glBindVertexArray(0); GL30.glBindVertexArray(0);
} }
/** /**
* This load/reload the data in the opengl context, needed when removed previously. * This load/reload the data in the opengl context, needed when removed previously.
*/ */
@Override @Override
public boolean updateContext() { public boolean updateContext() {
Log.verbose(" Start: [" + getId() + "] '" + getName() + "' (size=" + this.vertexCount + ") ********************************"); LOGGER.trace(" Start: [" + getId() + "] '" + getName() + "' (size=" + this.vertexCount
+ ") ********************************");
if (!this.exist) { if (!this.exist) {
Log.verbose(" ==> ALLOCATE new handle"); LOGGER.trace(" ==> ALLOCATE new handle");
// Allocate and assign a Vertex Array Object to our handle // Allocate and assign a Vertex Array Object to our handle
loadToVAO(); loadToVAO();
} else { } else {
// Update VAO (only for dynamic: // Update VAO (only for dynamic:
if (!this.dynamic) { if (!this.dynamic) {
Log.error(" Request update a VAO with a static buffer !!!" + this.name); LOGGER.error(" Request update a VAO with a static buffer !!!" + this.name);
} }
loadAgainToVAO(); loadAgainToVAO();
} }
this.exist = true; this.exist = true;
Log.verbose(" Stop: [" + getId() + "] '" + getName() + "'"); LOGGER.trace(" Stop: [" + getId() + "] '" + getName() + "'");
return true; return true;
} }
} }

View File

@ -12,21 +12,23 @@ import org.atriasoft.etk.math.Vector2f;
import org.atriasoft.etk.math.Vector3f; import org.atriasoft.etk.math.Vector3f;
import org.atriasoft.gale.backend3d.OpenGL; import org.atriasoft.gale.backend3d.OpenGL;
import org.atriasoft.gale.backend3d.OpenGL.Usage; import org.atriasoft.gale.backend3d.OpenGL.Usage;
import org.atriasoft.gale.internal.Log; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* ResourceVirtualBufferObject is a specific resources for opengl, this load the data directly in the graphic card ad keep these inside * ResourceVirtualBufferObject is a specific resources for opengl, this load the data directly in the graphic card ad keep these inside
*/ */
public class ResourceVirtualBufferObject extends Resource { public class ResourceVirtualBufferObject extends Resource {
static final Logger LOGGER = LoggerFactory.getLogger(ResourceVirtualBufferObject.class);
public static ResourceVirtualBufferObject create(final int count) { public static ResourceVirtualBufferObject create(final int count) {
return new ResourceVirtualBufferObject(count); return new ResourceVirtualBufferObject(count);
} }
private boolean exist = false; //!< This data is available in the Graphic card private boolean exist = false; //!< This data is available in the Graphic card
private final int[] vbo; //!< openGl ID of this VBO private final int[] vbo; //!< openGl ID of this VBO
private final Object[] buffer; //!< data that is available in the VBO system ... private final Object[] buffer; //!< data that is available in the VBO system ...
/** /**
* Constructor of this VBO. * Constructor of this VBO.
* @param accesMode Access mode : ??? * @param accesMode Access mode : ???
@ -34,10 +36,10 @@ public class ResourceVirtualBufferObject extends Resource {
protected ResourceVirtualBufferObject(final int number) { protected ResourceVirtualBufferObject(final int number) {
this.vbo = new int[number]; // 0 this.vbo = new int[number]; // 0
this.buffer = new Object[number]; this.buffer = new Object[number];
Log.debug("OGL : load VBO count=\"" + number + "\""); LOGGER.debug("OGL : load VBO count=\"" + number + "\"");
this.resourceLevel = 3; this.resourceLevel = 3;
} }
public int bufferSize(final int vboidcoord) { public int bufferSize(final int vboidcoord) {
if (this.buffer[vboidcoord] != null) { if (this.buffer[vboidcoord] != null) {
// select the buffer to set data inside it ... // select the buffer to set data inside it ...
@ -53,35 +55,35 @@ public class ResourceVirtualBufferObject extends Resource {
} else if (this.buffer[vboidcoord] instanceof Color[]) { } else if (this.buffer[vboidcoord] instanceof Color[]) {
return ((Color[]) (this.buffer[vboidcoord])).length; return ((Color[]) (this.buffer[vboidcoord])).length;
} else { } else {
Log.error("Not managed VBO model : " + this.buffer[vboidcoord].getClass().getCanonicalName()); LOGGER.error("Not managed VBO model : " + this.buffer[vboidcoord].getClass().getCanonicalName());
} }
} }
return 0; return 0;
} }
@Override @Override
public void cleanUp() { public void cleanUp() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/** /**
* clear buffers * clear buffers
*/ */
public void clear() { public void clear() {
Log.verbose(" Clear: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")"); LOGGER.trace(" Clear: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")");
// DO not clear the this.vbo indexed in the graphic cards ... // DO not clear the this.vbo indexed in the graphic cards ...
Arrays.fill(this.buffer, null); Arrays.fill(this.buffer, null);
} }
/** /**
* Send the data to the graphic card. * Send the data to the graphic card.
*/ */
public synchronized void flush() { public synchronized void flush() {
// request to the manager to be call at the next update ... // request to the manager to be call at the next update ...
Resource.getManager().update(this); Resource.getManager().update(this);
Log.verbose("Request flush of VBO: [" + getId() + "] '" + getName() + "'"); LOGGER.trace("Request flush of VBO: [" + getId() + "] '" + getName() + "'");
} }
public int getElementSize(final int index) { public int getElementSize(final int index) {
if (this.buffer[index] != null) { if (this.buffer[index] != null) {
// select the buffer to set data inside it ... // select the buffer to set data inside it ...
@ -97,12 +99,12 @@ public class ResourceVirtualBufferObject extends Resource {
} else if (this.buffer[index] instanceof Color[]) { } else if (this.buffer[index] instanceof Color[]) {
return 4; return 4;
} else { } else {
Log.error("Not managed VBO model : " + this.buffer[index].getClass().getCanonicalName()); LOGGER.error("Not managed VBO model : " + this.buffer[index].getClass().getCanonicalName());
} }
} }
return 1; return 1;
} }
/** /**
* get the real openGL ID. * get the real openGL ID.
* @return the Ogl id reference of this VBO. * @return the Ogl id reference of this VBO.
@ -110,7 +112,7 @@ public class ResourceVirtualBufferObject extends Resource {
public int getOpenGlId(final int id) { public int getOpenGlId(final int id) {
return this.vbo[id]; return this.vbo[id];
} }
/** /**
* Relode the shader from the file. used when a request of resouces reload is done. * 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. * @note this is really usefull when we tested the new themes or shader developpements.
@ -120,7 +122,7 @@ public class ResourceVirtualBufferObject extends Resource {
removeContext(); removeContext();
updateContext(); updateContext();
} }
/** /**
* remove the data from the opengl context. * remove the data from the opengl context.
*/ */
@ -131,7 +133,7 @@ public class ResourceVirtualBufferObject extends Resource {
this.exist = false; this.exist = false;
} }
} }
/** /**
* Special android spec! It inform us that all context is removed and after notify us... * Special android spec! It inform us that all context is removed and after notify us...
*/ */
@ -140,56 +142,58 @@ public class ResourceVirtualBufferObject extends Resource {
this.exist = false; this.exist = false;
Arrays.fill(this.vbo, 0); Arrays.fill(this.vbo, 0);
} }
/** /**
* get the data from the graphic card. * get the data from the graphic card.
*/ */
public void retreiveData() { public void retreiveData() {
Log.error("TODO ... "); LOGGER.error("TODO ... ");
} }
public void setVboData(final int vboId, final Color[] data) { public void setVboData(final int vboId, final Color[] data) {
this.buffer[vboId] = data; this.buffer[vboId] = data;
} }
public void setVboData(final int vboId, final float[] data) { public void setVboData(final int vboId, final float[] data) {
this.buffer[vboId] = data; this.buffer[vboId] = data;
} }
public void setVboData(final int vboId, final int[] data) { public void setVboData(final int vboId, final int[] data) {
this.buffer[vboId] = data; this.buffer[vboId] = data;
} }
public void setVboData(final int vboId, final Vector2f[] data) { public void setVboData(final int vboId, final Vector2f[] data) {
this.buffer[vboId] = data; this.buffer[vboId] = data;
} }
public void setVboData(final int vboId, final Vector3f[] data) { public void setVboData(final int vboId, final Vector3f[] data) {
this.buffer[vboId] = data; this.buffer[vboId] = data;
} }
/** /**
* This load/reload the data in the opengl context, needed when removed previously. * This load/reload the data in the opengl context, needed when removed previously.
*/ */
@Override @Override
public synchronized boolean updateContext() { public synchronized boolean updateContext() {
Log.verbose("updateContext (VBO Start: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")"); LOGGER.trace(
"updateContext (VBO Start: [" + getId() + "] '" + getName() + "' (size=" + this.buffer.length + ")");
/* /*
if (lock.tryLock() == false) { if (lock.tryLock() == false) {
//Lock error ==> try later ... //Lock error ==> try later ...
Log.warning(" ==> Lock error on VBO"); LOGGER.warn(" ==> Lock error on VBO");
return false; return false;
} }
*/ */
if (!this.exist) { if (!this.exist) {
Log.debug(" ==> ALLOCATE new handle"); LOGGER.debug(" ==> ALLOCATE new handle");
// Allocate and assign a Vertex Array Object to our handle // Allocate and assign a Vertex Array Object to our handle
OpenGL.genBuffers(this.vbo); OpenGL.genBuffers(this.vbo);
} }
this.exist = true; this.exist = true;
for (int iii = 0; iii < this.vbo.length; iii++) { for (int iii = 0; iii < this.vbo.length; iii++) {
if (this.buffer[iii] != null) { if (this.buffer[iii] != null) {
Log.verbose("VBO : add [" + getId() + "]=" + this.buffer[iii].getClass().getCanonicalName() + "*sizeof(float) OGl_Id=" + this.vbo[iii]); LOGGER.trace("VBO : add [" + getId() + "]=" + this.buffer[iii].getClass().getCanonicalName()
+ "*sizeof(float) OGl_Id=" + this.vbo[iii]);
OpenGL.bindBuffer(this.vbo[iii]); OpenGL.bindBuffer(this.vbo[iii]);
// select the buffer to set data inside it ... // select the buffer to set data inside it ...
if (this.buffer[iii] instanceof float[]) { if (this.buffer[iii] instanceof float[]) {
@ -203,13 +207,13 @@ public class ResourceVirtualBufferObject extends Resource {
} else if (this.buffer[iii] instanceof Color[]) { } else if (this.buffer[iii] instanceof Color[]) {
OpenGL.bufferData((Color[]) (this.buffer[iii]), Usage.streamDraw); OpenGL.bufferData((Color[]) (this.buffer[iii]), Usage.streamDraw);
} else { } else {
Log.error("Not managed VBO model : " + this.buffer[iii].getClass().getCanonicalName()); LOGGER.error("Not managed VBO model : " + this.buffer[iii].getClass().getCanonicalName());
} }
} }
} }
// un-bind it to permet to have no error in the next display ... // un-bind it to permet to have no error in the next display ...
OpenGL.unbindBuffer(); OpenGL.unbindBuffer();
Log.verbose(" Stop: [" + getId() + "] '" + getName() + "'"); LOGGER.trace(" Stop: [" + getId() + "] '" + getName() + "'");
return true; return true;
} }
} }

View File

@ -14,23 +14,26 @@ import org.atriasoft.gale.key.KeyStatus;
import org.atriasoft.gale.key.KeyType; import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceProgram; import org.atriasoft.gale.resource.ResourceProgram;
import org.atriasoft.gale.resource.ResourceVirtualArrayObject; import org.atriasoft.gale.resource.ResourceVirtualArrayObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Sample1Application extends GaleApplication { public class Sample1Application extends GaleApplication {
static final Logger LOGGER = LoggerFactory.getLogger(Sample1Application.class);
//float[] vertices = { 0.2f, 0.1f, 0.0f, 0.3f, 0.4f, 0.0f, 0.1f, 0.4f, 0.0f }; //float[] vertices = { 0.2f, 0.1f, 0.0f, 0.3f, 0.4f, 0.0f, 0.1f, 0.4f, 0.0f };
private static final float[] VERTICES = { -0.5f, -0.5f, -1.0f, 0.0f, 0.5f, -1.0f, 0.5f, -0.5f, -1.0f }; private static final float[] VERTICES = { -0.5f, -0.5f, -1.0f, 0.0f, 0.5f, -1.0f, 0.5f, -0.5f, -1.0f };
private static final float[] COLORS = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, }; private static final float[] COLORS = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, };
private static final int[] INDICES = { 0, 1, 2 }; private static final int[] INDICES = { 0, 1, 2 };
private static final boolean TEST_STATIC_MODE = false; private static final boolean TEST_STATIC_MODE = false;
private ResourceProgram oGLprogram; private ResourceProgram oGLprogram;
private int oGLMatrixTransformation; private int oGLMatrixTransformation;
private int oGLMatrixProjection; private int oGLMatrixProjection;
private int oGLMatrixView; private int oGLMatrixView;
private float angle; private float angle;
private ResourceVirtualArrayObject verticesVBO; private ResourceVirtualArrayObject verticesVBO;
@Override @Override
public void onCreate(final GaleContext context) { public void onCreate(final GaleContext context) {
//setSize(new Vector2f(800, 600)); //setSize(new Vector2f(800, 600));
@ -41,7 +44,7 @@ public class Sample1Application extends GaleApplication {
this.oGLMatrixProjection = this.oGLprogram.getUniform("in_matrixProjection"); this.oGLMatrixProjection = this.oGLprogram.getUniform("in_matrixProjection");
this.oGLMatrixView = this.oGLprogram.getUniform("in_matrixView"); this.oGLMatrixView = this.oGLprogram.getUniform("in_matrixView");
} }
// this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer // this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer
if (TEST_STATIC_MODE) { if (TEST_STATIC_MODE) {
this.verticesVBO = ResourceVirtualArrayObject.create(VERTICES, COLORS, INDICES); this.verticesVBO = ResourceVirtualArrayObject.create(VERTICES, COLORS, INDICES);
@ -52,49 +55,49 @@ public class Sample1Application extends GaleApplication {
this.verticesVBO.setName("[VBO] of basic SAMPLE"); this.verticesVBO.setName("[VBO] of basic SAMPLE");
// update all the VBO elements ... // update all the VBO elements ...
this.verticesVBO.flush(); this.verticesVBO.flush();
Log.info("==> Init APPL (END)"); LOGGER.info("==> Init APPL (END)");
} }
@Override @Override
public void onDraw(final GaleContext context) { public void onDraw(final GaleContext context) {
this.angle += 0.01; this.angle += 0.01;
//Log.info("==> appl Draw ..."); //LOGGER.info("==> appl Draw ...");
Vector2f size = getSize(); final Vector2f size = getSize();
// set the basic openGL view port: (position drawed in the windows) // set the basic openGL view port: (position drawed in the windows)
OpenGL.setViewPort(Vector2f.ZERO, size); OpenGL.setViewPort(Vector2f.ZERO, size);
// Clear all the stacked matrix ... // Clear all the stacked matrix ...
OpenGL.setBasicMatrix(Matrix4f.IDENTITY); OpenGL.setBasicMatrix(Matrix4f.IDENTITY);
// clear background // clear background
Color bgColor = Color.CYAN; final Color bgColor = Color.CYAN;
OpenGL.clearColor(bgColor); OpenGL.clearColor(bgColor);
// real clear request: // real clear request:
OpenGL.clear(OpenGL.ClearFlag.clearFlag_colorBuffer); OpenGL.clear(OpenGL.ClearFlag.clearFlag_colorBuffer);
// create a local matrix environment. // create a local matrix environment.
OpenGL.push(); OpenGL.push();
Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-getAspectRatio(), getAspectRatio(), -1, 1, -50, 50); final Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-getAspectRatio(), getAspectRatio(), -1, 1, -50, 50);
//Matrix4f tmpProjection = Matrix4f.IDENTITY; //Matrix4f tmpProjection = Matrix4f.IDENTITY;
// set internal matrix system: // set internal matrix system:
OpenGL.setMatrix(tmpProjection); OpenGL.setMatrix(tmpProjection);
if (this.oGLprogram == null) { if (this.oGLprogram == null) {
Log.info("No shader ..."); LOGGER.info("No shader ...");
return; return;
} }
//EWOL_DEBUG(" display " + this.coord.size() + " elements" ); //EWOL_DEBUG(" display " + this.coord.size() + " elements" );
this.oGLprogram.use(); this.oGLprogram.use();
// set Matrix: translation/positionMatrix // set Matrix: translation/positionMatrix
Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix(); final Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix();
Matrix4f transforamtionMatrix = Matrix4f.createMatrixRotate(new Vector3f(0, 0, 1), this.angle); final Matrix4f transforamtionMatrix = Matrix4f.createMatrixRotate(new Vector3f(0, 0, 1), this.angle);
Matrix4f viewMatrix = OpenGL.getCameraMatrix(); final Matrix4f viewMatrix = OpenGL.getCameraMatrix();
//Matrix4f tmpMatrix = projMatrix * camMatrix; //Matrix4f tmpMatrix = projMatrix * camMatrix;
this.verticesVBO.bindForRendering(); this.verticesVBO.bindForRendering();
this.oGLprogram.uniformMatrix(this.oGLMatrixView, viewMatrix); this.oGLprogram.uniformMatrix(this.oGLMatrixView, viewMatrix);
this.oGLprogram.uniformMatrix(this.oGLMatrixProjection, projectionMatrix); this.oGLprogram.uniformMatrix(this.oGLMatrixProjection, projectionMatrix);
// Change the position for each element with the same pipeline you need to render ... // Change the position for each element with the same pipeline you need to render ...
this.oGLprogram.uniformMatrix(this.oGLMatrixTransformation, transforamtionMatrix); this.oGLprogram.uniformMatrix(this.oGLMatrixTransformation, transforamtionMatrix);
// Request the draw of the elements: // Request the draw of the elements:
if (TEST_STATIC_MODE) { if (TEST_STATIC_MODE) {
this.verticesVBO.render(OpenGL.RenderMode.TRIANGLE); this.verticesVBO.render(OpenGL.RenderMode.TRIANGLE);
@ -107,7 +110,7 @@ public class Sample1Application extends GaleApplication {
OpenGL.pop(); OpenGL.pop();
// mark to redraw the screen ==> demo only.... // mark to redraw the screen ==> demo only....
markDrawingIsNeeded(); markDrawingIsNeeded();
if (!TEST_STATIC_MODE) { if (!TEST_STATIC_MODE) {
this.verticesVBO.clear(); this.verticesVBO.clear();
this.verticesVBO.setPosition(VERTICES); this.verticesVBO.setPosition(VERTICES);
@ -116,20 +119,29 @@ public class Sample1Application extends GaleApplication {
this.verticesVBO.flush(); this.verticesVBO.flush();
} }
} }
@Override @Override
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) { public void onKeyboard(
Log.info("Keyboard event: special=" + special); final KeySpecial special,
Log.info(" type=" + type); final KeyKeyboard type,
Log.info(" value='" + value + "'"); final Character value,
Log.info(" state=" + state); final KeyStatus state) {
LOGGER.info("Keyboard event: special=" + special);
LOGGER.info(" type=" + type);
LOGGER.info(" value='" + value + "'");
LOGGER.info(" state=" + state);
} }
@Override @Override
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) { public void onPointer(
// Log.info("input event: type=" + type); final KeySpecial special,
// Log.info(" id=" + pointerID); final KeyType type,
// Log.info(" pos=" + pos); final int pointerID,
// Log.info(" state=" + state); final Vector2f pos,
final KeyStatus state) {
// LOGGER.info("input event: type=" + type);
// LOGGER.info(" id=" + pointerID);
// LOGGER.info(" pos=" + pos);
// LOGGER.info(" state=" + state);
} }
} }

View File

@ -15,8 +15,11 @@ import org.atriasoft.gale.key.KeyType;
import org.atriasoft.gale.resource.ResourceProgram; import org.atriasoft.gale.resource.ResourceProgram;
import org.atriasoft.gale.resource.ResourceTexture; import org.atriasoft.gale.resource.ResourceTexture;
import org.atriasoft.gale.resource.ResourceVirtualArrayObject; import org.atriasoft.gale.resource.ResourceVirtualArrayObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Sample2Application extends GaleApplication { public class Sample2Application extends GaleApplication {
static final Logger LOGGER = LoggerFactory.getLogger(Sample2Application.class);
private ResourceProgram oGLprogram; private ResourceProgram oGLprogram;
private int oGLMatrixTransformation; private int oGLMatrixTransformation;
private int oGLMatrixProjection; private int oGLMatrixProjection;
@ -26,7 +29,7 @@ public class Sample2Application extends GaleApplication {
private float angleZ = 0; private float angleZ = 0;
private ResourceVirtualArrayObject verticesVBO; private ResourceVirtualArrayObject verticesVBO;
private ResourceTexture texture; private ResourceTexture texture;
@Override @Override
public void onCreate(final GaleContext context) { public void onCreate(final GaleContext context) {
setSize(new Vector2f(800, 600)); setSize(new Vector2f(800, 600));
@ -37,88 +40,88 @@ public class Sample2Application extends GaleApplication {
this.oGLMatrixView = this.oGLprogram.getUniform("in_matrixView"); this.oGLMatrixView = this.oGLprogram.getUniform("in_matrixView");
} }
//@formatter:off //@formatter:off
float[] vertices = { final float[] vertices = {
-0.5f,0.5f,-0.5f, -0.5f,0.5f,-0.5f,
-0.5f,-0.5f,-0.5f, -0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f, 0.5f,-0.5f,-0.5f,
0.5f,0.5f,-0.5f, 0.5f,0.5f,-0.5f,
-0.5f,0.5f,0.5f,
-0.5f,-0.5f,0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
0.5f,0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
-0.5f,0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,0.5f,
-0.5f,0.5f,0.5f, -0.5f,0.5f,0.5f,
-0.5f,-0.5f,0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
0.5f,0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
0.5f,-0.5f,0.5f,
0.5f,0.5f,0.5f,
-0.5f,0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,0.5f,
-0.5f,0.5f,0.5f,
-0.5f,0.5f,0.5f, -0.5f,0.5f,0.5f,
-0.5f,0.5f,-0.5f, -0.5f,0.5f,-0.5f,
0.5f,0.5f,-0.5f, 0.5f,0.5f,-0.5f,
0.5f,0.5f,0.5f, 0.5f,0.5f,0.5f,
-0.5f,-0.5f,0.5f, -0.5f,-0.5f,0.5f,
-0.5f,-0.5f,-0.5f, -0.5f,-0.5f,-0.5f,
0.5f,-0.5f,-0.5f, 0.5f,-0.5f,-0.5f,
0.5f,-0.5f,0.5f 0.5f,-0.5f,0.5f
}; };
float[] textureCoords = { final float[] textureCoords = {
0,0, 0,1, 1,1, 1,0, 0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0, 0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0, 0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0, 0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0, 0,0, 0,1, 1,1, 1,0,
0,0, 0,1, 1,1, 1,0 0,0, 0,1, 1,1, 1,0
}; };
int[] indices = { final int[] indices = {
1,0,3, 1,3,2, 1,0,3, 1,3,2,
4,5,7, 7,5,6, 4,5,7, 7,5,6,
9,8,11, 9,11,10, 9,8,11, 9,11,10,
12,13,15, 15,13,14, 12,13,15, 15,13,14,
17,16,19, 17,19,18, 17,16,19, 17,19,18,
20,21,23, 23,21,22 20,21,23, 23,21,22
}; };
//@formatter:on //@formatter:on
// this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer // this is the properties of the buffer requested : "r"/"w" + "-" + buffer type "f"=float "i"=integer
this.verticesVBO = ResourceVirtualArrayObject.create(vertices, textureCoords, null, indices); this.verticesVBO = ResourceVirtualArrayObject.create(vertices, textureCoords, null, indices);
// TO facilitate some debugs we add a name of the VBO: // TO facilitate some debugs we add a name of the VBO:
this.verticesVBO.setName("[VBO] of basic SAMPLE"); this.verticesVBO.setName("[VBO] of basic SAMPLE");
// update all the VBO elements ... // update all the VBO elements ...
this.verticesVBO.flush(); this.verticesVBO.flush();
this.texture = ResourceTexture.createFromPng(new Uri("DATA", "tree_sample.png")); this.texture = ResourceTexture.createFromPng(new Uri("DATA", "tree_sample.png"));
if (this.texture == null) { if (this.texture == null) {
Log.error("can not instanciate Texture ..."); LOGGER.error("can not instanciate Texture ...");
return; return;
} }
Log.info("==> Init APPL (END)"); LOGGER.info("==> Init APPL (END)");
} }
@Override @Override
public void onDraw(final GaleContext context) { public void onDraw(final GaleContext context) {
this.angleX += 0.001; this.angleX += 0.001;
this.angleY += 0.005; this.angleY += 0.005;
this.angleZ += 0.01; this.angleZ += 0.01;
//Log.info("==> appl Draw ..."); //LOGGER.info("==> appl Draw ...");
Vector2f size = getSize(); final Vector2f size = getSize();
//Log.info("==> Windows size = " + size); //LOGGER.info("==> Windows size = " + size);
// set the basic openGL view port: (position drawed in the windows) // set the basic openGL view port: (position drawed in the windows)
OpenGL.setViewPort(new Vector2f(0, 0), size); OpenGL.setViewPort(new Vector2f(0, 0), size);
// Clear all the stacked matrix ... // Clear all the stacked matrix ...
OpenGL.setBasicMatrix(Matrix4f.IDENTITY); OpenGL.setBasicMatrix(Matrix4f.IDENTITY);
// clear background // clear background
Color bgColor = new Color(0.0f, 1.0f, 1.0f, 0.75f); final Color bgColor = new Color(0.0f, 1.0f, 1.0f, 0.75f);
OpenGL.enable(OpenGL.Flag.flag_depthTest); OpenGL.enable(OpenGL.Flag.flag_depthTest);
OpenGL.clearColor(bgColor); OpenGL.clearColor(bgColor);
// real clear request: // real clear request:
@ -126,26 +129,30 @@ public class Sample2Application extends GaleApplication {
OpenGL.clear(OpenGL.ClearFlag.clearFlag_depthBuffer); OpenGL.clear(OpenGL.ClearFlag.clearFlag_depthBuffer);
// create a local matrix environnement. // create a local matrix environnement.
OpenGL.push(); OpenGL.push();
//Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-getAspectRatio(), getAspectRatio(), -1, 1, -50, 50); //Matrix4f tmpProjection = Matrix4f.createMatrixOrtho(-getAspectRatio(), getAspectRatio(), -1, 1, -50, 50);
Matrix4f tmpProjection = Matrix4f.createMatrixPerspective(1.30f, getAspectRatio(), 1, 50); final Matrix4f tmpProjection = Matrix4f.createMatrixPerspective(1.30f, getAspectRatio(), 1, 50);
// set internal matrix system: // set internal matrix system:
OpenGL.setMatrix(tmpProjection); OpenGL.setMatrix(tmpProjection);
if (this.oGLprogram == null) { if (this.oGLprogram == null) {
Log.info("No shader ..."); LOGGER.info("No shader ...");
return; return;
} }
//EWOL_DEBUG(" display " + this.coord.size() + " elements" ); //EWOL_DEBUG(" display " + this.coord.size() + " elements" );
this.oGLprogram.use(); this.oGLprogram.use();
// set Matrix : translation/positionMatrix // set Matrix : translation/positionMatrix
Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix(); final Matrix4f projectionMatrix = tmpProjection; //OpenGL.getMatrix();
Matrix4f transforamtionMatrix = Matrix4f.IDENTITY; Matrix4f transforamtionMatrix = Matrix4f.IDENTITY;
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, -1))); transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, -1)));
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(1, 0, 0), this.angleX)); transforamtionMatrix = transforamtionMatrix
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 1, 0), this.angleY)); .multiply(Matrix4f.createMatrixRotate(new Vector3f(1, 0, 0), this.angleX));
transforamtionMatrix = transforamtionMatrix.multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 0, 1), this.angleZ)); transforamtionMatrix = transforamtionMatrix
Matrix4f viewMatrix = OpenGL.getCameraMatrix().multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, -2))); .multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 1, 0), this.angleY));
transforamtionMatrix = transforamtionMatrix
.multiply(Matrix4f.createMatrixRotate(new Vector3f(0, 0, 1), this.angleZ));
final Matrix4f viewMatrix = OpenGL.getCameraMatrix()
.multiply(Matrix4f.createMatrixTranslate(new Vector3f(0, 0, -2)));
//Matrix4f tmpMatrix = projMatrix * camMatrix; //Matrix4f tmpMatrix = projMatrix * camMatrix;
this.verticesVBO.bindForRendering(); this.verticesVBO.bindForRendering();
this.oGLprogram.uniformMatrix(this.oGLMatrixView, viewMatrix); this.oGLprogram.uniformMatrix(this.oGLMatrixView, viewMatrix);
@ -157,7 +164,7 @@ public class Sample2Application extends GaleApplication {
OpenGL.updateAllFlags(); OpenGL.updateAllFlags();
// Request the draw od the elements: // Request the draw od the elements:
this.verticesVBO.render(OpenGL.RenderMode.TRIANGLE); this.verticesVBO.render(OpenGL.RenderMode.TRIANGLE);
this.verticesVBO.unBindForRendering(); this.verticesVBO.unBindForRendering();
this.texture.unBindForRendering(); this.texture.unBindForRendering();
this.oGLprogram.unUse(); this.oGLprogram.unUse();
@ -165,20 +172,29 @@ public class Sample2Application extends GaleApplication {
OpenGL.pop(); OpenGL.pop();
markDrawingIsNeeded(); markDrawingIsNeeded();
} }
@Override @Override
public void onKeyboard(final KeySpecial special, final KeyKeyboard type, final Character value, final KeyStatus state) { public void onKeyboard(
Log.info("Keyboard event: special=" + special); final KeySpecial special,
Log.info(" type=" + type); final KeyKeyboard type,
Log.info(" value='" + value + "'"); final Character value,
Log.info(" state=" + state); final KeyStatus state) {
LOGGER.info("Keyboard event: special=" + special);
LOGGER.info(" type=" + type);
LOGGER.info(" value='" + value + "'");
LOGGER.info(" state=" + state);
} }
@Override @Override
public void onPointer(final KeySpecial special, final KeyType type, final int pointerID, final Vector2f pos, final KeyStatus state) { public void onPointer(
// Log.info("input event: type=" + type); final KeySpecial special,
// Log.info(" id=" + pointerID); final KeyType type,
// Log.info(" pos=" + pos); final int pointerID,
// Log.info(" state=" + state); final Vector2f pos,
final KeyStatus state) {
// LOGGER.info("input event: type=" + type);
// LOGGER.info(" id=" + pointerID);
// LOGGER.info(" pos=" + pos);
// LOGGER.info(" state=" + state);
} }
} }

View File

@ -1,59 +0,0 @@
package test.atriasoft.gale;
import org.atriasoft.reggol.LogLevel;
import org.atriasoft.reggol.Logger;
public class Log {
private static final String LIB_NAME = "gale-test";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_CRITICAL = Logger.getNeedPrint(LIB_NAME, LogLevel.CRITICAL);
private static final boolean PRINT_ERROR = Logger.getNeedPrint(LIB_NAME, LogLevel.ERROR);
private static final boolean PRINT_WARNING = Logger.getNeedPrint(LIB_NAME, LogLevel.WARNING);
private static final boolean PRINT_INFO = Logger.getNeedPrint(LIB_NAME, LogLevel.INFO);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private static final boolean PRINT_VERBOSE = Logger.getNeedPrint(LIB_NAME, LogLevel.VERBOSE);
private static final boolean PRINT_TODO = Logger.getNeedPrint(LIB_NAME, LogLevel.TODO);
private static final boolean PRINT_PRINT = Logger.getNeedPrint(LIB_NAME, LogLevel.PRINT);
private Log() {}
public static void print(String data) {
if (PRINT_PRINT)
Logger.print(LIB_NAME_DRAW, data);
}
public static void critical(String data) {
if (PRINT_CRITICAL)
Logger.critical(LIB_NAME_DRAW, data);
}
public static void error(String data) {
if (PRINT_ERROR)
Logger.error(LIB_NAME_DRAW, data);
}
public static void warning(String data) {
if (PRINT_WARNING)
Logger.warning(LIB_NAME_DRAW, data);
}
public static void info(String data) {
if (PRINT_INFO)
Logger.info(LIB_NAME_DRAW, data);
}
public static void debug(String data) {
if (PRINT_DEBUG)
Logger.debug(LIB_NAME_DRAW, data);
}
public static void verbose(String data) {
if (PRINT_VERBOSE)
Logger.verbose(LIB_NAME_DRAW, data);
}
public static void todo(String data) {
if (PRINT_TODO)
Logger.todo(LIB_NAME_DRAW, data);
}
}

View File

@ -1,18 +0,0 @@
package test.atriasoft.gale;
import org.atriasoft.reggol.LogLevel;
import org.atriasoft.reggol.Logger;
public class Log2 {
private static final String LIB_NAME = "gale-test-2";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private Log2() {}
public static void debug(String data) {
if (PRINT_DEBUG)
Logger.debug(LIB_NAME_DRAW, data);
}
}

View File

@ -11,20 +11,18 @@ package test.atriasoft.gale;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.atriasoft.reggol.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(OrderAnnotation.class) @TestMethodOrder(OrderAnnotation.class)
public class TestBasicLog { public class TestBasicLog {
// JUST keep a kanva ...
@Test @Test
@Order(1) @Order(1)
public void aaFirstInitialisation() { public void aaFirstInitialisation() {
List<String> args = new ArrayList<>(); final List<String> args = new ArrayList<>();
args.add("--log-level=999"); args.add("--log-level=999");
args.add("--log-level=1"); args.add("--log-level=1");
args.add("--log-no-color"); args.add("--log-no-color");
@ -37,66 +35,6 @@ public class TestBasicLog {
args.add("--log-lib=sc-log-test"); args.add("--log-lib=sc-log-test");
args.add("--log-with-stupid-parameter=sdkfjsqdlkf"); args.add("--log-with-stupid-parameter=sdkfjsqdlkf");
args.add("--help"); args.add("--help");
Logger.init(args);
}
@Test
@Order(2)
public void bbSecondInitialisation() {
List<String> args = new ArrayList<>();
Logger.init(args);
}
@Test
@Order(3)
public void ccBasicLogCall() {
Log.print("Simple print");
Log.todo("Simple todo");
Log.error("Simple error");
Log.warning("Simple warning");
Log.info("Simple info");
Log.debug("Simple debug");
Log.verbose("Simple verbose");
}
// TODO REFACTO REMOVE this and set it in the Test of the logger.
public static String getAAAAAAA(int dfsdf) {
int hhh = 0;
for (int kkk = 0; kkk < dfsdf; kkk++)
for (int iii = 0; iii < 10000; iii++)
for (int jjj = 0; jjj < 100000; jjj++)
for (int lll = 0; lll < 100000; lll++)
hhh++;
return "kkk" + hhh;
}
public static void testLog() {
Log.print("test direct [START]");
// test de 10 secondes contre 0.0?? second quand le niveau n'est pas assez grand ...
long timeStart = System.currentTimeMillis();
for (int iii = 0; iii < 100000000; iii++)
Log2.debug("test direct");
long timeStop = System.currentTimeMillis();
Log.print("test direct [END] : " + timeStart + " to " + timeStop + " ==> delta=" + (timeStop - timeStart));
Log.print("test concat [START]");
// C'est très long dans les 2 cas ...
timeStart = System.currentTimeMillis();
for (int iii = 0; iii < 6; iii++)
Log2.debug("test concat: non fonctionnel, il applelle le get a chaque log ... " + getAAAAAAA(iii));
timeStop = System.currentTimeMillis();
Log.print("test concat [END] : " + timeStart + " to " + timeStop + " ==> delta=" + (timeStop - timeStart));
}
@Test
@Order(4)
public void ddTestSimpleLog() {
testLog();
}
@Test
@Order(4)
public void eeUsage() {
Logger.usage();
} }
} }