Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - AGP

Pages: 1 ... 5 6 [7] 8 9 ... 16
91
Support / Shadertoy
« on: December 12, 2013, 02:06:30 am »
I'd like to play around with Shadertoy's shaders. To start with, I would like to use this one: https://www.shadertoy.com/view/4slGRM. From what I gather, Shadertoy only has fragment shaders (am I right?). So I wrote a skeleton of a vertex shader that looks like this:

Code: [Select]
void main(void) {

}
I know, breathtaking, right? Still, GLSLShader tells me that the fragment shader (not my brilliant vertexshader, mind you) isn't compiled. How come?

Quote
[ Wed Dec 11 23:02:13 EST 2013 ] - ERROR: Attached fragment shader is not compiled.

Code: [Select]
// Simple Water shader. (c) Victor Korsun, bitekas@gmail.com; 2012.
//
// Attribution-ShareAlike CC License.

#ifdef GL_ES
precision highp float;
#endif

const float PI = 3.1415926535897932;

// play with these parameters to custimize the effect
// ===================================================

//speed
const float speed = 0.2;
const float speed_x = 0.3;
const float speed_y = 0.3;

// refraction
const float emboss = 0.50;
const float intensity = 2.4;
const int steps = 8;
const float frequency = 6.0;
const int angle = 7; // better when a prime

// reflection
const float delta = 60.;
const float intence = 700.;

const float reflectionCutOff = 0.012;
const float reflectionIntence = 200000.;

// ===================================================

float time = iGlobalTime*1.3;

  float col(vec2 coord)
  {
    float delta_theta = 2.0 * PI / float(angle);
    float col = 0.0;
    float theta = 0.0;
    for (int i = 0; i < steps; i++)
    {
      vec2 adjc = coord;
      theta = delta_theta*float(i);
      adjc.x += cos(theta)*time*speed + time * speed_x;
      adjc.y -= sin(theta)*time*speed - time * speed_y;
      col = col + cos( (adjc.x*cos(theta) - adjc.y*sin(theta))*frequency)*intensity;
    }

    return cos(col);
  }

//---------- main

void main(void)
{
vec2 p = (gl_FragCoord.xy) / iResolution.xy, c1 = p, c2 = p;
float cc1 = col(c1);

c2.x += iResolution.x/delta;
float dx = emboss*(cc1-col(c2))/delta;

c2.x = p.x;
c2.y += iResolution.y/delta;
float dy = emboss*(cc1-col(c2))/delta;

c1.x += dx*2.;
c1.y = -(c1.y+dy*2.);

float alpha = 1.+dot(dx,dy)*intence;

float ddx = dx - reflectionCutOff;
float ddy = dy - reflectionCutOff;
if (ddx > 0. && ddy > 0.)
alpha = pow(alpha, ddx*ddy*reflectionIntence);

vec4 col = texture2D(iChannel0,c1)*(alpha);
gl_FragColor = col;
}

92
Bugs / ShadowHelper/Primitives Bug
« on: December 09, 2013, 10:12:25 pm »
At (1, 600) I can create a Receiver plane which successfully displays shadows. At (1, 1000), it doesn't work. (2, 1000) does. I would think that it's an issue with the way in which ShadowHelper displays its shadows. And I would be happier without the extra polygons.

93
Support / Normal Mapping with Bones
« on: December 07, 2013, 08:23:31 am »
The NormalMapping example on the wiki requires you to compile your model. But bones breaks with compiled models. So how do I go about applying a normal map to a bones-animated model?

94
Bones / How to Use Shaders
« on: December 07, 2013, 08:22:41 am »
The NormalMapping example on the wiki requires you to compile your model. But bones breaks with compiled models. So how do I go about applying a normal map to a bones-animated model?

95
Support / Shouldn't MemoryHelper.compact() Free All My RAM?
« on: December 06, 2013, 07:52:27 pm »
I wrote a little endless runner, which I tested with textures 512x512 in size, on both the Nexus 10 tablet and the Galaxy S4. It ran fine. On the Galaxy Tab 2, for which the game was actually written as that is my son's tablet, it doesn't run at all. I've even reduced the textures to 256x256. After loading all the textures I call MemoryHelper.compact(). But before even the first chunk of city is loaded (and during its loading process), the game crashes with an OutOfMemoryError. I would think that the model itself isn't so complex that it would crash for simply trying to load this chunk (it has a total of 36k triangles). Is it possible that compact isn't doing its job (at least not right away)? Any suggestions?

96
Support / What's the advantage of using OpenGL ES 2?
« on: November 28, 2013, 11:41:52 pm »
Future compatibility? Memory efficiency? Performance?

97
Support / Which Way is the Camera Looking?
« on: November 20, 2013, 02:56:02 am »
On the docs, you should put down which way the original camera (as returned by World.getCamera()) is looking. Is it facing down or is it on the X/Z plane?

98
Support / Quick-and-dirty Jirr Wrapper
« on: November 18, 2013, 08:39:23 am »
I'm trying to run a game written for Jirr. As it happens, the 5+ year old Jirr dll isn't working for me. So, how could I go about making a quick-and-dirty jirr wrapper for jpct to avoid the issue altogether? Alternatively, Egon, you wouldn't happen to have tried this yourlself already? :- )

99
Support / Serialization Problem
« on: October 24, 2013, 12:53:18 pm »
The following code produces the message at the bottom. What's wrong?

