Shadertoy shader import to libgdx - libgdx

I have searched everywhere but got no reference.
I want to use this shader from shadertoy to my libgdx project, so I tried to import simple shader first from: https://www.shadertoy.com/view/XsffRs
I modified it a bit like this but got no success:
/*
* Original shader from: https://www.shadertoy.com/view/XsffRs
*/
#ifdef GL_ES
precision mediump float;
#endif
uniform float time;
uniform vec2 resolution;
// shadertoy emulation
#define iTime time
#define iResolution resolution
// --------[ Original ShaderToy begins here ]---------- //
#define TAU 6.28318531
float C,S;
mat2 rot(float a){
return mat2(C=cos(a),S=sin(a),-S,C);
}
float map(vec3 p) {
p.yz*=rot(p.z*(.03*sin(iTime*3.)));
p.xz*=rot(p.z*(.03*cos(iTime*3.)));
float m=TAU/6.,
l=length(p.xy),
a=mod(atan(p.y,p.x)-p.z*.5+iTime*5.,m)-.5*m;
return length(vec2(a*l,l-2.))-.8;
}
void main(void)
{
vec2 uv = gl_FragCoord.xy / iResolution.xy;
uv-=.5;
uv.x*=iResolution.x/iResolution.y;
vec3 ro=vec3(uv,-3.),rd=normalize(vec3(uv,1.)),mp=ro;
float i=0.;
for (int ii=0;ii<30;++ii) {
i++;
float md=map(mp);
if (abs(md)<.001)break;
mp+=rd*md;
}
float r=i/30.;
float d=length(mp-ro)*.1;
vec3 c=mix(vec3(.2,.5,.7)*d*d,vec3(.2,.4,.8)*r/d,r*r);
c=sqrt(c);
gl_FragColor = vec4(c,1.);
}
Code for ShaderProgram
public void create () {
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
batch = new SpriteBatch();
ShaderProgram.pedantic = false;
shader = new ShaderProgram(Gdx.files.internal("vert.vert"), Gdx.files.internal("frag.frag"));
if(!shader.isCompiled())
shader.getLog();
}
public void render () {
time+=Gdx.graphics.getDeltaTime();
shader.begin();
shader.setUniformf("resolution", new Vector2(width, height));
shader.setUniformf("time", time);
shader.end();
batch.begin();
batch.setShader(shader);
batch.end();
}
Shader is running without error but getting black screen.
Edit: It works by drawing dummy texture
Texture t = new Texture(new Pixmap(width,height, Pixmap.Format.RGB565));
with spritebatch, but don't know why is dummy texture required?

