Basic support for skinning with GLSL shaders. Still need to work out
how to handle different lighting arrangements and complex materials (e.g., the metal effect for the Iron Plate). git-svn-id: svn+ssh://src.earth.threerings.net/nenya/trunk@229 ed5b42cb-e716-0410-a449-f6a68f950b19
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
//
|
||||
// $Id: ImageCache.java 158 2007-02-24 00:38:17Z mdb $
|
||||
//
|
||||
// Nenya library - tools for developing networked games
|
||||
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
|
||||
// http://www.threerings.net/code/nenya/
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or modify it
|
||||
// under the terms of the GNU Lesser General Public License as published
|
||||
// by the Free Software Foundation; either version 2.1 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
#version 110
|
||||
|
||||
#if BONES_PER_VERTEX == 4
|
||||
#define ATTRIB_TYPE vec4
|
||||
#elif BONES_PER_VERTEX == 3
|
||||
#define ATTRIB_TYPE vec3
|
||||
#elif BONES_PER_VERTEX == 2
|
||||
#define ATTRIB_TYPE vec2
|
||||
#else
|
||||
#define ATTRIB_TYPE float
|
||||
#endif
|
||||
|
||||
/** The bone transforms. */
|
||||
uniform mat4 boneTransforms[MAX_BONE_COUNT];
|
||||
|
||||
/** The bone indices. */
|
||||
attribute ATTRIB_TYPE boneIndices;
|
||||
|
||||
/** The bone weights. */
|
||||
attribute ATTRIB_TYPE boneWeights;
|
||||
|
||||
/**
|
||||
* Vertex shader for skinned meshes.
|
||||
*/
|
||||
void main ()
|
||||
{
|
||||
vec4 normal4 = vec4(gl_Normal, 0.0);
|
||||
|
||||
// add up the vertex as transformed by each bone and scaled by each weight
|
||||
#if BONES_PER_VERTEX == 1
|
||||
vec4 skinVertex = boneTransforms[int(boneIndices)] * gl_Vertex;
|
||||
vec4 skinNormal = boneTransforms[int(boneIndices)] * normal4;
|
||||
#else
|
||||
vec4 skinVertex = boneTransforms[int(boneIndices[0])] * gl_Vertex * boneWeights[0];
|
||||
vec4 skinNormal = boneTransforms[int(boneIndices[0])] * normal4 * boneWeights[0];
|
||||
for (int ii = 1; ii < BONES_PER_VERTEX; ii++) {
|
||||
skinVertex += boneTransforms[int(boneIndices[ii])] * gl_Vertex * boneWeights[ii];
|
||||
skinNormal += boneTransforms[int(boneIndices[ii])] * normal4 * boneWeights[ii];
|
||||
}
|
||||
#endif
|
||||
|
||||
// copy the texture coordinates from attribute to varying
|
||||
gl_TexCoord[0] = gl_MultiTexCoord0;
|
||||
gl_TexCoord[1] = gl_MultiTexCoord1;
|
||||
|
||||
// apply the standard transformation
|
||||
gl_Position = gl_ModelViewProjectionMatrix * skinVertex;
|
||||
|
||||
// eye space 'z' is the standard fog coordinate
|
||||
gl_FogFragCoord = -dot(gl_ModelViewMatrixTranspose[2], skinVertex);
|
||||
|
||||
// transform the normal into eye space
|
||||
vec3 eyeNormal = normalize(vec3(gl_ModelViewMatrixInverseTranspose * skinNormal));
|
||||
|
||||
// set gl_FrontColor based on normal and light parameters
|
||||
gl_FrontColor.rgb =
|
||||
gl_FrontLightProduct[0].ambient.rgb +
|
||||
gl_FrontLightProduct[0].diffuse.rgb *
|
||||
max(dot(eyeNormal, gl_LightSource[0].position.xyz), 0.0) +
|
||||
gl_FrontLightProduct[1].ambient.rgb +
|
||||
gl_FrontLightProduct[1].diffuse.rgb *
|
||||
max(dot(eyeNormal, gl_LightSource[1].position.xyz), 0.0);
|
||||
gl_FrontColor.a = gl_FrontMaterial.diffuse.a;
|
||||
}
|
||||
@@ -67,6 +67,7 @@ import com.samskivert.util.PropertiesUtil;
|
||||
import com.samskivert.util.StringUtil;
|
||||
|
||||
import com.threerings.jme.Log;
|
||||
import com.threerings.jme.util.ShaderCache;
|
||||
|
||||
/**
|
||||
* A {@link TriMesh} with a serialization mechanism tailored to stored models.
|
||||
@@ -441,6 +442,12 @@ public class ModelMesh extends TriMesh
|
||||
}
|
||||
}
|
||||
|
||||
// documentation inherited from interface ModelSpatial
|
||||
public void configureShaders (ShaderCache scache)
|
||||
{
|
||||
// no-op
|
||||
}
|
||||
|
||||
// documentation inherited from interface ModelSpatial
|
||||
public void storeMeshFrame (int frameId, boolean blend)
|
||||
{
|
||||
@@ -603,20 +610,6 @@ public class ModelMesh extends TriMesh
|
||||
return astate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenates the two provided buffers.
|
||||
*/
|
||||
protected static FloatBuffer concatenate (FloatBuffer b1, FloatBuffer b2)
|
||||
{
|
||||
FloatBuffer nb = BufferUtils.createFloatBuffer(b1.capacity() + b2.capacity());
|
||||
b1.clear();
|
||||
nb.put(b1);
|
||||
b2.clear();
|
||||
nb.put(b2);
|
||||
nb.clear();
|
||||
return nb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the encoded triangle index/distance pairs in {@link #_tcodes}
|
||||
* using a two-pass (16 bit) radix sort (as described by
|
||||
|
||||
@@ -42,6 +42,7 @@ import com.jme.util.export.OutputCapsule;
|
||||
|
||||
import com.threerings.jme.Log;
|
||||
import com.threerings.jme.util.JmeUtil;
|
||||
import com.threerings.jme.util.ShaderCache;
|
||||
|
||||
/**
|
||||
* A {@link Node} with a serialization mechanism tailored to stored models.
|
||||
@@ -259,6 +260,17 @@ public class ModelNode extends Node
|
||||
}
|
||||
}
|
||||
|
||||
// documentation inherited from interface ModelSpatial
|
||||
public void configureShaders (ShaderCache scache)
|
||||
{
|
||||
for (int ii = 0, nn = getQuantity(); ii < nn; ii++) {
|
||||
Spatial child = getChild(ii);
|
||||
if (child instanceof ModelSpatial) {
|
||||
((ModelSpatial)child).configureShaders(scache);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// documentation inherited from interface ModelSpatial
|
||||
public void storeMeshFrame (int frameId, boolean blend)
|
||||
{
|
||||
|
||||
@@ -24,6 +24,8 @@ package com.threerings.jme.model;
|
||||
import com.jme.renderer.Renderer;
|
||||
import com.jme.scene.Spatial;
|
||||
|
||||
import com.threerings.jme.util.ShaderCache;
|
||||
|
||||
/**
|
||||
* Contains method common to both {@link ModelNode}s and {@link ModelMesh}es.
|
||||
*/
|
||||
@@ -56,6 +58,11 @@ public interface ModelSpatial
|
||||
*/
|
||||
public void resolveTextures (TextureProvider tprov);
|
||||
|
||||
/**
|
||||
* Recursively creates or reconfigures any shaders used by the model using the supplied cache.
|
||||
*/
|
||||
public void configureShaders (ShaderCache scache);
|
||||
|
||||
/**
|
||||
* Recursively requests that the current state of all skinned meshes be
|
||||
* stored as an animation frame on the next update.
|
||||
|
||||
@@ -33,6 +33,8 @@ import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
import org.lwjgl.opengl.GLContext;
|
||||
|
||||
import com.jme.bounding.BoundingVolume;
|
||||
import com.jme.math.Matrix4f;
|
||||
import com.jme.math.Vector3f;
|
||||
@@ -42,7 +44,10 @@ import com.jme.scene.TriMesh;
|
||||
import com.jme.scene.VBOInfo;
|
||||
import com.jme.scene.batch.SharedBatch;
|
||||
import com.jme.scene.batch.TriangleBatch;
|
||||
import com.jme.scene.state.GLSLShaderObjectsState;
|
||||
import com.jme.scene.state.RenderState;
|
||||
import com.jme.system.DisplaySystem;
|
||||
import com.jme.util.ShaderAttribute;
|
||||
import com.jme.util.export.JMEExporter;
|
||||
import com.jme.util.export.JMEImporter;
|
||||
import com.jme.util.export.InputCapsule;
|
||||
@@ -52,15 +57,23 @@ import com.jme.util.geom.BufferUtils;
|
||||
|
||||
import com.samskivert.util.ArrayUtil;
|
||||
import com.samskivert.util.HashIntMap;
|
||||
import com.samskivert.util.ListUtil;
|
||||
|
||||
import com.threerings.jme.Log;
|
||||
import com.threerings.jme.util.JmeUtil;
|
||||
import com.threerings.jme.util.ShaderCache;
|
||||
|
||||
/**
|
||||
* A triangle mesh that deforms according to a bone hierarchy.
|
||||
*/
|
||||
public class SkinMesh extends ModelMesh
|
||||
{
|
||||
/** The maximum number of bone matrices that we can use for hardware skinning. */
|
||||
public static final int MAX_SHADER_BONE_COUNT = 32;
|
||||
|
||||
/** The maximum number of bones influencing a single vertex for hardware skinning. */
|
||||
public static final int MAX_SHADER_BONES_PER_VERTEX = 4;
|
||||
|
||||
/** Represents the vertex weights of a group of vertices influenced by the
|
||||
* same set of bones. */
|
||||
public static class WeightGroup
|
||||
@@ -239,12 +252,26 @@ public class SkinMesh extends ModelMesh
|
||||
} else {
|
||||
mstore = (SkinMesh)store;
|
||||
}
|
||||
properties.removeProperty("vertices");
|
||||
properties.removeProperty("normals");
|
||||
GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState(
|
||||
RenderState.RS_GLSL_SHADER_OBJECTS);
|
||||
if (sstate == null) {
|
||||
// vertices and normals must be cloned if not using a shader
|
||||
properties.removeProperty("vertices");
|
||||
properties.removeProperty("normals");
|
||||
}
|
||||
properties.removeProperty("displaylistid");
|
||||
super.putClone(mstore, properties);
|
||||
properties.addProperty("vertices");
|
||||
properties.addProperty("normals");
|
||||
if (sstate == null) {
|
||||
properties.addProperty("vertices");
|
||||
properties.addProperty("normals");
|
||||
} else {
|
||||
// for the shader, we must create a separate instance with different uniforms
|
||||
GLSLShaderObjectsState msstate =
|
||||
DisplaySystem.getDisplaySystem().getRenderer().createGLSLShaderObjectsState();
|
||||
msstate.setProgramID(sstate.getProgramID());
|
||||
msstate.attribs = sstate.attribs;
|
||||
mstore.setRenderState(msstate);
|
||||
}
|
||||
properties.addProperty("displaylistid");
|
||||
mstore._frames = _frames;
|
||||
mstore._useDisplayLists = _useDisplayLists;
|
||||
@@ -261,8 +288,8 @@ public class SkinMesh extends ModelMesh
|
||||
}
|
||||
mstore._ovbuf = _ovbuf;
|
||||
mstore._onbuf = _onbuf;
|
||||
mstore._vbuf = new float[_vbuf.length];
|
||||
mstore._nbuf = new float[_nbuf.length];
|
||||
mstore._vbuf = (sstate == null) ? _vbuf : new float[_vbuf.length];
|
||||
mstore._nbuf = (sstate == null) ? _nbuf : new float[_nbuf.length];
|
||||
return mstore;
|
||||
}
|
||||
|
||||
@@ -323,10 +350,48 @@ public class SkinMesh extends ModelMesh
|
||||
vboinfo.setVBOTextureEnabled(true);
|
||||
vboinfo.setVBOIndexEnabled(!_translucent);
|
||||
setVBOInfo(vboinfo);
|
||||
|
||||
// use VBOs for shader attributes
|
||||
GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState(
|
||||
RenderState.RS_GLSL_SHADER_OBJECTS);
|
||||
if (sstate != null) {
|
||||
for (ShaderAttribute attrib : sstate.attribs.values()) {
|
||||
attrib.useVBO = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
_useDisplayLists = useDisplayLists && !_translucent;
|
||||
}
|
||||
|
||||
@Override // documentation inherited
|
||||
public void configureShaders (ShaderCache scache)
|
||||
{
|
||||
if (_disableShaders || !GLContext.getCapabilities().GL_ARB_vertex_shader ||
|
||||
_bones.length > MAX_SHADER_BONE_COUNT) {
|
||||
return;
|
||||
}
|
||||
int bonesPerVertex = 0;
|
||||
for (WeightGroup group : _weightGroups) {
|
||||
bonesPerVertex = Math.max(group.bones.length, bonesPerVertex);
|
||||
}
|
||||
if (bonesPerVertex > MAX_SHADER_BONES_PER_VERTEX) {
|
||||
return;
|
||||
}
|
||||
GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState(
|
||||
RenderState.RS_GLSL_SHADER_OBJECTS);
|
||||
if (sstate == null) {
|
||||
sstate = DisplaySystem.getDisplaySystem().getRenderer().createGLSLShaderObjectsState();
|
||||
setShaderAttributes(sstate, bonesPerVertex);
|
||||
setRenderState(sstate);
|
||||
}
|
||||
if (!scache.configureState(sstate, "media/jme/skin.vert", null,
|
||||
"MAX_BONE_COUNT " + MAX_SHADER_BONE_COUNT, "BONES_PER_VERTEX " + bonesPerVertex)) {
|
||||
clearRenderState(RenderState.RS_GLSL_SHADER_OBJECTS);
|
||||
_disableShaders = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@Override // documentation inherited
|
||||
public void storeMeshFrame (int frameId, boolean blend)
|
||||
{
|
||||
@@ -375,6 +440,16 @@ public class SkinMesh extends ModelMesh
|
||||
bone.transform.multLocal(bone.invRefTransform);
|
||||
}
|
||||
|
||||
// if we're using shaders, initialize the uniform variables with the bone transforms
|
||||
GLSLShaderObjectsState sstate = (GLSLShaderObjectsState)getRenderState(
|
||||
RenderState.RS_GLSL_SHADER_OBJECTS);
|
||||
if (sstate != null) {
|
||||
for (int ii = 0; ii < _bones.length; ii++) {
|
||||
sstate.setUniform("boneTransforms[" + ii + "]", _bones[ii].transform, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// deform the mesh according to the positions of the bones (this code
|
||||
// is ugly as sin because it's optimized at a low level)
|
||||
Bone[] bones;
|
||||
@@ -481,6 +556,35 @@ public class SkinMesh extends ModelMesh
|
||||
_nbuf = new float[_onbuf.length];
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the skin shader attributes (bone indices and weights) in the supplied state.
|
||||
*/
|
||||
protected void setShaderAttributes (GLSLShaderObjectsState sstate, int bonesPerVertex)
|
||||
{
|
||||
int size = getBatch(0).getVertexCount() * bonesPerVertex;
|
||||
ByteBuffer bibuf = BufferUtils.createByteBuffer(size);
|
||||
FloatBuffer bwbuf = BufferUtils.createFloatBuffer(size);
|
||||
|
||||
for (WeightGroup group : _weightGroups) {
|
||||
byte[] indices = new byte[bonesPerVertex];
|
||||
for (int ii = 0; ii < indices.length; ii++) {
|
||||
indices[ii] = (byte)((ii < group.bones.length) ?
|
||||
ListUtil.indexOf(_bones, group.bones[ii]) : 0);
|
||||
}
|
||||
for (int ii = 0, widx = 0; ii < group.vertexCount; ii++) {
|
||||
bibuf.put(indices);
|
||||
for (int jj = 0; jj < bonesPerVertex; jj++) {
|
||||
bwbuf.put((jj < group.bones.length) ? group.weights[widx++] : 0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
bibuf.rewind();
|
||||
bwbuf.rewind();
|
||||
|
||||
sstate.setAttributePointer("boneIndices", bonesPerVertex, false, false, 0, bibuf);
|
||||
sstate.setAttributePointer("boneWeights", bonesPerVertex, false, 0, bwbuf);
|
||||
}
|
||||
|
||||
/** A stored frame used for linear blending. */
|
||||
protected static class BlendFrame
|
||||
{
|
||||
@@ -535,6 +639,9 @@ public class SkinMesh extends ModelMesh
|
||||
/** Whether or not the stored frame id will be used for blending. */
|
||||
protected boolean _storeBlend;
|
||||
|
||||
/** Set if we determine that our shaders don't compile to prevent us from trying again. */
|
||||
protected static boolean _disableShaders;
|
||||
|
||||
/** A dummy mesh that simply hold transformation values. */
|
||||
protected static final TriMesh DUMMY_MESH = new TriMesh();
|
||||
|
||||
|
||||
@@ -114,6 +114,7 @@ import com.threerings.jme.Log;
|
||||
import com.threerings.jme.camera.CameraHandler;
|
||||
import com.threerings.jme.model.Model;
|
||||
import com.threerings.jme.model.TextureProvider;
|
||||
import com.threerings.jme.util.ShaderCache;
|
||||
import com.threerings.jme.util.SpatialVisitor;
|
||||
|
||||
/**
|
||||
@@ -153,6 +154,7 @@ public class ModelViewer extends JmeCanvasApp
|
||||
{
|
||||
super(1024, 768);
|
||||
_rsrcmgr = new ResourceManager("rsrc");
|
||||
_scache = new ShaderCache(_rsrcmgr);
|
||||
_msg = new MessageManager("rsrc.i18n").getBundle("jme.viewer");
|
||||
_path = path;
|
||||
|
||||
@@ -639,6 +641,7 @@ public class ModelViewer extends JmeCanvasApp
|
||||
}
|
||||
_ctx.getGeometry().attachChild(_model = _omodel = model);
|
||||
_model.setAnimationMode(_animMode);
|
||||
_model.configureShaders(_scache);
|
||||
_model.lockStaticMeshes(_ctx.getRenderer(), true, true);
|
||||
|
||||
// load the model's textures
|
||||
@@ -814,6 +817,9 @@ public class ModelViewer extends JmeCanvasApp
|
||||
/** The resource manager. */
|
||||
protected ResourceManager _rsrcmgr;
|
||||
|
||||
/** The shader cache. */
|
||||
protected ShaderCache _scache;
|
||||
|
||||
/** The translation bundle. */
|
||||
protected MessageBundle _msg;
|
||||
|
||||
|
||||
@@ -22,9 +22,9 @@
|
||||
package com.threerings.jme.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import java.nio.IntBuffer;
|
||||
|
||||
@@ -198,14 +198,16 @@ public class JmeUtil
|
||||
|
||||
/**
|
||||
* Loads the specified shaders (prepending the supplied preprocessor definitions)
|
||||
* and returns a GLSL shader state. One of the supplied files may be <code>null</code>
|
||||
* and returns a GLSL shader state. One of the supplied streams may be <code>null</code>
|
||||
* in order to use the fixed-function pipeline for that part. The method returns
|
||||
* <code>null</code> if the shaders fail to compile (JME will log an error).
|
||||
*
|
||||
* @param defs a number of preprocessor definitions to be #defined in both shaders
|
||||
* (e.g., "ENABLE_FOG", "NUM_LIGHTS 2").
|
||||
*/
|
||||
public static GLSLShaderObjectsState loadShaders (File vert, File frag, String... defs)
|
||||
public static GLSLShaderObjectsState loadShaders (
|
||||
InputStream vert, InputStream frag, String... defs)
|
||||
throws IOException
|
||||
{
|
||||
GLSLShaderObjectsState sstate =
|
||||
DisplaySystem.getDisplaySystem().getRenderer().createGLSLShaderObjectsState();
|
||||
@@ -223,21 +225,18 @@ public class JmeUtil
|
||||
/**
|
||||
* Loads an entire source file as a string, prepending the supplied preprocessor definitions.
|
||||
*/
|
||||
protected static String readSource (File file, String[] defs)
|
||||
protected static String readSource (InputStream in, String[] defs)
|
||||
throws IOException
|
||||
{
|
||||
StringBuffer buf = new StringBuffer();
|
||||
String ln = System.getProperty("line.separator");
|
||||
for (String def : defs) {
|
||||
buf.append("#define ").append(def).append(ln);
|
||||
}
|
||||
try {
|
||||
BufferedReader reader = new BufferedReader(new FileReader(file));
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
buf.append(line).append(ln);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
buf.append(line).append(ln);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//
|
||||
// $Id: ImageCache.java 158 2007-02-24 00:38:17Z mdb $
|
||||
//
|
||||
// Nenya library - tools for developing networked games
|
||||
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
|
||||
// http://www.threerings.net/code/nenya/
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or modify it
|
||||
// under the terms of the GNU Lesser General Public License as published
|
||||
// by the Free Software Foundation; either version 2.1 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
package com.threerings.jme.util;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
import com.jme.scene.state.GLSLShaderObjectsState;
|
||||
import com.jme.system.DisplaySystem;
|
||||
import com.jme.util.ShaderAttribute;
|
||||
import com.jme.util.ShaderUniform;
|
||||
|
||||
import com.samskivert.util.ArrayUtil;
|
||||
import com.samskivert.util.ObjectUtil;
|
||||
|
||||
import com.threerings.resource.ResourceManager;
|
||||
|
||||
import static com.threerings.jme.Log.*;
|
||||
|
||||
/**
|
||||
* Caches shaders under their names and preprocessor definitions, ensuring that identical shaders
|
||||
* are only compiled once.
|
||||
*/
|
||||
public class ShaderCache
|
||||
{
|
||||
/**
|
||||
* Create a shader cache that will obtain shader source from the supplied resource manager.
|
||||
*/
|
||||
public ShaderCache (ResourceManager rsrcmgr)
|
||||
{
|
||||
_rsrcmgr = rsrcmgr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new shader state with the supplied vertex shader, fragment shader,
|
||||
* and preprocessor definitions. If a program with the given parameters has already been
|
||||
* compiled, the state will use the program id of the existing shader.
|
||||
*
|
||||
* @return the newly created state, or <code>null</code> if there was an error and the
|
||||
* program could not be compiled.
|
||||
*/
|
||||
public GLSLShaderObjectsState createState (String vert, String frag, String... defs)
|
||||
{
|
||||
GLSLShaderObjectsState sstate =
|
||||
DisplaySystem.getDisplaySystem().getRenderer().createGLSLShaderObjectsState();
|
||||
return (configureState(sstate, vert, frag, defs) ? sstate : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re)configures an existing shader state with the supplied parameters.
|
||||
*
|
||||
* @return true if the shader was successfully configured, false if the shader could not
|
||||
* be compiled.
|
||||
*/
|
||||
public boolean configureState (
|
||||
GLSLShaderObjectsState sstate, String vert, String frag, String... defs)
|
||||
{
|
||||
return configureState(sstate, vert, frag, defs, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re)configures an existing shader state with the supplied parameters.
|
||||
*
|
||||
* @param ddefs an optional array of derived preprocessor definitions that, unlike the
|
||||
* principal definitions, need not be compared when differentiating between cached shaders.
|
||||
* @return true if the shader was successfully configured, false if the shader could not
|
||||
* be compiled.
|
||||
*/
|
||||
public boolean configureState (
|
||||
GLSLShaderObjectsState sstate, String vert, String frag, String[] defs, String[] ddefs)
|
||||
{
|
||||
ShaderKey key = new ShaderKey(vert, frag, defs);
|
||||
Integer programId = _programIds.get(key);
|
||||
if (programId == null) {
|
||||
if (ddefs != null) {
|
||||
defs = ArrayUtil.concatenate(defs, ddefs);
|
||||
}
|
||||
GLSLShaderObjectsState pstate;
|
||||
try {
|
||||
pstate = JmeUtil.loadShaders(
|
||||
(vert == null) ? null : _rsrcmgr.getResource(vert),
|
||||
(frag == null) ? null : _rsrcmgr.getResource(frag), defs);
|
||||
} catch (IOException e) {
|
||||
log.warning("Failed to load shaders [vert=" + vert + ", frag=" + frag +
|
||||
", error=" + e + "].");
|
||||
return false;
|
||||
}
|
||||
if (pstate == null) {
|
||||
return false;
|
||||
}
|
||||
_programIds.put(key, programId = pstate.getProgramID());
|
||||
}
|
||||
if (sstate.getProgramID() == programId) {
|
||||
return true;
|
||||
}
|
||||
sstate.setProgramID(programId);
|
||||
for (ShaderAttribute attrib : sstate.attribs.values()) {
|
||||
attrib.attributeID = -1;
|
||||
}
|
||||
for (ShaderUniform uniform : sstate.uniforms.values()) {
|
||||
uniform.uniformID = -1;
|
||||
}
|
||||
sstate.setNeedsRefresh(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the specified shader is already loaded. This is useful in order to avoid
|
||||
* generating complex derived definitions when they won't be needed.
|
||||
*/
|
||||
public boolean isLoaded (String vert, String frag, String... defs)
|
||||
{
|
||||
return _programIds.containsKey(new ShaderKey(vert, frag, defs));
|
||||
}
|
||||
|
||||
/** Identifies a cached shader. */
|
||||
protected static class ShaderKey
|
||||
{
|
||||
/** The name of the vertex shader (or <code>null</code> for none). */
|
||||
public String vert;
|
||||
|
||||
/** The name of the fragment shader (or <code>null</code> for none). */
|
||||
public String frag;
|
||||
|
||||
/** The set of preprocessor definitions. */
|
||||
public HashSet<String> defs = new HashSet<String>();
|
||||
|
||||
public ShaderKey (String vert, String frag, String[] defs)
|
||||
{
|
||||
this.vert = vert;
|
||||
this.frag = frag;
|
||||
Collections.addAll(this.defs, defs);
|
||||
}
|
||||
|
||||
@Override // documentation inherited
|
||||
public int hashCode ()
|
||||
{
|
||||
return (vert == null ? 0 : vert.hashCode()) + (frag == null ? 0 : frag.hashCode()) +
|
||||
defs.hashCode();
|
||||
}
|
||||
|
||||
@Override // documentation inherited
|
||||
public boolean equals (Object obj)
|
||||
{
|
||||
ShaderKey okey = (ShaderKey)obj;
|
||||
return ObjectUtil.equals(vert, okey.vert) && ObjectUtil.equals(frag, okey.frag) &&
|
||||
defs.equals(okey.defs);
|
||||
}
|
||||
|
||||
@Override // documentation inherited
|
||||
public String toString ()
|
||||
{
|
||||
return "[vert=" + vert + ", frag=" + frag + ", defs=" + defs + "]";
|
||||
}
|
||||
}
|
||||
|
||||
/** Provides access to shader source. */
|
||||
protected ResourceManager _rsrcmgr;
|
||||
|
||||
/** Maps shader keys to linked program ids. */
|
||||
protected HashMap<ShaderKey, Integer> _programIds = new HashMap<ShaderKey, Integer>();
|
||||
}
|
||||
Reference in New Issue
Block a user