Code: [Select]
        chunk2 = Loader.loadSerializedObject(new FileInputStream("chunk2.ser"));
Object3D chunk2Trees = Loader.loadSerializedObject(new FileInputStream("chunk2trees.ser"));
chunk2Trees.setTransparency(100);
chunk2Blades = Loader.loadSerializedObjectArray(new FileInputStream("chunk2blades.ser"));
for (int i = 0; i < chunk2Blades.length; i++) {
     chunk2.addChild(chunk2Blades[i]);
     chunk2Blades[i].build();
     theWorld.addObject(chunk2Blades[i]);
}
chunk2Trees.build();
chunk2.build();
chunk2.addChild(chunk2Trees);
chunk2.setRotationPivot(SimpleVector.ORIGIN);
chunk2.rotateX((float)Math.PI*-.5f);//-.5f
chunk2.translate(superman.getZ().x*-59700f, 0, superman.getZ().z*-59700f);
theWorld.addObject(chunk2Trees);
theWorld.addObject(chunk2);
chunk3 = Loader.loadSerializedObject(new FileInputStream("chunk3.ser"));
chunk3.build();
chunk3.setRotationPivot(SimpleVector.ORIGIN);
chunk3.rotateX((float)Math.PI*-.5f);//-.5f
chunk3.translate(superman.getZ().x*-119400f, 0, superman.getZ().z*-119400f);
theWorld.addObject(chunk3);

Code: [Select]
java.lang.ArrayIndexOutOfBoundsException: 69518
        at com.threed.jpct.Object3D.recreateTextureCoords(Object3D.java:4840)
        at com.threed.jpct.Object3D.build(Object3D.java:1830)
        at SuperEndless.loadModelsSerialized(SuperEndless.java:181)
        at SuperEndless.<init>(SuperEndless.java:122)
        at SuperEndless.main(SuperEndless.java:391)
[ Thu Oct 24 12:45:21 BRST 2013 ] - ERROR: Couldn't build() object (object542):
java.lang.ArrayIndexOutOfBoundsException/69518
No octree found in serialized data!
java.lang.ArrayIndexOutOfBoundsException: 70061
        at com.threed.jpct.Object3D.recreateTextureCoords(Object3D.java:4840)
        at com.threed.jpct.Object3D.build(Object3D.java:1830)
        at SuperEndless.loadModelsSerialized(SuperEndless.java:189)
        at SuperEndless.<init>(SuperEndless.java:122)
        at SuperEndless.main(SuperEndless.java:391)
[ Thu Oct 24 12:45:21 BRST 2013 ] - ERROR: Couldn't build() object (object1707):
 java.lang.ArrayIndexOutOfBoundsException/70061

100
Support / Incomprehensible Translations
« on: October 17, 2013, 09:36:01 am »
I have a very large 3x3 city. I haven't really tested the chunk's individual sizes, just going by trial-and-error. Nevertheless, the results should be more predictable. The following code generates the following screenshot. Overlapping (but not symmetrically so) chunks can be seen on it.

Code: [Select]
     private void loadModels() {
TextureManager manager = TextureManager.getInstance();
manager.addTexture("Girl", new Texture("Girl.jpg"));
FilenameFilter filter = new FilenameFilter() {
     public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith("png");
     }
};
String[] textures = new File("./").list(filter);
for (int i = 0; i < textures.length; i++)
     manager.addTexture(textures[i], new Texture(textures[i]));
oneByOne = Object3D.mergeAll(Loader.loadOBJ("1x1.obj", "1x1.mtl", .01f));
twoByOne = Object3D.mergeAll(Loader.loadOBJ("2x1.obj", "2x1.mtl", .01f));
threeByOne = Object3D.mergeAll(Loader.loadOBJ("3x1.obj", "3x1.mtl", .01f));
oneByTwo = Object3D.mergeAll(Loader.loadOBJ("1x2.obj", "1x2.mtl", .01f));
twoByTwo = Object3D.mergeAll(Loader.loadOBJ("2x2.obj", "2x2.mtl", .01f));
threeByTwo = Object3D.mergeAll(Loader.loadOBJ("3x2.obj", "3x2.mtl", .01f));
oneByThree = Object3D.mergeAll(Loader.loadOBJ("1x3.obj", "1x3.mtl", .01f));
twoByThree = Object3D.mergeAll(Loader.loadOBJ("2x3.obj", "2x3.mtl", .01f));
threeByThree = Object3D.mergeAll(Loader.loadOBJ("3x3.obj", "3x3.mtl", .01f));
oneByOne.setCenter(SimpleVector.ORIGIN);
twoByOne.setCenter(SimpleVector.ORIGIN);
threeByOne.setCenter(SimpleVector.ORIGIN);
oneByTwo.setCenter(SimpleVector.ORIGIN);
twoByTwo.setCenter(SimpleVector.ORIGIN);
threeByTwo.setCenter(SimpleVector.ORIGIN);
oneByThree.setCenter(SimpleVector.ORIGIN);
twoByThree.setCenter(SimpleVector.ORIGIN);
threeByThree.setCenter(SimpleVector.ORIGIN);
oneByOne.rotateX((float)Math.PI*-.5f);
twoByOne.rotateX((float)Math.PI*-.5f);
threeByOne.rotateX((float)Math.PI*-.5f);
oneByTwo.rotateX((float)Math.PI*-.5f);
twoByTwo.rotateX((float)Math.PI*-.5f);
threeByTwo.rotateX((float)Math.PI*-.5f);
oneByThree.rotateX((float)Math.PI*-.5f);
twoByThree.rotateX((float)Math.PI*-.5f);
threeByThree.rotateX((float)Math.PI*-.5f);
final float sizeX = 11000f, sizeZ = -7200f;//CHUNKS ARE 1.6:1, BUT ON WHAT AXIS?
oneByOne.translate(-sizeX, 0, 0);
threeByOne.translate(sizeX, 0, 0);
oneByTwo.translate(-sizeX, 0, sizeZ);
twoByTwo.translate(0, 0, sizeZ);
threeByTwo.translate(sizeX, 0, sizeZ);
oneByThree.translate(-sizeX, 0, sizeZ*2f);
twoByThree.translate(0, 0, sizeZ*2f);
threeByThree.translate(sizeX, 0, sizeZ*2f);
theWorld.addObject(oneByOne);
theWorld.addObject(twoByOne);
theWorld.addObject(threeByOne);
theWorld.addObject(oneByTwo);
theWorld.addObject(twoByTwo);
theWorld.addObject(threeByTwo);
theWorld.addObject(oneByThree);
theWorld.addObject(twoByThree);
theWorld.addObject(threeByThree);