In order to see the shader in action you need to draw something, the code is only specifying that the shader is going to be used but nothing is being drawn with it
batch.begin();
batch.setShader(shader);
batch.draw(new Texture(new Pixmap(width,height, Pixmap.Format.RGB565),0,0);
batch.end();

Related

calling Thrust device_vector from a device function

I have a struct Cap which inside I have a thrust::device_vector of another structure. When I compile the code, I get an error which complains about calling a host function (thrust::device_vector<FloatIntPair>) from a device function SphericalFaceManager::makeCaps. When I add __host__ __device__ instead of only __device__ to the member functions and constructors the code then compiles but I receive a warning same as aforementioned error and I think it copies data between host and device. My question is how can I access to device vectors in my classes avoiding any data transfer between CPU and GPU?
Hereafter you can find the code:
struct ParticleID {
Int solver;
Int ngb;
Int oldNgb;
LLInt no;
LLInt masterNo;
__device__ ParticleID() {
solver = -8;
ngb = 0;
oldNgb = 0;
no = 0;
masterNo = -1;
}
};
struct BaseParticle {
Float h;
Float3 pos;
ParticleID id;
__device__ BaseParticle(const Float3& _pos, const Float& _h, const ParticleID& _id) :
h(_h), pos(_pos), id(_id) { }
};
struct FloatIntPair{
Float first;
Int second;
__device__ FloatIntPair(const Float& _first, Int _second) : first(_first), second(_second) { }
__device__ FloatIntPair(const FloatIntPair& sample) : first(sample.first), second(sample.second) { }
static struct {
__device__ bool operator()(const FloatIntPair& a, const FloatIntPair& b) { return a.first < b.first; }
} LessOp;
};
struct Cap {
Float3 eX;
Float3 eY;
Float radius;
Float height;
Float3 center;
Float3 normal;
BaseParticle* aP;
BaseParticle* bP;
thrust::device_vector<FloatIntPair> vertices; // The ordered list of vertices generated from intersections by other circles
__device__ inline Float findAngle(const Float3& vertex) const {
Float result;
Float3 r = (vertex - center);
result = atan2(r|eY,r|eX);
return result += (result < 0.0) * (2.0 * _PI);
}
__device__ void insertVertex(const Float3& vertex, Int id) {
Float theta;
if (!vertices.empty())
theta = findAngle(vertex);
else {
eX = normalVec(vertex - center);
eY = normal ^ eX;
theta = 0.0;
}
vertices.push_back(FloatIntPair(theta,id));
}
__device__ Cap(BaseParticle* _aP, BaseParticle* _bP) : aP(_aP), bP(_bP) {
//Compute normal, center, radius
Float d = mag(bP->pos - aP->pos);
if(d == 0.0){
normal = Vector1(0.0);
center = aP->pos;
radius = height = 0.0;
} else {
normal = (bP->pos - aP->pos) / d;
Float x = (d * d - bP->h * bP->h + aP->h * aP->h) / (2.0 * d);
center = aP->pos + normal * x;
if (x >= aP->h) {
radius = height = 0.0;
return;
}
radius = sqrt(aP->h * aP->h - x * x);
height = min(2.0 * aP->h, aP->h - x);
Float3 vec001 = Vector(0.0,0.0,1.0);
Float3 vec011 = Vector(0.0,1.0,1.0);
eX = normalVec(vec001 ^ normal);
if (mag2(eX) < geoEps()) {
eX = eX = normalVec(vec011 ^ normal);
}
eY = normal ^ eX;
}
}
};
class SphericalFaceManager {
BaseParticle* particle;
Int baseSigma;
public:
thrust::device_vector<Cap> caps;
thrust::device_vector<Float3> vertexPool;
__device__ void makeCaps();
};
__device__ void SphericalFaceManager::makeCaps() {
BaseParticle* aP;
BaseParticle* bP;
Cap aCap(aP,bP);
}
You cannot use thrust vectors (or std::vector) directly in device code. This is mentioned in various other SO questions such as here
If you want to use the data in a thrust::device_vector in device code, you should pass a pointer to the data as a functor initializing parameter. Various other SO questions give examples of this, such as here
Likewise, you cannot use vector methods, e.g. .empty() or .push_back() in device code.
You will need to replace these with ordinary C-style allocators and C-style indexed data access.
For a multi-threaded implementation of push_back in device code, I would recommend something like this. That is a fully worked example that demonstrates how to allocate space for the vector and how each thread can use it for insertVertex for example.

implementing random generator in cuda

i want to implement this function in cuda as device/global function so as to obtain random numbers which are in gaussian distribution.
double gasdev2() {
double ran3n(long *seed);
// double genrand64_real3();
static int iset=0;
static double gcos;
double tmp1,tmp2;
if (iset==0) {
tmp1=sqrt(-2*log(ran3n(&seed)));
tmp2=pi2*ran3n(&seed);
// tmp1=sqrt(-2*log(genrand64_real3()));
// tmp2=pi2*genrand64_real3();
gcos=tmp1*cos(tmp2);
iset=1;
return tmp1*sin(tmp2);
//return 1;
}else{
iset=0;
return gcos;
//return 1;
}
}
this function will be basically used in these function calls and in serial code these are like this
for(int i=0;i<NTO;i++){
Frdx[j]=gasdev2()*ranm[j]*tconst;
Frdy[j]=gasdev2()*ranm[j]*tconst;
Frdz[j]=gasdev2()*ranm[j]*tconst;
}
I'd suggest not implementing it yourself but using the random algorithms provided by Thrust:
uint32_t seed = 1234;
thrust::default_random_engine rng(seed);
thrust::uniform_real_distribution<float> dist(0.0f, 1.0f);
float random_value_1 = dist(rng);
float random_value_2 = dist(rng);
You can use this both in host and device code.
Have a look at the Thrust examples.

Using a uniform in an "if" instruction inside a fragment shader don't work since recent chrome update

I'm using GLSL shaders in my WebGL project, a recent Chrome update made my shaders not linking without error message.
The problem occur when i use a uniform as a condition of a "if" in a fragment shader, like this example :
uniform int hasTexture;
void main(void) {
if(hasTexture == 1) {
// some code
}
}
In the vertex shader, it works, and if i don't use an uniform here, it works too.
EDIT : Here is the full shader where my problem occur :
Vertex Shader :
attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aVertexTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat3 uNMatrix;
uniform mat4 uMVMatrixCenter;
uniform vec3 uSunPosition;
uniform int hasTexture;
uniform int hasNormal;
varying float vLightLength;
varying float vSpecularLength;
varying vec2 vTextureCoord;
uniform float shininess;
uniform float sunPower;
void main(void) {
vec4 inposition = uMVMatrix * vec4(aVertexPosition, 1.0);
gl_Position = uPMatrix * inposition;
if(hasNormal == 1) {
vec4 transformedLocation = (uMVMatrixCenter * vec4(uSunPosition, 1.0));
vec3 sunPosition = transformedLocation.xyz;
vec3 lightDirection = normalize(sunPosition - inposition.xyz);
vec3 transformedNormal = uNMatrix * aVertexNormal;
vec3 normal = normalize(transformedNormal);
vLightLength = max(dot(normal, lightDirection), 0.0)*sunPower;
vec3 eyeDirection = normalize(-inposition.xyz);
vec3 reflectionDirection = reflect(-lightDirection, normal);
vSpecularLength = pow(max(dot(reflectionDirection, eyeDirection), 0.0), 32.0)*sunPower;
}
else {
vLightLength = 1.0;
vSpecularLength = 0.0;
}
if(hasTexture == 1)
vTextureCoord = aVertexTextureCoord;
}
And here is the fragment shader :
#ifdef GL_ES
precision highp float;
#endif
varying float vLightLength;
varying float vSpecularLength;
varying vec2 vTextureCoord;
uniform sampler2D uSampler;
uniform int hasTexture;
uniform float ambiantIntensity;
uniform vec3 diffuseColor;
uniform vec3 emissiveColor;
uniform vec3 specularColor;
uniform float shininess;
uniform float transparency;
void main(void) {
if(hasTexture == 1) {
gl_FragColor = vec4(texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)).rgb*(
emissiveColor*(1.0-vLightLength)
+diffuseColor*vLightLength
+specularColor*vSpecularLength*shininess), 1.0-transparency); // *vLightLength
}
else {
gl_FragColor = vec4((emissiveColor*(1.0-vLightLength)
+diffuseColor*vLightLength
+specularColor*vSpecularLength*shininess), 1.0-transparency);
}
}
And here is the code compiling them :
for(i=0;i<shaderNames.length;i++) {
vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, shaderSourceList[i*2]);
gl.compileShader(vertexShader);
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(vertexShader));
return;
}
fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, shaderSourceList[i*2+1]);
gl.compileShader(fragmentShader);
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(fragmentShader));
return;
}
shaderPrograms[i] = gl.createProgram();
gl.attachShader(shaderPrograms[i], vertexShader);
gl.attachShader(shaderPrograms[i], fragmentShader);
gl.linkProgram(shaderPrograms[i]);
if (!gl.getProgramParameter(shaderPrograms[i], gl.LINK_STATUS)) {
alert("Could not initialise shader "+shaderNames[i]);
return;
}
}
The error returned here is "Could not initialise shader " followed by the name.
If i remove the "if(hasTexture == 1) {" from my code, it works.
EDIT 2 :
I have installed WebGL inspector and i have now an error message for this buffer :
"Precisions for uniform hasTexture do not match between the vertex and fragment shader"
But i don't know what is wrong with my uniform.
Ok, apparently the problem is due to a same uniform used in both vertex and fragment shader, if i rename the "hasTexture" uniform to "hasTextureVS" in the vertex shader, it works !
I don't know why using the same uniform in both shaders is now forbidden since a recent Chrome update, but this workaround solve my problem.