try {hero = BonesIO.loadGroup(new java.io.FileInputStream("Girl.bones"));}
catch (java.io.FileNotFoundException e) {System.out.println("No such file: "+e.getMessage());}
catch (Exception e) {System.out.println("IO: "+e.getMessage());}
hero.get(0).setTexture("Girl");
hero.addToWorld(theWorld);

theWorld.buildAllObjects();
identifyAnimations();
     }


101
Support / Accelerometer Orientation
« on: October 06, 2013, 07:40:27 am »
Orientation of values[1] is different between the Galaxy S4 and the Nexus 10. Now that I think about it, it may be that it's because one is a phone and one is a tablet (hopefully between phones the value will be consistent and the same for tablets). So I have two questions:
1) Is it because one is a phone and the other is a tablet?
2) Either way, how do I test for it or otherwise get the desired result (I want for a landscape game to tilt sideways to move my hero)?

Code: [Select]
public void onSensorChanged(SensorEvent e) {
float[] values = e.values;
if (values[1] > .2f) {
xTranslation = values[1];
}
else if (values[1] < -.2f) {
xTranslation = values[1];
}
}

102
Bones / Special bones.jar
« on: September 13, 2013, 08:53:42 pm »
Raft, is there any chance you could make me a bones.jar that DOESN'T produce a null reference for model.getMesh()? As the code suggests, I'm trying to make a previously rigged cape into a simulated cloth (and eventually use the bones as references with which to "pick" the cloth).


103
Support / Cloth Cape
« on: September 13, 2013, 10:21:00 am »
I've been playing around Mizuki's and your cloth simulator. I've been trying to make a cape. I've replaced the sphere with my character as the colliding object. The problem is that the cloth seems to fold onto itself. It doesn't fall to the ground, either, it hangs there. I've included both the screenshot and mine and your source code.



Code: [Select]
//THIS CLASS SORT OF REPLACES ClothTester. I initialize it with cape = new ClothCape(manager, theWorld, batman.model.get(0));
     public ClothCape(TextureManager manager, World theWorld, raft.jpct.bones.Animated3D batman) {
this.theWorld = theWorld;
this.batman = batman;
manager.addTexture("twinkle", new Texture("blue.png"));
manager.addTexture("table", new Texture("brown.png"));

cape = Primitives.getPlane(10, 1);
cape.translate(0, -15f, 5f);
cape.setTexture("twinkle");
cape.setCulling(Object3D.CULLING_DISABLED);
cape.build();
theWorld.addObject(cape);
batman.setCollisionMode(Object3D.COLLISION_CHECK_OTHERS);

clothSim = new ClothController(theWorld, true, 11, 11, 50f);
cape.getMesh().setVertexController(clothSim, IVertexController.PRESERVE_SOURCE_MESH);
     }
     public void doMovement() {//FROM YOUR ClothTester
           ....
     }
}

Code: [Select]
import com.threed.jpct.*;
import java.lang.Math;

/**
 * Based on the orginal source by Mizuki Takase. Optimized for Android by EgonOlsen.
 *
 * @author Mizuki Takase, EgonOlsen
 *
 */
public class ClothController extends GenericVertexController {

private static final long serialVersionUID = 1L;

private int gridx;
private int gridy;
private float spacing;
private float stff;
private float mass;
private float dt;
private SimpleVector gravity;
private int numParticles;
private int numConstraints;
private int[] index;
private Particle[] particles;
private SimpleVector[] forces;
private SpringConstraint[] constraints;
private World theWorld;
private boolean freezeTop;

/*
* when inputting in the grid x and y, don't forget that this is for the
* amount of lines that make up the grid.
*/
public ClothController(World w, int x, int y, float sp) {
theWorld = w;
freezeTop = false;
gridx = x;
gridy = y;
spacing = sp;
stff = 5f;
mass = 0.5f; // 0.5
dt = 0.05f; // 0.05
gravity = new SimpleVector(0F, 9F, 0F);
}

public ClothController(World w, boolean f, int x, int y, float sp) {
theWorld = w;
freezeTop = f;
gridx = x;
gridy = y;
spacing = sp;
stff = 5f;
mass = 0.5f;
dt = 0.05f;
gravity = new SimpleVector(0F, 9F, 0F);
}

/*
* when inputting in the grid x and y, don't forget that this is for the
* amount of lines that make up the grid.
*/
public ClothController(World w, boolean f, int x, int y, float sp, float st, float m, float t, SimpleVector g) {
theWorld = w;
freezeTop = f;
gridx = x;
gridy = y;
spacing = sp;
stff = st;
mass = m;
dt = t;
gravity = g;
}

public boolean setup() {
index = QSort.sort(getSourceMesh());

numConstraints = (gridx - 1) * gridy + (gridy - 1) * gridx + (gridx - 1) * 2 * (gridy - 1);
numParticles = gridx * gridy;
constraints = new SpringConstraint[numConstraints];
particles = new Particle[numParticles];
forces = new SimpleVector[numParticles];

for (int i = 0; i < numParticles; i++) {
if (i > numParticles - gridx)
mass = 5;
particles[i] = new Particle(getSourceMesh()[i].x, getSourceMesh()[i].y, getSourceMesh()[i].z, mass);
particles[i].velocity = new SimpleVector(0F, 0F, 0F);
}

for (int i = 0; i < forces.length; i++) {
forces[i] = new SimpleVector();
}

float diagstff = (float) Math.sqrt(stff * stff + stff * stff);
float rt2 = (float) Math.sqrt(spacing * spacing + spacing * spacing);
int off = 0;
for (int i = 0; i < numParticles; i++) {
if (i % (gridx) < gridx - 1 && i < numParticles - gridx || i == 0) {
constraints[off++] = new SpringConstraint(particles[i], particles[i + 1], spacing, stff);
constraints[off++] = new SpringConstraint(particles[i], particles[i + gridx], spacing, stff);
constraints[off++] = new SpringConstraint(particles[i], particles[i + gridx + 1], rt2, diagstff);
if (i % gridx > 0) {
constraints[off++] = new SpringConstraint(particles[i], particles[i + gridx - 1], rt2, diagstff);
}
} else if ((i % (gridx) == gridx - 1) && (i < (gridx * gridy - (gridx)))) {
constraints[off++] = new SpringConstraint(particles[i], particles[i + gridx], spacing, stff);
constraints[off++] = new SpringConstraint(particles[i], particles[i + gridx - 1], rt2, diagstff);
} else if (i > numParticles - 2) {
} else {
constraints[off++] = new SpringConstraint(particles[i], particles[i + 1], spacing, stff);
}
}
return true;
}

public void apply() {
resolveConstraints();

int j;
if (freezeTop) {
j = gridx;
} else {
j = 0;
}
int end = particles.length;
for (; j < end; j++) {

Particle particlesj = particles[j];
SimpleVector forcesj = forces[j];

particlesj.oldPosition.set(particlesj.currentPosition);

particles[j].acceleration.set((float) (particlesj.acceleration.x + (forcesj.x / particlesj.mass) - 0.05 * particlesj.velocity.x), (float) (particlesj.acceleration.y
+ (forcesj.y / particlesj.mass) - 0.05 * particlesj.velocity.y),
(float) (particlesj.acceleration.z + (forcesj.z / particlesj.mass) - 0.05 * particlesj.velocity.z));

float vx = particlesj.velocity.x;
float vy = particlesj.velocity.y;
float vz = particlesj.velocity.z;
float p = 1F;

particlesj.velocity.set(particlesj.velocity.x + particlesj.acceleration.x * dt, particlesj.velocity.y + particlesj.acceleration.y * dt, particlesj.velocity.z
+ particlesj.acceleration.z * dt);

particlesj.currentPosition.set(particlesj.currentPosition.x + ((1F - p) * vx + p * particlesj.velocity.x) * dt, particlesj.currentPosition.y
+ ((1F - p) * vy + p * particlesj.velocity.y) * dt, particlesj.currentPosition.z + ((1F - p) * vz + p * particlesj.velocity.z) * dt);

particlesj.acceleration.set(0F, 0F, 0F);

if (theWorld.checkCollision(particlesj.currentPosition, particlesj.velocity, 20) != Object3D.NO_OBJECT) {
particlesj.currentPosition.set(particlesj.oldPosition);
particlesj.velocity.set(0, 0, 0);
}

// apply force
forcesj.set(gravity);
}

for (int i = 0; i < particles.length; i++) {
getDestinationMesh()[index[i]].set(particles[i].currentPosition);
}
}

void resolveConstraints() {
for (int j = 0; j < constraints.length; j++) {
constraints[j].resolveConstraint();
}
}

public Particle getParticle(SimpleVector v) {
if (v != null) {
float mindist = 1000.0F;
int index = 0;
for (int i = 0; i < particles.length; i++) {
SimpleVector pic = particles[i].currentPosition;
float deltax = pic.x - v.x;
float deltay = pic.y - v.y;
float distance = (float) Math.sqrt(deltax * deltax + deltay * deltay);

if (distance < mindist) {
mindist = distance;
index = i;
}
}
return particles[index];
} else
return null;
}

}