DirectX 11.1 Matrix Multiplication issues

I wrote a generic matrix class for all of my 3d objects, but the translations seem to be really off.
Here is my class:
class GenericMatrix
{
public:
GenericMatrix();
virtual void Identity();
virtual void Scale( float x, float y, float z );
virtual void Scale( const DirectX::XMFLOAT3& s );
virtual DirectX::XMFLOAT3 Scaling( void );
virtual void Translate( float x, float y, float z );
virtual void Translate( const DirectX::XMFLOAT3& t );
virtual DirectX::XMFLOAT3 Translations( void );
virtual void Rotate( float x, float y, float z );
virtual void Rotate( const DirectX::XMFLOAT3& r );
virtual DirectX::XMVECTOR Rotations( void );
virtual DirectX::XMFLOAT3 RotationsPYR( void );
virtual DirectX::XMMATRIX Matrix( bool process = true );
virtual operator DirectX::XMMATRIX()
{
return this->Matrix();
}
virtual void UpdateMatrix( void );
DirectX::XMMATRIX matrix;
DirectX::XMFLOAT3 scale;
DirectX::XMFLOAT3 translation;
DirectX::XMVECTOR rotation;
bool matrixNeedsUpdate;
protected:
float yaw, pitch, roll;
};
And the source:
#include "pch.h"
#include "GenericMatrix.h"
GenericMatrix::GenericMatrix()
: matrixNeedsUpdate( true )
{
this->Identity();
this->pitch = 90.0f;
this->yaw = 0.0f;
this->roll = 0.0f;
}
void GenericMatrix::Identity()
{
this->scale = DirectX::XMFLOAT3( 1.0f, 1.0f, 1.0f );
this->translation = DirectX::XMFLOAT3( 0.0f, 0.0f, 0.0f );
this->rotation = DirectX::XMQuaternionIdentity();
this->pitch = 90.0f;
this->yaw = 0.0f;
this->roll = 0.0f;
matrixNeedsUpdate = true;
}
void GenericMatrix::Scale( float x, float y, float z )
{
this->scale.x += x;
this->scale.y += y;
this->scale.z += z;
this->matrixNeedsUpdate = true;
}
void GenericMatrix::Scale( const DirectX::XMFLOAT3& s )
{ Scale( s.x, s.y, s.z ); }
DirectX::XMFLOAT3 GenericMatrix::Scaling( void )
{ return this->scale; }
void GenericMatrix::Translate( float x, float y, float z )
{
this->translation.x += x;
this->translation.y += y;
this->translation.z += z;
this->matrixNeedsUpdate = true;
}
void GenericMatrix::Translate( const DirectX::XMFLOAT3& t )
{ Translate( t.x, t.y, t.z ); }
DirectX::XMFLOAT3 GenericMatrix::Translations( void )
{ return this->translation; }
void GenericMatrix::Rotate( float x, float y, float z )
{
pitch = x;
yaw = y;
roll = z;
this->rotation = DirectX::XMQuaternionRotationRollPitchYaw( pitch, yaw, roll );
this->matrixNeedsUpdate = true;
}
void GenericMatrix::Rotate( const DirectX::XMFLOAT3& r )
{ Rotate( r.x, r.y, r.z ); }
DirectX::XMVECTOR GenericMatrix::Rotations( void )
{ return this->rotation; }
DirectX::XMFLOAT3 GenericMatrix::RotationsPYR( void )
{
return DirectX::XMFLOAT3( pitch, yaw, roll );
}
DirectX::XMMATRIX GenericMatrix::Matrix( bool process )
{
if ( process && this->matrixNeedsUpdate )
{
UpdateMatrix();
this->matrixNeedsUpdate = false;
}
return this->matrix;
}
void GenericMatrix::UpdateMatrix( void )
{
DirectX::XMVECTOR scaleVec, translateVec;
scaleVec = DirectX::XMLoadFloat3( &this->scale );
translateVec = DirectX::XMLoadFloat3( &this->translation );
this->matrix = DirectX::XMMatrixScalingFromVector( scaleVec ) * DirectX::XMMatrixRotationQuaternion( this->rotation ) * DirectX::XMMatrixTranslationFromVector( translateVec );
}
When I use this as a model matrix, after doing Identity(), then Translate( 0.0f, 0.0f, 5.0f ), my model becomes only visible when I position my camera at [0,0,5], and even then, it's just a flicker. The last bit of 3d programming I have done was with OpenGL 1.x, so there is a good chance I'm doing something weird with the matrices, but haven't found anything that would tell me how to do this otherwise. If there is more information anyone needs, just ask.
update: Some more details - if I set the matrix to Identity() and leave it, i can move the camera and see the model without any problem from any position, meanwhile if I move it anywhere, it messes up the visibility.
I discovered the problem after a few tests. It seems I was using a left-handed coordinate system for my camera, but right-handed for my perspective. In between z 0.9 to -0.9, both left and right handed systems were able to agree that the model should be visible, but when I moved them out of that space, neither matrix could agree on what was visible unless my camera was exactly at the same coordinates.
Moral of the story - remember to consistently use the same coordinate system throughout your code.