class SpringConstraint {

private Particle a, b;
private float restLen;
private float stiffness;

public SpringConstraint(Particle pa, Particle pb, float restlength, float stiff) {
a = pa;
b = pb;
restLen = restlength;
stiffness = stiff;
}

void resolveConstraint() {
if (a == b)
return;
else {
SimpleVector acurrentPosition = a.currentPosition;
SimpleVector bcurrentPosition = b.currentPosition;

SimpleVector aacceleration = a.acceleration;
SimpleVector bacceleration = b.acceleration;

SimpleVector avelocity = a.velocity;
SimpleVector bvelocity = b.velocity;

float amass1 = 1f / a.mass;
float bmass1 = 1f / b.mass;

float deltax = acurrentPosition.x - bcurrentPosition.x;
float deltay = acurrentPosition.y - bcurrentPosition.y;
float deltaz = acurrentPosition.z - bcurrentPosition.z;
float distance = (float) Math.sqrt(deltax * deltax + deltay * deltay + deltaz * deltaz);

float diff = (distance - restLen) * (stiffness / distance);

float dvx = avelocity.x - bvelocity.x;
float dvy = avelocity.y - bvelocity.y;
float dvz = avelocity.z - bvelocity.z;

float dmp = dvx * deltax + dvy * deltay + dvz * deltaz;
dmp /= distance * distance;
dmp *= 2.0;

a.acceleration.set((float) (aacceleration.x - deltax * (dmp + diff) * (amass1)), (float) (aacceleration.y - deltay * (dmp + diff) * (amass1)),
(float) (aacceleration.z - deltaz * (dmp + diff) * (amass1)));

b.acceleration.set((float) (bacceleration.x + deltax * (dmp + diff) * (bmass1)), (float) (bacceleration.y + deltay * (dmp + diff) * (bmass1)),
(float) (bacceleration.z + deltaz * (dmp + diff) * (bmass1)));
}
}
}

class Particle {
SimpleVector currentPosition;
SimpleVector oldPosition;
SimpleVector acceleration;
SimpleVector velocity;
float mass;

public Particle(float x, float y, float z, float m) {
this.currentPosition = new SimpleVector(x, y, z);
this.oldPosition = new SimpleVector(x, y, z);
this.acceleration = new SimpleVector(0.0001F, 0.0001F, 0.0001F);
this.velocity = new SimpleVector(0.0001F, 0.0001F, 0.0001F);
this.mass = m;
}

void setPosition(float xnew, float ynew, float znew) {
this.oldPosition.set(this.currentPosition);
this.currentPosition.set(xnew, ynew, znew);
}
}

class QSort {
static int[] QuickSort(SimpleVector[] a, int[] b, int lo0, int hi0) {
int lo = lo0;
int hi = hi0;
SimpleVector mid;

if (hi0 > lo0) {
mid = a[(lo0 + hi0) / 2];
while (lo <= hi) {
while ((lo < hi0) && (a[lo].y < mid.y || (a[lo].x < mid.x && a[lo].y == mid.y))) {
++lo;
}

while ((hi > lo0) && (a[hi].y > mid.y || (a[hi].y == mid.y && a[hi].x > mid.x))) {
--hi;
}
if (lo <= hi) {
swap(a, lo, hi);
swap(b, lo, hi);

++lo;
--hi;
}
}
if (lo0 < hi) {
QuickSort(a, b, lo0, hi);
}
if (lo < hi0) {
QuickSort(a, b, lo, hi0);
}
}

return b;
}

private static final void swap(int a[], int i, int j) {
int T = a[i];
a[i] = a[j];
a[j] = T;
}

private static final void swap(SimpleVector a[], int i, int j) {
SimpleVector T = a[i];
a[i] = a[j];
a[j] = T;
}

public static final int[] sort(SimpleVector a[]) {
int[] temp = new int[a.length];
for (int i = 0; i < temp.length; i++) {
temp[i] = i;
}
QuickSort(a, temp, 0, a.length - 1);
return temp;
}
}

Code: [Select]
/**
ORIGINALLY DATED Oct. 17, 2011. IS THIS Helge's OR Mizuki's?
*/

import java.io.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

import com.threed.jpct.*;
import com.threed.jpct.util.*;

class ClothTester  {
private final static float MOVE_SPEED = 2.5f;
private final static float TURN_SPEED = 0.06f;
private Matrix playerDirection = new Matrix();
private SimpleVector tempVector = new SimpleVector();

private final static int SWITCH_RENDERER = 35;
private boolean fullscreen = false;
private boolean openGL = false;
private boolean wireframe = false;

// some jPCT related stuff...
private Object3D obj;
private Object3D sphere;
private ClothController clothSim;
private FrameBuffer buffer = null;
private World theWorld = null;
private TextureManager texMan = null;
private Camera camera = null;
private Texture numbers = null;
private int width = 640;
private int height = 480;

// some AWT related stuff
private Frame frame = null;
private Graphics gFrame = null;
private BufferStrategy bufferStrategy = null;
private GraphicsDevice device = null;
private KeyMapper keyMapper = null;
private int titleBarHeight = 0;
private int leftBorderWidth = 0;
private int switchMode = 0;
private int fps;
private int lastFps;
private long totalFps;
private int pps;
private int lastPps;
private boolean isIdle = false;
private boolean exit = false;

// direction
private boolean left = false;
private boolean right = false;
private boolean forward = false;
private boolean back = false;
private boolean up = false;
private boolean down = false;
private int mouseX;
private int mouseY;

// ball movement
private boolean ballfoward = false;
private boolean ballback = false;
private boolean ballleft = false;
private boolean ballright = false;
private boolean ballup = false;
private boolean balldown = false;

// mouse picker
private Particle selected = null;

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

/**
* The constructor. Here we are initializing things...
*/
private ClothTester(String[] args) {

Config.useMultipleThreads = true;
Config.mtDebug = true;
Config.loadBalancingStrategy = 1;
Config.maxNumberOfCores = Runtime.getRuntime().availableProcessors();

isIdle = false;
switchMode = 0;
totalFps = 0;
fps = 0;
lastFps = 0;

/**
* Initialize the World instance and get the TextureManager (a
* singleton)
*/
theWorld = new World();
texMan = TextureManager.getInstance();

/**
* Setup the lighting. We are not using overbright lighting because the
* OpenGL renderer can't do it, but we are using RGB-scaling. Some
* hardware/drivers for OpenGL don't support this.
*/
Config.fadeoutLight = false;
Config.lightDiscardDistance = 3500;
Config.farPlane = 5000;
theWorld.getLights().setOverbrightLighting(Lights.OVERBRIGHT_LIGHTING_DISABLED);
theWorld.setAmbientLight(100, 150, 150);

/**
* Place the lightsources...
*/
theWorld.addLight(new SimpleVector(0, 0, 300), 100, 100, 100);

/**
* Load the textures needed and add them to the TextureManager. We are
* loading the "numbers" texture for blitting the framerate as well as
* the weapon's environment map and all JPGs that can be found in the
* "textures"-directory. The 3DS file of the level contains materials
* that are pointing to these textures (identified by name).
*/
numbers = new Texture("numbers.jpg");
texMan.addTexture("numbers", numbers);
texMan.addTexture("twinkle", new Texture("blue.png"));
texMan.addTexture("table", new Texture("brown.png"));

obj = Primitives.getPlane(10, 50);
obj.rotateX((float) Math.PI / 2);
obj.rotateMesh();
obj.setRotationMatrix(new Matrix());
obj.setTexture("twinkle");
obj.setCulling(Object3D.CULLING_DISABLED);
obj.build();
theWorld.addObject(obj);

clothSim = new ClothController(theWorld, true, 11, 11, 50f);
obj.getMesh().setVertexController(clothSim, IVertexController.PRESERVE_SOURCE_MESH);

sphere = Primitives.getSphere(150F);
// sphere = Primitives.getCone(150F);
// sphere = Primitives.getCube(150F);
sphere.translate(0f, 375f, 0f);
sphere.setTexture("table");
sphere.setCollisionMode(Object3D.COLLISION_CHECK_OTHERS);
sphere.build();
theWorld.addObject(sphere);

camera = theWorld.getCamera();
camera.setPosition(new SimpleVector(0, -50, -400));
camera.lookAt(sphere.getTransformedCenter());
camera.rotateX(0.3f);
theWorld.buildAllObjects();

sphere.compile();
obj.compile(true);

/**
* Setup some optimizations for outdoor rendering (the level is not very
* outdoorish at all, but at least the framebuffer needs clearing
* because the level is not closed.
*/
Config.collideOffset = 250;
Config.tuneForOutdoor();

/**
* Do some AWT setup work
*/
initializeFrame();

/**
* Here we go...!
*/
gameLoop();
}

/**
* This initializes the AWT frame either in fullscreen or in windowed mode.
* This is not a waterproof intialization, but i didn't want to do a AWT
* tutorial here (and i would be the wrong person to do this anyway...:-)).
* Change whatever you think that needs change here...
*/
private void initializeFrame() {
if (fullscreen) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
device = env.getDefaultScreenDevice();
GraphicsConfiguration gc = device.getDefaultConfiguration();
frame = new Frame(gc);
frame.setUndecorated(true);
frame.setIgnoreRepaint(true);
device.setFullScreenWindow(frame);
if (device.isDisplayChangeSupported()) {
device.setDisplayMode(new DisplayMode(width, height, 32, 0));
}
frame.createBufferStrategy(2);
bufferStrategy = frame.getBufferStrategy();
Graphics g = bufferStrategy.getDrawGraphics();
bufferStrategy.show();
g.dispose();
} else {
frame = new Frame();
frame.setTitle("jPCT " + Config.getVersion());
frame.pack();
Insets insets = frame.getInsets();
titleBarHeight = insets.top;
leftBorderWidth = insets.left;
frame.setSize(width + leftBorderWidth + insets.right, height + titleBarHeight + insets.bottom);
frame.setResizable(false);
frame.setVisible(true);
gFrame = frame.getGraphics();
}

/**
* The listeners are bound to the AWT frame...they are useless in OpenGL
* mode.
*/
frame.addWindowListener(new WindowEvents());
keyMapper = new KeyMapper(frame);

frame.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
selected = clothSim.getParticle(getAbsoluteCoordinate(camera, buffer, mouseX, mouseY, obj));
}

public void mouseReleased(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
selected = null;
}
});

frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if (selected != null) {
selected.velocity.x = (e.getX() - mouseX);
selected.velocity.y = (e.getY() - mouseY);
}
}

public void mouseMoved(MouseEvent e) {
}
});
}