opengl -- how to call a function and draw it from the beginning (from menu option)

i have the following code ,which draws mandelbrot set.I created a menu with an option "black&white" which i want to draw the mandelbrot in black and white color.I haven't figured how to do this (if it can be done this way).mandelbrot is called through the display function ,but how can i call mandelbrot_black?
Also, if someone knows hot to make "zoom" in my code...here...http://stackoverflow.com/questions/5705554/how-to-do-zoom-in-my-code-mandelbrot
void mandelbrot();
void mandelbrot_black();
GLsizei width = 600;
GLsizei height = 600;
GLfloat AspectRatio;
int max = 500;
double xpos=0,ypos=0;
int CLEARFLAG=1;
double xmax = 2.0;
double xmin = -2.0;
double ymax = 2.0;
double ymin = -2.0;
using namespace std;
void display()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-2, width, -2, height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT );
mandelbrot();
glutSwapBuffers();
}
void reshape(GLsizei w, GLsizei h) {
width=w; height=h;
glViewport(0,0,width,height);
glutPostRedisplay();
}
void setXYpos(int px, int py)
{
xpos=xmin+(xmax-xmin)*px/width;
ypos=ymax-(ymax-ymin)*py/height;
}
void mouse(int button, int state, int x, int y)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN) {CLEARFLAG=0; setXYpos(x,y);}
glutPostRedisplay();
}
void mandelbrot()
{
...}
void mandelbrot_black(){
...}
void mymenu(int n)
{
switch(n) {
case 1: zoom_in();break;
case 2: zoom_out();break;
case 3: mandelbrot_black();break;
case 4: exit(0);
}
glutPostRedisplay();
}
void SetupMenu()
{
glutCreateMenu(mymenu);
glutAddMenuEntry("zoom in",1);
glutAddMenuEntry("zoom out",2);
glutAddMenuEntry("black&white",3);
glutAddMenuEntry("exit",4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(600, 600);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutCreateWindow("Mandelbrot");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
Your display function needs to draw either mandelbrot() or mandelbrot_black() depending on the current state (which can/should be a global variable).
//in global scope
static bool black = false;
...
//in display()
if(black)
mandelbrot_black();
else
mandelbrot();
Change black accordingly in mymenu(). You still need to attach your menu to a mouse button and call SetupMenu().