/**
* get 3d coordinate of srcPoint on object's surface from 2d coordinates.
*
* @param camera
*            scene camera
* @param buffer
* @param x
*            screen (mouse) X coordinate
* @param y
*            screen (mouse) Y coordinate
* @param object
*            to check against
* @return
*/
public static SimpleVector getAbsoluteCoordinate(Camera camera, FrameBuffer buffer, int x, int y, Object3D object) {
SimpleVector rezult = null;
if (camera != null && buffer != null) {
SimpleVector rayTemp = Interact2D.reproject2D3D(camera, buffer, x, y);

rayTemp.normalize();
Matrix orient = camera.getFront();
float[] dump = orient.getDump();
SimpleVector ray = new SimpleVector();
ray.x = dump[0] * rayTemp.x + dump[1] * rayTemp.y + dump[2] * rayTemp.z + dump[3] * 1;
ray.y = dump[4] * rayTemp.x + dump[5] * rayTemp.y + dump[6] * rayTemp.z + dump[7] * 1;
ray.z = dump[8] * rayTemp.x + dump[9] * rayTemp.y + dump[10] * rayTemp.z + dump[11] * 1;

float distance = object.rayIntersectsAABB(camera.getPosition(), ray);

if (distance != Object3D.RAY_MISSES_BOX) {
rezult = new SimpleVector(camera.getPosition());
ray.scalarMul(distance);
rezult.add(ray);
}
}
return rezult;
}

/**
* The fps counter is blitted into the rendered framebuffer here and the
* results will be displayed (hence the name of the method...:-))
*/
private void display() {
blitNumber((int) totalFps, 5, 2);
blitNumber((int) lastPps, 5, 12);

if (!openGL) {
if (!fullscreen) {
buffer.display(gFrame, leftBorderWidth, titleBarHeight);
} else {
Graphics g = bufferStrategy.getDrawGraphics();
g.drawImage(buffer.getOutputBuffer(), 0, 0, null);
bufferStrategy.show();
g.dispose();
}
} else {
buffer.displayGLOnly();
}
}

/**
* A simple method that does the number-blitting.
*/
private void blitNumber(int number, int x, int y) {
if (numbers != null) {
String sNum = Integer.toString(number);
for (int i = 0; i < sNum.length(); i++) {
char cNum = sNum.charAt(i);
int iNum = cNum - 48;
buffer.blit(numbers, iNum * 5, 0, x, y, 5, 9, FrameBuffer.TRANSPARENT_BLITTING);
x += 5;
}
}
}

/**
* Does the collision detection and the movement of the player.
*/
private void doMovement() {

// forward and back may change during excution (threaded!), so we have
// to ensure to
// reset the camera only if has been changed before.
boolean cameraChanged = false;

if (forward) {
cameraChanged = true;
tempVector = playerDirection.getZAxis();
theWorld.checkCameraCollisionEllipsoid(tempVector, new SimpleVector(0, 0, 0), MOVE_SPEED, 5);
}
if (back) {
if (!cameraChanged) {
cameraChanged = true;
}
tempVector = playerDirection.getZAxis();
tempVector.scalarMul(-1f);
theWorld.checkCameraCollisionEllipsoid(tempVector, new SimpleVector(0, 0, 0), MOVE_SPEED, 5);
}

if (left) {
camera.rotateAxis(camera.getBack().getYAxis(), -TURN_SPEED);
playerDirection.rotateY(-TURN_SPEED);
}
if (right) {
camera.rotateAxis(camera.getBack().getYAxis(), TURN_SPEED);
playerDirection.rotateY(TURN_SPEED);
}
if (up) {
camera.rotateX(TURN_SPEED);
}
if (down) {
camera.rotateX(-TURN_SPEED);
}

if (ballfoward) {
SimpleVector a = obj.getZAxis();
a.scalarMul(3);
sphere.translate(a);
}
if (ballback) {
SimpleVector a = obj.getZAxis();
a.scalarMul(-3);
sphere.translate(a);
}
if (ballleft) {
SimpleVector a = obj.getXAxis();
a.scalarMul(-3);
sphere.translate(a);
}
if (ballright) {
SimpleVector a = obj.getXAxis();
a.scalarMul(3);
sphere.translate(a);
}
if (ballup) {
SimpleVector a = obj.getYAxis();
a.scalarMul(3);
sphere.translate(a);
}
if (balldown) {
SimpleVector a = obj.getYAxis();
a.scalarMul(-3);
sphere.translate(a);
}
}

/**
* Poll the keyboard using the KeyMapper from com.threed.jpct.util
*/
private void poll() {
KeyState state = null;
do {
state = keyMapper.poll();
if (state != KeyState.NONE) {
keyAffected(state);
}
} while (state != KeyState.NONE);
}

/**
* This is the game's main loop. We are doing some additional setup work
* here and rendering the scene in a loop, as well as calling doMovement()
* to handle the movement and the collision detection before each frame.
*/
private void gameLoop() {
World.setDefaultThread(Thread.currentThread());

buffer = new FrameBuffer(width, height, FrameBuffer.SAMPLINGMODE_NORMAL);
buffer.enableRenderer(IRenderer.RENDERER_SOFTWARE);

Timer timer = new Timer(10);
timer.start();

Timer fpsTimer = new Timer(1000);
fpsTimer.start();

long timerTicks = 0;

while (!exit) {
if (!isIdle) {

long ticks = timer.getElapsedTicks();
timerTicks += ticks;

for (int i = 0; i < ticks; i++) {
doMovement();
obj.getMesh().applyVertexController();
obj.touch();
}

poll();

if (switchMode != 0) {
switchOptions();
}

sphere.setScale(0.9f);

buffer.clear();
theWorld.renderScene(buffer);

if (!wireframe) {
theWorld.draw(buffer);
} else {
theWorld.drawWireframe(buffer, Color.white);
}

sphere.setScale(1f);

buffer.update();
display();

fps++;
pps += theWorld.getVisibilityList().getSize();

if (fpsTimer.getElapsedTicks() > 0) {
totalFps = (fps - lastFps);
lastFps = fps;
lastPps = pps;
pps = 0;
}

Thread.yield();

} else {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}

if (openGL) {
buffer.disableRenderer(IRenderer.RENDERER_OPENGL);
} else {
if (fullscreen) {
device.setFullScreenWindow(null);
}
}
System.exit(0);
}

/**
* This is for switching settings. Currently, only switching from OpenGL to
* software and back is supported here.
*/
private void switchOptions() {
switch (switchMode) {
case (SWITCH_RENDERER): {
isIdle = true;
if (buffer.usesRenderer(IRenderer.RENDERER_OPENGL)) {
keyMapper.destroy();
buffer.disableRenderer(IRenderer.RENDERER_OPENGL);
buffer.enableRenderer(IRenderer.RENDERER_SOFTWARE, IRenderer.MODE_OPENGL);
openGL = false;
if (fullscreen) {
device.setFullScreenWindow(null);
}
frame.setVisible(false);
frame.dispose();
initializeFrame();
} else {
frame.setVisible(false);
keyMapper.destroy();
buffer.enableRenderer(IRenderer.RENDERER_OPENGL, IRenderer.MODE_OPENGL);
buffer.disableRenderer(IRenderer.RENDERER_SOFTWARE);
openGL = true;
keyMapper = new KeyMapper();
}
isIdle = false;
break;
}
}
switchMode = 0;
}

private void keyAffected(KeyState state) {
int code = state.getKeyCode();
boolean event = state.getState();
switch (code) {
case (KeyEvent.VK_ESCAPE): {
exit = event;
break;
}
case (KeyEvent.VK_LEFT): {
left = event;
break;
}
case (KeyEvent.VK_RIGHT): {
right = event;
break;
}
case (KeyEvent.VK_PAGE_UP): {
up = event;
break;
}
case (KeyEvent.VK_PAGE_DOWN): {
down = event;
break;
}
case (KeyEvent.VK_UP): {
forward = event;
break;
}
case (KeyEvent.VK_DOWN): {
back = event;
break;
}
case (KeyEvent.VK_1): {
if (event && buffer.supports(FrameBuffer.SUPPORT_FOR_RGB_SCALING)) {
theWorld.getLights().setRGBScale(Lights.RGB_SCALE_DEFAULT);
}
break;
}
case (KeyEvent.VK_2): { // 2x scaling
if (event && buffer.supports(FrameBuffer.SUPPORT_FOR_RGB_SCALING)) {
theWorld.getLights().setRGBScale(Lights.RGB_SCALE_2X);
}
break;
}
case (KeyEvent.VK_4): { // 4x scaling
if (event && buffer.supports(FrameBuffer.SUPPORT_FOR_RGB_SCALING)) {
theWorld.getLights().setRGBScale(Lights.RGB_SCALE_4X);
}
break;
}
case (KeyEvent.VK_W): { // wireframe mode (w)
if (event) {
wireframe = !wireframe;
}
break;
}
case (KeyEvent.VK_X): { // change renderer (x)
if (event) {
switchMode = SWITCH_RENDERER;
}
break;
}

case (KeyEvent.VK_I): {
ballfoward = event;
break;
}
case (KeyEvent.VK_K): {
ballback = event;
break;
}
case (KeyEvent.VK_J): {
ballleft = event;
break;
}
case (KeyEvent.VK_L): {
ballright = event;
break;
}
case (KeyEvent.VK_U): {
ballup = event;
break;
}
case (KeyEvent.VK_O): {
balldown = event;
break;
}
}
}

/**
* The WindowApapter used for software mode
*/
private class WindowEvents extends WindowAdapter {
public void windowClosing(WindowEvent e) {
exit = true;
}

public void windowIconified(WindowEvent e) {
isIdle = true;
}

public void windowDeiconified(WindowEvent e) {
isIdle = false;
}
}

private class Timer {
private long ticks = 0;
private long granularity = 0;

public Timer(int granularity) {
this.granularity = granularity;
}

public void start() {
ticks = System.currentTimeMillis();
}

public void reset() {
start();
}

public long getElapsedTicks() {
long cur = System.currentTimeMillis();
long l = cur - ticks;

if (l >= granularity) {
ticks = cur - (l % granularity);
return l / granularity;
}
return 0;
}
}
}

104
I only get them when my program closes and I never got a "creating an additional visibility list" message. I'm using neither the ShadowHelper nor the ReflectionHelper. Is something wrong?

105
Bones / character.get(0).getTransformedCenter() Changes Gradually
« on: August 07, 2013, 11:05:19 pm »
Code: [Select]
I\m writing an endless runner. The following camera code produces gradually further results relative to the character. The character, of course, is animated. so is it possible that the animation causes a shift in its transformed center?

     private void follow() { //ADJUSTS CAMERA
Matrix matrix = character.get(0).getWorldTransformation().invert3x3();
camera.setBack(matrix);
camera.setPosition(character.get(0).getTransformedCenter());
camera.rotateCameraY((float)Math.toRadians(180+cameraDisplacement));
if (character.walkUp) {
     camera.rotateCameraX((float)Math.toRadians(-65));
     camera.moveCamera(Camera.CAMERA_MOVEOUT, 160f);
}
else camera.moveCamera(Camera.CAMERA_MOVEOUT, 240f);
     }

Pages: 1 ... 5 6 [7] 8 9 ... 16