Giter Club home page Giter Club logo

shaderman's Introduction

ShaderMan

ShaderToy to ShaderLab Converter

If you’ve tried dabbling with shaders at all, you’ve probably come across ShaderToy – an online shader showcase with some pretty amazing examples of what’s possible in a few lines of shader code, inspired greatly by classic demoscene coding. Here’s just two examples: https://www.shadertoy.com/view/4dl3zn

It’s an amazing resource, not only for inspiration but for learning how to create shaders, since every example comes with full source code which you can edit and immediately test online in your browser, alter parameters, supply different inputs etc.

The shaders exhibited on ShaderToy are exclusively written in GLSL, and run in your browser using WebGL.I write an automatic conversion tool to turn a GLSL shader into an HLSL shader that help you fast convert ShaderToy to ShaderLab unity.

Microsoft have published a very useful reference guide here which details many of the general differences between GLSL and HLSL. Unity also have a useful page here.

    Replace iGlobalTime shader input (“shader playback time in seconds”) with _Time.y
    Replace iResolution.xy (“viewport resolution in pixels”) with _ScreenParams.xy
    Replace vec2 types with float2, mat2 with float2x2 etc.
    Replace vec3(1) shortcut constructors in which all elements have same value with explicit float3(1,1,1)
    Replace Texture2D with Tex2D
    Replace atan(x,y) with atan2(y,x) <- Note parameter ordering!
    Replace mix() with lerp()
    Replace *= with mul()
    Remove third (bias) parameter from Texture2D lookups
    mainImage(out vec4 fragColor, in vec2 fragCoord) is the fragment shader function, equivalent to float4 mainImage(float2 fragCoord : SV_POSITION) : SV_Target
    UV coordinates in GLSL have 0 at the top and increase downwards, in HLSL 0 is at the bottom and increases upwards, so you may need to use uv.y = 1 – uv.y at some point.

Note that ShaderToys don’t have a vertex shader function – they are effectively full-screen pixel shaders which calculate the value at each UV coordinate in screenspace. As such, they are most suitable for use in a full-screen image effect (or, you can just apply them to a plane/quad if you want) in which the UVs range from 0-1.

But calculating pixel shaders for each pixel in a 1024×768 resolution (or higher) is expensive. One solution if you want to achieve anything like a game-playable framerate is to render the effect to a fixed-size rendertexture, and then scale that up to fill the screen. Here’s a simple generic script to do that:

Demo


How to use:

1.copy your lovely shader from www.shadertoy.com

ShaderToy

2.Open ShaderMan from Tools\ShaderMan

before opening shaderman be sure that there is codegenerator.cs in scene otherwise ShaderMan throws NullReferenceException.

3.Choose Name for you shader:

Step

4.Import your shader from shaderToy.com

Step

5.Click On Convert And Enjoy :D

Final Step


Video Tutorial is Available

capturedwadad

https://www.youtube.com/watch?v=MCER5P8Xz3w&lc=z22ysdkqln2texqj004t1aokgkzlpvkn3rdybfw1wtugrk0h00410


Musual

Music Visualization Shader

Musual

shaderman's People

Contributors

ggalancs avatar smkplus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

shaderman's Issues

Syntax error unexpected end of file at line (on d3d11)

Great resource!

One error I get after conversion is
syntax error: unexpected end of file at line...(d3d11)

However I can see nothing wrong at that specific line
pa=length(p);

I guess the problem lies elsewhere?
Perhaps the location of ENDCG or???

const float is always 0

Define should be used instead of const.
Anything const seems to be always equal to 0 regardless of what you set it to.

Example:

const float MAX_TRACE_DISTANCE = 20.0;
const float INTERSECTION_PRECISION = 0.001;
const int NUM_OF_TRACE_STEPS = 100;

should be turned to

#define MAX_TRACE_DISTANCE 20.0
#define INTERSECTION_PRECISION 0.001
#define NUM_OF_TRACE_STEPS 100

Pink shaders in Unity 2019. Solution? (Not using a custom pipeline)

Been trying to convert a shadertoy, but shaderman output a pink shader in Unity. Here is the shader. Thanks in advance for a solution!:
https://www.shadertoy.com/view/llVXRd

// --------------------------------------------------------
// HG_SDF
// https://www.shadertoy.com/view/Xs3GRB
// --------------------------------------------------------

void pR(inout vec2 p, float a) {
p = cos(a)*p + sin(a)*vec2(p.y, -p.x);
}

float pReflect(inout vec3 p, vec3 planeNormal, float offset) {
float t = dot(p, planeNormal)+offset;
if (t < 0.) {
p = p - (2.*t)*planeNormal;
}
return sign(t);
}

float smax(float a, float b, float r) {
float m = max(a, b);
if ((-a < r) && (-b < r)) {
return max(m, -(r - sqrt((r+a)(r+a) + (r+b)(r+b))));
} else {
return m;
}
}

// --------------------------------------------------------
// Icosahedron domain mirroring
// Adapted from knighty https://www.shadertoy.com/view/MsKGzw
// --------------------------------------------------------

#define PI 3.14159265359

vec3 facePlane;
vec3 uPlane;
vec3 vPlane;

int Type=5;
vec3 nc;
vec3 pab;
vec3 pbc;
vec3 pca;

void initIcosahedron() {//setup folding planes and vertex
float cospin=cos(PI/float(Type)), scospin=sqrt(0.75-cospin*cospin);
nc=vec3(-0.5,-cospin,scospin);//3rd folding plane. The two others are xz and yz planes
pbc=vec3(scospin,0.,0.5);//No normalization in order to have 'barycentric' coordinates work evenly
pca=vec3(0.,scospin,cospin);
pbc=normalize(pbc); pca=normalize(pca);//for slightly better DE. In reality it's not necesary to apply normalization :)
pab=vec3(0,0,1);

facePlane = pca;
uPlane = cross(vec3(1,0,0), facePlane);
vPlane = vec3(1,0,0);

}

void pModIcosahedron(inout vec3 p) {
p = abs(p);
pReflect(p, nc, 0.);
p.xy = abs(p.xy);
pReflect(p, nc, 0.);
p.xy = abs(p.xy);
pReflect(p, nc, 0.);
}

// --------------------------------------------------------
// Triangle tiling
// Adapted from mattz https://www.shadertoy.com/view/4d2GzV
// --------------------------------------------------------

const float sqrt3 = 1.7320508075688772;
const float i3 = 0.5773502691896258;

const mat2 cart2hex = mat2(1, 0, i3, 2. * i3);
const mat2 hex2cart = mat2(1, 0, -.5, .5 * sqrt3);

#define PHI (1.618033988749895)
#define TAU 6.283185307179586

struct TriPoints {
vec2 a;
vec2 b;
vec2 c;
vec2 center;
vec2 ab;
vec2 bc;
vec2 ca;
};

TriPoints closestTriPoints(vec2 p) {
vec2 pTri = cart2hex * p;
vec2 pi = floor(pTri);
vec2 pf = fract(pTri);

float split1 = step(pf.y, pf.x);
float split2 = step(pf.x, pf.y);

vec2 a = vec2(split1, 1);
vec2 b = vec2(1, split2);
vec2 c = vec2(0, 0);

a += pi;
b += pi;
c += pi;

a = hex2cart * a;
b = hex2cart * b;
c = hex2cart * c;

vec2 center = (a + b + c) / 3.;

vec2 ab = (a + b) / 2.;
vec2 bc = (b + c) / 2.;
vec2 ca = (c + a) / 2.;

return TriPoints(a, b, c, center, ab, bc, ca);

}

// --------------------------------------------------------
// Geodesic tiling
// --------------------------------------------------------

struct TriPoints3D {
vec3 a;
vec3 b;
vec3 c;
vec3 center;
vec3 ab;
vec3 bc;
vec3 ca;
};

vec3 intersection(vec3 n, vec3 planeNormal, float planeOffset) {
float denominator = dot(planeNormal, n);
float t = (dot(vec3(0), planeNormal ) + planeOffset) / -denominator;
return n * t;
}

//// Edge length of an icosahedron with an inscribed sphere of radius of 1
//float edgeLength = 1. / ((sqrt(3.) / 12.) * (3. + sqrt(5.)));
//// Inner radius of the icosahedron's face
//float faceRadius = (1./6.) * sqrt(3.) * edgeLength;
float faceRadius = 0.3819660112501051;

// 2D coordinates on the icosahedron face
vec2 icosahedronFaceCoordinates(vec3 p) {
vec3 pn = normalize(p);
vec3 i = intersection(pn, facePlane, -1.);
return vec2(dot(i, uPlane), dot(i, vPlane));
}

// Project 2D icosahedron face coordinates onto a sphere
vec3 faceToSphere(vec2 facePoint) {
return normalize(facePlane + (uPlane * facePoint.x) + (vPlane * facePoint.y));
}

TriPoints3D geodesicTriPoints(vec3 p, float subdivisions) {
// Get 2D cartesian coordiantes on that face
vec2 uv = icosahedronFaceCoordinates(p);

// Get points on the nearest triangle tile
float uvScale = subdivisions / faceRadius / 2.;
TriPoints points = closestTriPoints(uv * uvScale);

// Project 2D triangle coordinates onto a sphere 
vec3 a = faceToSphere(points.a / uvScale);
vec3 b = faceToSphere(points.b / uvScale);
vec3 c = faceToSphere(points.c / uvScale);
vec3 center = faceToSphere(points.center / uvScale);
vec3 ab = faceToSphere(points.ab / uvScale);
vec3 bc = faceToSphere(points.bc / uvScale);
vec3 ca = faceToSphere(points.ca / uvScale);

return TriPoints3D(a, b, c, center, ab, bc, ca);

}

// --------------------------------------------------------
// Spectrum colour palette
// IQ https://www.shadertoy.com/view/ll2GD3
// --------------------------------------------------------

vec3 pal( in float t, in vec3 a, in vec3 b, in vec3 c, in vec3 d ) {
return a + bcos( 6.28318(c*t+d) );
}

vec3 spectrum(float n) {
return pal( n, vec3(0.5,0.5,0.5),vec3(0.5,0.5,0.5),vec3(1.0,1.0,1.0),vec3(0.0,0.33,0.67) );
}

// --------------------------------------------------------
// Model/Camera Rotation
// --------------------------------------------------------

mat3 sphericalMatrix(float theta, float phi) {
float cx = cos(theta);
float cy = cos(phi);
float sx = sin(theta);
float sy = sin(phi);
return mat3(
cy, -sy * -sx, -sy * cx,
0, cx, sx,
sy, cy * -sx, cy * cx
);
}

mat3 mouseRotation(bool enable, vec2 xy) {
if (enable) {
vec2 mouse = iMouse.xy / iResolution.xy;

    if (mouse.x != 0. && mouse.y != 0.) {
        xy.x = mouse.x;
        xy.y = mouse.y;
    }
}
float rx, ry;

rx = (xy.y + .5) * PI;
ry = (-xy.x) * 2. * PI;

return sphericalMatrix(rx, ry);

}

mat3 modelRotation() {
mat3 m = mouseRotation(MOUSE_CONTROL==1, MODEL_ROTATION);
return m;
}

mat3 cameraRotation() {
mat3 m = mouseRotation(MOUSE_CONTROL==2, CAMERA_ROTATION);
return m;
}

// --------------------------------------------------------
// Animation
// --------------------------------------------------------

const float SCENE_DURATION = 6.;
const float CROSSFADE_DURATION = 2.;

float time;

struct HexSpec {
float roundTop;
float roundCorner;
float height;
float thickness;
float gap;
};

HexSpec newHexSpec(float subdivisions) {
return HexSpec(
.05 / subdivisions,
.1 / subdivisions,
2.,
2.,
.005
);
}

// Animation 1

float animSubdivisions1() {
return mix(2.4, 3.4, cos(time * PI) * .5 + .5);
}

HexSpec animHex1(vec3 hexCenter, float subdivisions) {
HexSpec spec = newHexSpec(subdivisions);

float offset = time * 3. * PI;
offset -= subdivisions;
float blend = dot(hexCenter, pca);
blend = cos(blend * 30. + offset) * .5 + .5;
spec.height = mix(1.75, 2., blend);

spec.thickness = spec.height;

return spec;

}

// Animation 2

float animSubdivisions2() {
return mix(1., 2.3, sin(time * PI/2.) * .5 + .5);
}

HexSpec animHex2(vec3 hexCenter, float subdivisions) {
HexSpec spec = newHexSpec(subdivisions);

float blend = hexCenter.y;
spec.height = mix(1.6, 2., sin(blend * 10. + time * PI) * .5 + .5);

spec.roundTop = .02 / subdivisions;
spec.roundCorner = .09 / subdivisions;
spec.thickness = spec.roundTop * 4.;
spec.gap = .01;

return spec;

}

// Animation 3

float animSubdivisions3() {
return 5.;
}

HexSpec animHex3(vec3 hexCenter, float subdivisions) {
HexSpec spec = newHexSpec(subdivisions);

float blend = acos(dot(hexCenter, pab)) * 10.;
blend = cos(blend + time * PI) * .5 + .5;
spec.gap = mix(.01, .4, blend) / subdivisions;

spec.thickness = spec.roundTop * 2.;

return spec;

}

// Transition between animations

float sineInOut(float t) {
return -0.5 * (cos(PI * t) - 1.0);
}

float transitionValues(float a, float b, float c) {
#ifdef LOOP
#if LOOP == 1
return a;
#endif
#if LOOP == 2
return b;
#endif
#if LOOP == 3
return c;
#endif
#endif
float t = time / SCENE_DURATION;
float scene = floor(mod(t, 3.));
float blend = fract(t);
float delay = (SCENE_DURATION - CROSSFADE_DURATION) / SCENE_DURATION;
blend = max(blend - delay, 0.) / (1. - delay);
blend = sineInOut(blend);
float ab = mix(a, b, blend);
float bc = mix(b, c, blend);
float cd = mix(c, a, blend);
float result = mix(ab, bc, min(scene, 1.));
result = mix(result, cd, max(scene - 1., 0.));
return result;
}

HexSpec transitionHexSpecs(HexSpec a, HexSpec b, HexSpec c) {
float roundTop = transitionValues(a.roundTop, b.roundTop, c.roundTop);
float roundCorner = transitionValues(a.roundCorner, b.roundCorner, c.roundCorner);
float height = transitionValues(a.height, b.height, c.height);
float thickness = transitionValues(a.thickness, b.thickness, c.thickness);
float gap = transitionValues(a.gap, b.gap, c.gap);
return HexSpec(roundTop, roundCorner, height, thickness, gap);
}

// --------------------------------------------------------
// Modelling
// --------------------------------------------------------

const vec3 FACE_COLOR = vec3(.9,.9,1.);
const vec3 BACK_COLOR = vec3(.1,.1,.15);
const vec3 BACKGROUND_COLOR = vec3(.0, .005, .03);

struct Model {
float dist;
vec3 albedo;
float glow;
};

Model hexModel(
vec3 p,
vec3 hexCenter,
vec3 edgeA,
vec3 edgeB,
HexSpec spec
) {
float d;

float edgeADist = dot(p, edgeA) + spec.gap;
float edgeBDist = dot(p, edgeB) - spec.gap;
float edgeDist = smax(edgeADist, -edgeBDist, spec.roundCorner);

float outerDist = length(p) - spec.height;
d = smax(edgeDist, outerDist, spec.roundTop);

float innerDist = length(p) - spec.height + spec.thickness;
d = smax(d, -innerDist, spec.roundTop);

vec3 color;

float faceBlend = (spec.height - length(p)) / spec.thickness;
faceBlend = clamp(faceBlend, 0., 1.);
color = mix(FACE_COLOR, BACK_COLOR, step(.5, faceBlend));

vec3 edgeColor = spectrum(dot(hexCenter, pca) * 5. + length(p) + .8);    
float edgeBlend = smoothstep(-.04, -.005, edgeDist);
color = mix(color, edgeColor, edgeBlend); 

return Model(d, color, edgeBlend);

}

// checks to see which intersection is closer
Model opU( Model m1, Model m2 ){
if (m1.dist < m2.dist) {
return m1;
} else {
return m2;
}
}

Model geodesicModel(vec3 p) {

pModIcosahedron(p);

float subdivisions = transitionValues(
    animSubdivisions1(),
    animSubdivisions2(),
    animSubdivisions3()
);
TriPoints3D points = geodesicTriPoints(p, subdivisions);
    
vec3 edgeAB = normalize(cross(points.center, points.ab));
vec3 edgeBC = normalize(cross(points.center, points.bc));
vec3 edgeCA = normalize(cross(points.center, points.ca));

Model model, part;
HexSpec spec;

spec = transitionHexSpecs(
    animHex1(points.b, subdivisions),
    animHex2(points.b, subdivisions),
    animHex3(points.b, subdivisions)
);
part = hexModel(p, points.b, edgeAB, edgeBC, spec);
model = part;

spec = transitionHexSpecs(
    animHex1(points.c, subdivisions),
    animHex2(points.c, subdivisions),
    animHex3(points.c, subdivisions)
);
part = hexModel(p, points.c, edgeBC, edgeCA, spec);
model = opU(model, part);

spec = transitionHexSpecs(
    animHex1(points.a, subdivisions),
    animHex2(points.a, subdivisions),
    animHex3(points.a, subdivisions)
);
part = hexModel(p, points.a, edgeCA, edgeAB, spec);
model = opU(model, part);

return model;

}

Model map( vec3 p ){
mat3 m = modelRotation();
p *= m;
#ifndef LOOP
pR(p.xz, time * PI/16.);
#endif
Model model = geodesicModel(p);
return model;
}

// --------------------------------------------------------
// LIGHTING
// Adapted from IQ https://www.shadertoy.com/view/Xds3zN
// --------------------------------------------------------

vec3 doLighting(Model model, vec3 pos, vec3 nor, vec3 ref, vec3 rd) {
vec3 lightPos = normalize(vec3(.5,.5,-1.));
vec3 backLightPos = normalize(vec3(-.5,-.3,1));
vec3 ambientPos = vec3(0,1,0);

vec3  lig = lightPos;
float amb = clamp((dot(nor, ambientPos) + 1.) / 2., 0., 1.);
float dif = clamp( dot( nor, lig ), 0.0, 1.0 );
float bac = pow(clamp(dot(nor, backLightPos), 0., 1.), 1.5);
float fre = pow( clamp(1.0+dot(nor,rd),0.0,1.0), 2.0 );

vec3 lin = vec3(0.0);
lin += 1.20 * dif * vec3(.9);
lin += 0.80 * amb * vec3(.5, .7, .8);
lin += 0.30 * bac * vec3(.25);
lin += 0.20 * fre * vec3(1);

vec3 albedo = model.albedo;
vec3 col = mix(albedo * lin, albedo, model.glow);    

return col;

}

// --------------------------------------------------------
// Ray Marching
// Adapted from cabbibo https://www.shadertoy.com/view/Xl2XWt
// --------------------------------------------------------

const float MAX_TRACE_DISTANCE = 8.; // max trace distance
const float INTERSECTION_PRECISION = .001; // precision of the intersection
const int NUM_OF_TRACE_STEPS = 100;
const float FUDGE_FACTOR = .9; // Default is 1, reduce to fix overshoots

struct CastRay {
vec3 origin;
vec3 direction;
};

struct Ray {
vec3 origin;
vec3 direction;
float len;
};

struct Hit {
Ray ray;
Model model;
vec3 pos;
bool isBackground;
vec3 normal;
vec3 color;
};

vec3 calcNormal( in vec3 pos ){
vec3 eps = vec3( 0.001, 0.0, 0.0 );
vec3 nor = vec3(
map(pos+eps.xyy).dist - map(pos-eps.xyy).dist,
map(pos+eps.yxy).dist - map(pos-eps.yxy).dist,
map(pos+eps.yyx).dist - map(pos-eps.yyx).dist );
return normalize(nor);
}

Hit raymarch(CastRay castRay){

float currentDist = INTERSECTION_PRECISION * 2.0;
Model model;

Ray ray = Ray(castRay.origin, castRay.direction, 0.);

for( int i=0; i< NUM_OF_TRACE_STEPS ; i++ ){
    if (currentDist < INTERSECTION_PRECISION || ray.len > MAX_TRACE_DISTANCE) {
        break;
    }
    model = map(ray.origin + ray.direction * ray.len);
    currentDist = model.dist;
    ray.len += currentDist * FUDGE_FACTOR;
}

bool isBackground = false;
vec3 pos = vec3(0);
vec3 normal = vec3(0);
vec3 color = vec3(0);

if (ray.len > MAX_TRACE_DISTANCE) {
    isBackground = true;
} else {
    pos = ray.origin + ray.direction * ray.len;
    normal = calcNormal(pos);
}

return Hit(ray, model, pos, isBackground, normal, color);

}

// --------------------------------------------------------
// Rendering
// --------------------------------------------------------

void shadeSurface(inout Hit hit){

vec3 color = BACKGROUND_COLOR;

if (hit.isBackground) {
    hit.color = color;
    return;
}

vec3 ref = reflect(hit.ray.direction, hit.normal);

#ifdef DEBUG
    color = hit.normal * 0.5 + 0.5;
#else 
    color = doLighting(
        hit.model,
        hit.pos,
        hit.normal,
        ref,
        hit.ray.direction
    );
#endif

hit.color = color;

}

vec3 render(Hit hit){
shadeSurface(hit);
return hit.color;
}

// --------------------------------------------------------
// Camera
// https://www.shadertoy.com/view/Xl2XWt
// --------------------------------------------------------

mat3 calcLookAtMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}

void doCamera(out vec3 camPos, out vec3 camTar, out float camRoll, in float time, in vec2 mouse) {
float dist = 5.5;
camRoll = 0.;
camTar = vec3(0,0,0);
camPos = vec3(0,0,-dist);
camPos *= cameraRotation();
camPos += camTar;
}

// --------------------------------------------------------
// Gamma
// https://www.shadertoy.com/view/Xds3zN
// --------------------------------------------------------

const float GAMMA = 2.2;

vec3 gamma(vec3 color, float g) {
return pow(color, vec3(g));
}

vec3 linearToScreen(vec3 linearRGB) {
return gamma(linearRGB, 1.0 / GAMMA);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
time = iTime;

#ifdef LOOP
    #if LOOP == 1
        time = mod(time, 2.);   
    #endif
    #if LOOP == 2
        time = mod(time, 4.);   
    #endif
    #if LOOP == 3
        time = mod(time, 2.);
	#endif
#endif

initIcosahedron();

vec2 p = (-iResolution.xy + 2.0*fragCoord.xy)/iResolution.y;
vec2 m = iMouse.xy / iResolution.xy;

vec3 camPos = vec3( 0., 0., 2.);
vec3 camTar = vec3( 0. , 0. , 0. );
float camRoll = 0.;

// camera movement
doCamera(camPos, camTar, camRoll, iTime, m);

// camera matrix
mat3 camMat = calcLookAtMatrix( camPos, camTar, camRoll );  // 0.0 is the camera roll

// create view ray
vec3 rd = normalize( camMat * vec3(p.xy,2.0) ); // 2.0 is the lens length

Hit hit = raymarch(CastRay(camPos, rd));

vec3 color = render(hit);

#ifndef DEBUG
    color = linearToScreen(color);
#endif

fragColor = vec4(color,1.0);

}

There is a problem about converting mod to fmod

Converting mod directly to fmod can cause problems, such as the toy below.
https://www.shadertoy.com/view/XsXXDn

GLSL mod is x - y * floor(x/y)
HLSL fmod is x - y * trunc(x/y)
CG fmod is

float2 fmod(float2 a, float2 b)
{
  float2 c = frac(abs(a/b))*abs(b);
  return (a < 0) ? -c : c;   /* if ( a < 0 ) c = 0-c */
}

https://forum.unity.com/threads/translating-a-glsl-shader-noise-algorithm-to-hlsl-cg.485750/#post-3164874
https://developer.download.nvidia.cn/cg/fmod.html

Always an error no matter what (Token and TOK and more

This is what it made you should be able to find the original link in it:

Shader "ShaderMan/CloudyCrystal"
{

Properties{
//Properties
}

SubShader
{
Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }

Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha

CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

struct VertexInput {
fixed4 vertex : POSITION;
fixed2 uv:TEXCOORD0;
fixed4 tangent : TANGENT;
fixed3 normal : NORMAL;
//VertexInput
};


struct VertexOutput {
fixed4 pos : SV_POSITION;
fixed2 uv:TEXCOORD0;
//VertexOutput
};

//Variables

// License CC0: Cloudy crystal

// Late to the party I discovered: https://www.shadertoy.com/view/MtX3Ws
// Played around with it for a bit and thought it looked quite nice so I shared

#define TIME _Time.y
#define RESOLUTION 1
#define ROT(a) fixed2x2(cos(a), sin(a), -sin(a), cos(a))
#define PI 3.141592654
#define TAU (2.0*PI)
#define L2(x) dot(x, x)

#define RAYSHAPE(ro, rd) raySphere4(ro, rd, 0.5)
#define IRAYSHAPE(ro, rd) iraySphere4(ro, rd, 0.5)

const fixed miss = 1E4;
const fixed refrIndex = 0.85;
const fixed3 lightPos = 2.0*fixed3(1.5, 2.0, 1.0);
const fixed3 skyCol1 = pow(fixed3(0.2, 0.4, 0.6), fixed3(0.25,0.25,0.25))*1.0;
const fixed3 skyCol2 = pow(fixed3(0.4, 0.7, 1.0), fixed3(2.0,2.0,2.0))*1.0;
const fixed3 sunCol = fixed3(8.0,7.0,6.0)/8.0;

fixed tanh_approx(fixed x) {
// return tanh(x);
fixed x2 = xx;
return clamp(x
(27.0 + x2)/(27.0+9.0*x2), -1.0, 1.0);
}

// https://stackoverflow.com/questions/15095909/from-rgb-to-hsv-in-opengl-glsl
fixed3 hsv2rgb(fixed3 c) {
const fixed4 K = fixed4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
fixed3 p = abs(frac(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * lerp(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

// Various ray object intersection from IQ:
// https://www.iquilezles.org/www/articles/intersectors/intersectors.htm
fixed raySphere4(fixed3 ro, fixed3 rd, fixed ra) {
fixed r2 = rara;
fixed3 d2 = rd
rd; fixed3 d3 = d2rd;
fixed3 o2 = ro
ro; fixed3 o3 = o2ro;
fixed ka = 1.0/dot(d2,d2);
fixed k3 = ka
dot(ro,d3);
fixed k2 = ka* dot(o2,d2);
fixed k1 = ka* dot(o3,rd);
fixed k0 = ka*(dot(o2,o2) - r2r2);
fixed c2 = k2 - k3
k3;
fixed c1 = k1 + 2.0k3k3k3 - 3.0k3k2;
fixed c0 = k0 - 3.0
k3k3k3k3 + 6.0k3k3k2 - 4.0k3k1;
fixed p = c2c2 + c0/3.0;
fixed q = c2
c2c2 - c2c0 + c1c1;
fixed h = q
q - ppp;
if (h<0.0) return miss; //no intersection
fixed sh = sqrt(h);
fixed s = sign(q+sh)pow(abs(q+sh),1.0/3.0); // cuberoot
fixed t = sign(q-sh)pow(abs(q-sh),1.0/3.0); // cuberoot
fixed2 w = fixed2( s+t,s-t );
fixed2 v = fixed2( w.x+c2
4.0, w.y
sqrt(3.0) )*0.5;
fixed r = length(v);
return -abs(v.y)/sqrt(r+v.x) - c1/r - k3;
}

fixed3 sphere4Normal(fixed3 pos) {
return normalize( pospospos );
}

fixed iraySphere4(fixed3 ro, fixed3 rd, fixed ra) {
// Computes inner intersection by intersecting a reverse outer intersection
fixed3 rro = ro + rdra4.0;
fixed3 rrd = -rd;
fixed rt = raySphere4(rro, rrd, ra);

if (rt == miss) return miss;

fixed3 rpos = rro + rrd*rt;
return length(rpos - ro);
}

fixed rayPlane(fixed3 ro, fixed3 rd, fixed4 p ) {
return -(dot(ro,p.xyz)+p.w)/dot(rd,p.xyz);
}

fixed3 skyColor(fixed3 ro, fixed3 rd) {
const fixed3 sunDir = normalize(lightPos);
fixed sunDot = max(dot(rd, sunDir), 0.0);
fixed3 final = fixed3(0.,0.,0.);

final += lerp(skyCol1, skyCol2, rd.y);
final += 0.5sunColpow(sunDot, 20.0);
final += 4.0sunColpow(sunDot, 400.0);

fixed tp = rayPlane(ro, rd, fixed4(fixed3(0.0, 1.0, 0.0), 0.505));
if (tp > 0.0) {
fixed3 pos = ro + tprd;
fixed3 ld = normalize(lightPos - pos);
fixed ts4 = RAYSHAPE(pos, ld);
fixed3 spos = pos + ld
ts4;
fixed its4= IRAYSHAPE(spos, ld);
// Extremely fake soft shadows
fixed sha = ts4 == miss ? 1.0 : (1.0-1.0tanh_approx(its41.5/(0.5+.5ts4)));
fixed3 nor = fixed3(0.0, 1.0, 0.0);
fixed3 icol = 1.5
skyCol1 + 4.0sunColshadot(-rd, nor);
fixed2 ppos = pos.xz
0.75;
ppos = frac(ppos+0.5)-0.5;
fixed pd = min(abs(ppos.x), abs(ppos.y));
fixed3 pcol= lerp(fixed3(0.4,0.4,0.4), fixed3(0.3,0.3,0.3), exp(-60.0*pd));

fixed3 col  = icol*pcol;
col = clamp(col, 0.0, 1.25);
fixed f   = exp(-10.0*(max(tp-10.0, 0.0) / 100.0));
return lerp(final, col , f);

} else{
return final;
}
}

// Marble fracal from https://www.shadertoy.com/view/MtX3Ws
fixed2 cmul(fixed2 a, fixed2 b) {
return fixed2(a.xb.x - a.yb.y, a.xb.y + a.yb.x);
}

fixed2 csqr(fixed2 a) {
return fixed2(a.xa.x - a.ya.y, 2.a.xa.y);
}

fixed marble_df(fixed3 p) {
fixed res = 0.;

fixed3 c = p;
fixed scale = 0.72;
const int max_iter = 10;
for (int i = 0; i < max_iter; ++i) {
p = scale*abs(p)/dot(p,p) - scale;
p.yz = csqr(p.yz);
p = p.zxy;
res += exp(-19. * abs(dot(p,c)));
}
return res;
}

fixed3 marble_march(fixed3 ro, fixed3 rd, fixed2 tminmax) {
fixed t = tminmax.x;
fixed dt = 0.02;
fixed3 col = fixed3(0.0,0.0,0.0);
fixed c = 0.;
const int max_iter = 64;
[unroll(100)]
for(int i = 0; i < max_iter; ++i) {
t += dtexp(-2.0c);
if(t>tminmax.y) {
break;
}
fixed3 pos = ro+t*rd;

  c = marble_df(ro+t*rd); 
  c *= 0.5;
    
  fixed dist = (abs(pos.x + pos.y-0.15))*10.0;
  fixed3 dcol = fixed3(c*c*c-c*dist, c*c-c, c);
  col = col + dcol;

}
const fixed scale = 0.005;
fixed td = (t - tminmax.x)/(tminmax.y - tminmax.x);
col = exp(-10.0td);
col *= scale;
return col;
}

fixed3 render1(fixed3 ro, fixed3 rd) {
fixed3 ipos = ro;
fixed3 ird = rd;

fixed its4 = IRAYSHAPE(ipos, ird);
return marble_march(ipos, ird, fixed2(0.0, its4));
}

fixed3 render(fixed3 ro, fixed3 rd) {
fixed3 skyCol = skyColor(ro, rd);
fixed3 col = fixed3(0.0,0.0,0.0);

fixed t = 1E6;
fixed ts4 = RAYSHAPE(ro, rd);
if (ts4 < miss) {
t = ts4;
fixed3 pos = ro + ts4*rd;
fixed3 nor = sphere4Normal(pos);
fixed3 refr = refract(rd, nor, refrIndex);
fixed3 refl = reflect(rd, nor);
fixed3 rcol = skyColor(pos, refl);
fixed fre = lerp(0.0, 1.0, pow(1.0-dot(-rd, nor), 4.0));

fixed3 lv   = lightPos - pos;
fixed ll2 = L2(lv);
fixed ll  = sqrt(ll2);
fixed3 ld   = lv / ll;

fixed dm  = min(1.0, 40.0/ll2);
fixed dif = pow(max(dot(nor,ld),0.0), 8.0)*dm;
fixed spe = pow(max(dot(reflect(-ld, nor), -rd), 0.), 100.);
fixed l   = dif;

fixed lin = lerp(0.0, 1.0, l);
const fixed3 lcol = 2.0*sqrt(sunCol);
col = render1(pos, refr);
fixed3 diff = hsv2rgb(fixed3(0.7, fre, 0.075*lin))*lcol;
col += fre*rcol+diff+spe*lcol;
if (refr == fixed3(0.0,0.0,0.0),0.0),0.0)) {
  // Not expected to happen as the refraction index < 1.0
  col = fixed3(1.0, 0.0, 0.0);
}

} else {
// Ray intersected sky
return skyCol;
}

return col;
}

fixed3 effect(fixed2 p, fixed2 q) {
fixed3 ro = 0.6fixed3(2.0, 0, 0.2)+fixed3(0.0, 0.75, 0.0);
ro.xz = ROT(PI/2.0+sin(TIME0.05));
ro.yz = ROT(0.5+0.25sin(TIME
0.05*sqrt(0.5))*0.5);

fixed3 ww = normalize(fixed3(0.0, 0.0, 0.0) - ro);
fixed3 uu = normalize(cross( fixed3(0.0,1.0,0.0), ww));
fixed3 vv = normalize(cross(ww,uu));
fixed rdd = 2.0;
fixed3 rd = normalize( p.xuu + p.yvv + rdd*ww);

fixed3 col = render(ro, rd);
return col;
}

fixed3 postProcess(fixed3 col, fixed2 q) {
col = clamp(col, 0.0, 1.0);
col = pow(col, fixed3(1.0/2.2,1.0/2.2,1.0/2.2));
col = col0.6+0.4colcol(3.0-2.0col);
col = lerp(col, fixed3(dot(col, fixed3(0.33,0.33,0.33))), -0.4);
col =0.5+0.5pow(19.0
q.xq.y(1.0-q.x)*(1.0-q.y),0.7);
return col;
}

VertexOutput vert (VertexInput v)
{
VertexOutput o;
o.pos = UnityObjectToClipPos (v.vertex);
o.uv = v.uv;
//VertexFactory
return o;
}
fixed4 frag(VertexOutput i) : SV_Target
{

fixed2 q = i.uv/RESOLUTION.xy;
fixed2 p = -1. + 2. * q;
p.x *= RESOLUTION.x/RESOLUTION.y;

fixed3 col = effect(p, q);
col = postProcess(col, q);

return fixed4(col, 1.0);

}
ENDCG
}

}
}

GLSL to HLSL issues

I am trying to convert GLSL from shadertoy to unity HLSL shaderlab. And I have below error messages:

  • error in 'ShaderMan/matrix3D': incorrect number of arguments to numeric-type constructor at line 81 (on d3d11)

  • invalid subscript "y" at line 124

Please help what is wrong with my code. Thanks. The original code from shadertoy(GLSL): https://www.shadertoy.com/view/4t3BWl

The converted code from unity shaderlab:
https://answers.unity.com/questions/1572270/glsl-to-hlsl.html

please help.
Thank you so much!

Not work

the website converter didn't work for this shader(https://www.shadertoy.com/view/XdB3Dw) can you convert it?
error:'mosaic': no matching 1 parameter function
Compiling Vertex program
Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_FULL_HDR

and

type mismatch
Compiling Vertex program
Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_FULL_HDR

Tools menu not showing in 2019.4

Thanks for what seems to be a wonderful tool. Sadly the shadertoy Unity editor menu is not loading in Unity 2019.4.

What is the most recent version of Unity known to be compatible?

Thanks in advance!

Type mismatch on line (d3d11)

Great resource!
Works on about half the shaders I've tried so far.

One common error I get is a 'Type mismatch' error (d3d11)

For instance on the following line
"fixed2x2 rot1=fixed2x2(cos(a1),sin(a1),-sin(a1),cos(a1));"

I think part of the problem in debugging is that the line indicated is not the REAL line causing the issue

In my case the actual line I think was 2 -3 lines further down
dir.xz*=rot1;

Which i fixed after searching other issues
#10
like so

dir.xz= mul(dir.xz,rot1);

Shader compiles but shows everything black

The shader has been successfully converted by the web tool (https://smkplus.github.io/ShaderMan.io/) but everything is black in Unity (using Unity 2020.1), and it's really hard to debug what's wrong.

I'm trying to convert this shader: https://www.shadertoy.com/view/WtyXzG
I've replaced 3D texture by a constant because I have no idea how to convert it to unity.

Here is a simplified version that still works in shadertoy:

void layer (out vec4 col, in vec3 uv, in float zoom, in float music) {
    
    vec2 baseUv = uv.xy;
    
    uv.xy *= mix(1.2, 0.001, zoom);
    
    float deCenter = length(uv);
    
    deCenter = min(1., deCenter * deCenter);

    vec2 smokeDin = vec2(-iTime + sin(uv.z*23.)*12.34, iTime + cos(uv.z*11.))*0.02;
    
    vec2 smokeUV = uv.xy;

    float texC = texture(iChannel3, smokeUV*13.+ smokeDin.yx*0.5).r
                *texture(iChannel3, smokeUV*15.*zoom*uv.y - smokeDin.yx*1.2).r*0.015;
    
    
    float texA = (1.- texture(iChannel3, smokeUV*0.6 - texC * 0.5 + smokeDin*0.2).r);
    
    float texB = 1.-texture(iChannel3, smokeUV *  (1.-texA*0.1 + texC * 0.4 * (.5-texA)) + smokeDin*0.1).r;
        

    texA *= (0.5 + texB)*0.25;

    texA *= texA * 8.* zoom * zoom * (1.-col.a) * deCenter;
    
    
    vec2 grid = uv.xy*10.;
    
    uv.xy = mod(grid,1.0);

    grid -= uv.xy;
    
    uv.xy-=0.5;
    
    
    vec4 add = vec4(0,0,0, texA);
    
    float depthMod = uv.z*0.123;
    
    float iTimeAndZoom = iTime + zoom;
    
    float cutMod = col.a * (64.) * music;
    
    float upscale =  (music * col.a * 20.);
    
    const float cuttingMod = 1.;
    
    float distMod =  (1. + texA* 50.  + cutMod)* max(0.1,  zoom - col.a*8.) ;
        
    for(int x=-1;x<=1;x++){
        for(int y=-1;y<=1;y++){
        
            vec2 dUv = uv.xy - vec2(x,y);
            vec2 dGrid = grid + vec2(x,y);

            vec3 vol = vec3(0.8);//texture(iChannel2, vec3(dGrid.xy*0.1+depthMod, (dGrid.x + iTimeAndZoom)*0.003 )).rgb ;

            float big = vol.b*vol.b * upscale;
            
            dUv += (vol.xy - .5)*1.5;
            
            
        
            // CIRCLES
            //dUv += normalize(-dUv.xy) * 0.2 * music  * vol.b;
            
            
            float len = length(dUv) +0.0001;
            
            float dist = big * distMod/len; 

            
            float cut = smoothstep(cuttingMod,.5,len);
            
            float ray = max(0., 1.-abs(dUv.x*dUv.y*300.))* cut * big;
            
            dist += ray;
            
            add.rgb +=  dist * cut * vol;
        }
    }

col += add * zoom * (1.-zoom);
    
    
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord/iResolution.xy;

    vec3 noise =  vec3(0.6);
        //texture(iChannel2, vec3(uv*123.123+iTime, iTime+uv.x*uv.y*543.21)).rgb;
    
    vec4 col = vec4(0,0,0,0);
    
    uv -= 0.5;
    
    vec2 M = (iMouse.xy - iResolution.xy * .5)/iResolution.y;
    
    uv += M;
    
    float aspect = iResolution.x/iResolution.y; 
    
    uv.x*=aspect;
        
    
    const float stepCnt =5.;
    const int steCntInt = 5;
    const float oneStep = 1./stepCnt;
    const float SPEED = 0.0;
    
    float zoom = iTime*SPEED;
    
    float index = floor(mod(zoom, 1.)*stepCnt);
    
    zoom = mod(zoom, oneStep);
    
    float off = 0.;
    
    float music = 0.;  
    
    for(int i=0;i<steCntInt;i++){
        
        float totalZoom = zoom + off;
        
        //music = texture(iChannel0, vec2(mix(0.01, 0.8, totalZoom),0.05)).x;

        // for Unseen: smoothstep(0.01,.4, music);    
        //music = smoothstep(-.2,1., music);
        music = 0.075;
        
        layer(col, vec3(uv.xy,index), totalZoom, music);
        off += oneStep;
        index = mod(index-1., stepCnt);
        
    }    
    
    col.rgb*=vec3(0.5,0.9,1) * 5. * oneStep;
    
    vec3 mixing = col.gbr+col.brg;
    
    col.rgb+= mixing * mixing * 0.1;
    
    col.rgb += noise*col.rgb*0.15;

    //col = clamp(col,0.,1.);
    
    fragColor = vec4(col.rgb,1.0);
}

Converted version with few issues fixed:

    Shader "ShaderMan/MyShader"
    {
    Properties{
    _MainTex("MainTex",2D) = "white"{} 
    _iMouse("Mouse", Vector) = (0,0,0,0)
_ThirdTex("ThirdTex",2D) = "white"{} 
_FourthTex("FourthTex",2D) = "white"{} 

    }
    SubShader
    {
    Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }
    Pass
    {
    ZWrite Off
    Blend SrcAlpha OneMinusSrcAlpha
    CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag
    #include "UnityCG.cginc"
            
    

    float4 vec4(float x,float y,float z,float w){return float4(x,y,z,w);}
    float4 vec4(float x){return float4(x,x,x,x);}
    float4 vec4(float2 x,float2 y){return float4(float2(x.x,x.y),float2(y.x,y.y));}
    float4 vec4(float3 x,float y){return float4(float3(x.x,x.y,x.z),y);}


    float3 vec3(float x,float y,float z){return float3(x,y,z);}
    float3 vec3(float x){return float3(x,x,x);}
    float3 vec3(float2 x,float y){return float3(float2(x.x,x.y),y);}

    float2 vec2(float x,float y){return float2(x,y);}
    float2 vec2(float x){return float2(x,x);}

    float vec(float x){return float(x);}
    
    

    struct VertexInput {
    float4 vertex : POSITION;
    float2 uv:TEXCOORD0;
    float4 tangent : TANGENT;
    float3 normal : NORMAL;
    //VertexInput
    };
    struct VertexOutput {
    float4 pos : SV_POSITION;
    float2 uv:TEXCOORD0;
    //VertexOutput
    };
    sampler2D _MainTex; 
sampler2D _ThirdTex; 
sampler2D _FourthTex; 
float4 _iMouse;

    
    VertexOutput vert (VertexInput v)
    {
    VertexOutput o;
    o.pos = UnityObjectToClipPos (v.vertex);
    o.uv = v.uv;
    //VertexFactory
    return o;
    }
    
    
void layer (out float4 col, in float3 uv, in float zoom, in float music)
{
    UNITY_INITIALIZE_OUTPUT(float4, col);
    float2 baseUv = uv.xy;
    
    uv.xy *= lerp(1.2, 0.001, zoom);
    
    float deCenter = length(uv);
    
    deCenter = min(1., deCenter * deCenter);

    float2 smokeDin = vec2(-_Time.y + sin(uv.z*23.)*12.34, _Time.y + cos(uv.z*11.))*0.02;
    
    float2 smokeUV = uv.xy;

    float texC = tex2D(_FourthTex, smokeUV*13.+ smokeDin.yx*0.5).r
                *tex2D(_FourthTex, smokeUV*15.*zoom*uv.y - smokeDin.yx*1.2).r*0.015;
    
    
    float texA = (1.- tex2D(_FourthTex, smokeUV*0.6 - texC * 0.5 + smokeDin*0.2).r);
    
    float texB = 1.-tex2D(_FourthTex, smokeUV *  (1.-texA*0.1 + texC * 0.4 * (.5-texA)) + smokeDin*0.1).r;
        

    texA *= (0.5 + texB)*0.25;

    texA *= texA * 8.* zoom * zoom * (1.-col.a) * deCenter;
    
    
    float2 grid = uv.xy*10.;
    
    uv.xy = fmod(grid,1.0);

    grid -= uv.xy;
    
    uv.xy-=0.5;
    
    
    float4 add = vec4(0,0,0, texA);
    
    float depthMod = uv.z*0.123;
    
    float timeAndZOom = _Time.y + zoom;
    
    float cutMod = col.a * (64.) * music;
    
    float upscale =  (music * col.a * 20.);
    
    const float cuttingMod = 1.;
    
    float distMod =  (1. + texA* 50.  + cutMod)* max(0.1,  zoom - col.a*8.) ;
        
    [unroll(100)]
for(int x=-1;x<=1;x++){
        [unroll(100)]
for(int y=-1;y<=1;y++){
        
            float2 dUv = uv.xy - vec2(x,y);
            float2 dGrid = grid + vec2(x,y);

            float3 vol = vec3(0.7);//tex2D(_ThirdTex, vec3(dGrid.xy*0.1+depthMod, (dGrid.x + _Time.yAndZoom)*0.003 )).rgb ;

            float big = vol.b*vol.b * upscale;
            
            dUv += (vol.xy - .5)*1.5;
            
            
        
            // CIRCLES
            //dUv += normalize(-dUv.xy) * 0.2 * music  * vol.b;
            
            
            
            
            
            float len = length(dUv) +0.0001;
            
            float dist = big * distMod/len; 

            
            float cut = smoothstep(cuttingMod,.5,len);
            
            float ray = max(0., 1.-abs(dUv.x*dUv.y*300.))* cut * big;
            
            dist += ray;
            
            add.rgb +=  dist * cut * vol;
        }
    }

col += add * zoom * (1.-zoom);
    
    
}
    fixed4 frag(VertexOutput vertex_output) : SV_Target
    {
    
    float2 uv = vertex_output.uv/1;

    float3 noise =  vec3(0.6);
        //tex2D(_ThirdTex, vec3(uv*123.123+_Time.y, _Time.y+uv.x*uv.y*543.21)).rgb;
    
    float4 col = vec4(0,0,0,0);
    
    uv -= 0.5;
    
    float2 M = (_iMouse.xy - 1 * .5)/1;
    
    uv += M;
    
    float aspect = 1/1; 
    
    uv.x*=aspect;
        
    
    const float stepCnt =5.;
    const int steCntInt = 5;
    const float oneStep = 1./stepCnt;
    const float SPEED = 0.0;
    
    float zoom = _Time.y*SPEED;
    
    float index = floor(fmod(zoom, 1.)*stepCnt);
    
    zoom = fmod(zoom, oneStep);
    
    float off = 0.;
    
    float music = 0.;  
    
    [unroll(100)]
for(int i=0;i<steCntInt;i++){
        
        float totalZoom = zoom + off;
        
        //music = tex2D(_MainTex, vec2(lerp(0.01, 0.8, totalZoom),0.05)).x;

        // for Unseen: smoothstep(0.01,.4, music);    
        //music = smoothstep(-.2,1., music);
        music = 0.075;
        
        layer(col, vec3(uv.xy,index), totalZoom, music);
        off += oneStep;
        index = fmod(index-1., stepCnt);
        
    }    
    
    col.rgb*=vec3(0.5,0.9,1) * 5. * oneStep;
    
    float3 lerping = col.gbr+col.brg;
    
    col.rgb+= lerping * lerping * 0.1;
    
    col.rgb += noise*col.rgb*0.15;

    //col = clamp(col,0.,1.);
    
    return vec4(col.rgb,1.0);

    }
    ENDCG
    }
}
}

This compiles but gives a black screen.
Could you please advise what could go wrong?

"mod()" conversion from Shadertoy to Unity is inaccurate.

I was trying to get this shader running in Unity, and while the original ShaderMan conversion had many errors that I could fix just by intuitively going between the Unity .shader file, the original ShaderToy upload file, and this primitive guide, there was still a weird difference between the .shader's results and the original. After lots of trial and error, I found out from the last response in this forum thread that the HLSL fmod() function that ShaderMan used to replace usages of GLSL's mod() is inaccurate to the math that mod() does in GLSL. The easiest way to get the same functionality in HLSL is to#define a new mod() as such:

#define mod(x, y) (x - y * floor(x / y))

Using transformation matrix leads to type mismatch

The error is as described in this post:
https://forum.unity.com/threads/using-transformation-matrix-leads-to-type-mismatch.466548/

I met the error trying to convert this shader:
https://www.shadertoy.com/view/XlfGRj

The actual code part in which the bug lies was the following.
After conversion I was given:

fixed3 dir=fixed3(uv*zoom,1.);
//... ... ...
fixed2x2 rot1=fixed2x2(cos(a1),sin(a1),-sin(a1),cos(a1));
//... ... ...
dir.xz*=rot1;

While the last line from the result as shown above, should be like this in order to work in Unity:

//...
dir.xz = mul(rot1, dir.xz); //dir.xz*=rot1;

Generated shader is gibberish

I'm trying to convert the following shader https://www.shadertoy.com/view/MdSfWK using Unity 2020.3.26f1 and receive the following error:

ArgumentNullException: Value cannot be null.
Parameter name: shader
UnityEngine.Material..ctor (UnityEngine.Shader shader) (at :0)
ShaderConverterEditor.CreateShader () (at Assets/Editor/ShaderConverterEditor.cs:110)
ShaderConverterEditor.OnGUI () (at Assets/Editor/ShaderConverterEditor.cs:51)
UnityEditor.HostView.OldOnGUI () (at <55729f52d042492e9efc384182ae2feb>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at :0)
UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect, System.Action onGUIHandler, System.Boolean canAffectFocus) (at :0)
UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Action onGUIHandler, System.Boolean canAffectFocus) (at :0)
UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Boolean canAffectFocus) (at :0)
UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUIRaw (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at :0)
UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUI (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at :0)
UnityEngine.UIElements.IMGUIContainer.HandleEvent (UnityEngine.UIElements.EventBase evt) (at :0)
UnityEngine.UIElements.CallbackEventHandler.HandleEventAtTargetPhase (UnityEngine.UIElements.EventBase evt) (at :0)
UnityEngine.UIElements.MouseCaptureDispatchingStrategy.DispatchEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at :0)
UnityEngine.UIElements.EventDispatcher.ApplyDispatchingStrategies (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, System.Boolean imguiEventIsInitiallyUsed) (at :0)
UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at :0)
UnityEngine.UIElements.EventDispatcher.ProcessEventQueue () (at :0)
UnityEngine.UIElements.EventDispatcher.OpenGate () (at :0)
UnityEngine.UIElements.EventDispatcherGate.Dispose () (at :0)
UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at :0)
UnityEngine.UIElements.EventDispatcher.Dispatch (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, UnityEngine.UIElements.DispatchMode dispatchMode) (at :0)
UnityEngine.UIElements.BaseVisualElementPanel.SendEvent (UnityEngine.UIElements.EventBase e, UnityEngine.UIElements.DispatchMode dispatchMode) (at :0)
UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at :0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& eventHandled) (at :0)
UnityEngine.UIElements.UIEventRegistration.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at :0)
UnityEngine.UIElements.UIEventRegistration+<>c.<.cctor>b__1_2 (System.Int32 i, System.IntPtr ptr) (at :0)
UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& result) (at <1c34070ddd5b426b8f32df1db927aad1>:0)

There is a CodeGenerator in the scene and I am supplying a shader name. The program will generate a shader file with the name but the contents are repetitive gibberish like the following line:

i.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvSi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvhi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvai.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvdi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvei.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvri.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uv i.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uv"i.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvSi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvhi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvai.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvdi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvei.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvri.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvMi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvai.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvni.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uv/i.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvSi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvci.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvri.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvii.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvbi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvbi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvli.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvei.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvSi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvhi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvai.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvdi.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvei.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uvri.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uv"i.uvfi.uvri.uvai.uvgi.uvCi.uvoi.uvli.uvoi.uvri.uv

Licence?

There's something in the readme but I'm not a lawyer. It sounds like an attempt to apply CC-NC to code which would make this project difficult for anyone else to contribute to or use in other open source projects. Was this your intention?

It would be best to choose an existing well understood source code licence. If you do want it to be open source then a non-commercial clause might be problemmatic: https://www.quora.com/What-is-the-best-free-for-non-commercial-use-license-to-use-for-an-open-source-project

Broken Converter

I heard a lot about this converter not working correctly anymore, and it not working for me too, so here's the shader I want to be converted.
#define t iTime
mat2 m(float a){float c=cos(a), s=sin(a);return mat2(c,-s,s,c);}
float map(vec3 p){
p.xz*= m(t0.4);p.xy= m(t0.3);
vec3 q = p
2.+t;
return length(p+vec3(sin(t*0.7)))*log(length(p)+1.) + sin(q.x+sin(q.z+sin(q.y)))*5.5 - 1.;
}

void mainImage( out vec4 fragColor, in vec2 fragCoord ){
vec2 p = fragCoord.xy/iResolution.y - vec2(.9,.5);
vec3 cl = vec3(0.);
float d = .9;
for(int i=0; i<=5; i++) {
vec3 p = vec3(0,0,5.) + normalize(vec3(p, -1.))d;
float rz = map(p);
float f = clamp((rz - map(p+.1))0.5, -.1, 1. );
vec3 l = vec3(.32, .24, .49) + vec3(.53, .48, .61)f;
cl = cl
l + (1.-smoothstep(0., 2.5, rz))
.7
l;
d += min(rz, 1.);
}
fragColor = vec4(cl, 1.);
}
Original website: https://www.shadertoy.com/view/wdjSRc

[API] Convert from link

I was about to start such project, when I stumbled on this. Pretty good work!

A fun enhancement can be working with https://www.shadertoy.com/api

So from a link, one can regex the shader id, download meta data, and then download code, textures and such, convert the shader, and create a material and assigning the downloaded texture!

Next step can be downloading the audio and assigning it to an audio source.

These are my thoughts, I can help with this

Shaders don't compile

I have tried converting the sample shader https://www.shadertoy.com/view/4dl3zn in Unity 5 and Unity 2018 but I get the compile error "Shader error in 'ShaderMan/bubbles': syntax error: unexpected end of file at line 86 (on d3d11)"

There's already a bubbles shader in the examples folder, but it's content looks a lot different then what is being converted now?

Direct2D Support

I found the tool after I have already converted lots of shaders in HLSL. It seems interesting, it could be nice if you can add Direct2D pixel shader support.

Direct2D HLSL has a factor passed as uw in the coordinates main function so the coordinates passed to the main can be converted to [0,1].

In Turbo Play I use this set of wrappers:


float2 FindSpace(float2 MV)
{
    float2 LastSample = float2(0, 0) + float2(center.x*2,center.y * 2)* MV;
    return LastSample;
}

float2 GetNormalized(float2 UV,float2 MV)
{
    float2 s = FindSpace(MV);
    return UV / s;
}

float2 FromNormalized(float2 UV, float2 MV)
{
    float2 s = FindSpace(MV);
    return UV * s;
}


See more at https://docs.microsoft.com/en-us/windows/win32/direct2d/custom-effects

HLSL shader compiles, but displays as black

I've successfully translated several shaders via @smkplus' ShaderMan (in Unity, and via your web app).

However, in the attached example this shader compiled with a simple fix (see below), but the resulting compiled shader displays as black in Unity 5.6.x.

If the community has any suggestions I'd love to understand.

The only change I made from the ShaderMan output is this simple adaptation below:

	float3 rd = normalize(camera(ro, la)*vec3(uv, 1.97));

I replaced the explicit multiplication with the mul() method:
float3 rd = normalize(mul(camera(ro, la), vec3(uv, 1.97)) );

Thanks again for a great tool!

server.zip

Web tool broken?

I am trying to use your web tool, but it doesn't finish loading due to a JavaScript syntax error.

image

It says there is an "invalid regular expression flag s" on line 486 of ShaderMan.io

Shader not compiling in 2020.3.x

Tried a bunch...none are compiling properly. Don't know why yet...pink materials only. (not because URP/HDRP, but because Unity couldn't compile the shaders)

Shader doesnt convert

I have tried to compile https://www.shadertoy.com/view/MddSRB#, but it does not work.
I tried it on the web, but it failed.
In Unity, I'm getting the error Shader error in 'ShaderMan/MyShader': undeclared identifier 'U' at line 70 (on metal).

Shader "ShaderMan/MyShader"
{
Properties{
_MainTex("MainTex",2D) = "white"{} 

}
SubShader
{
Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
		


float4 vec4(float x,float y,float z,float w){return float4(x,y,z,w);}
float4 vec4(float x){return float4(x,x,x,x);}
float4 vec4(float2 x,float2 y){return float4(float2(x.x,x.y),float2(y.x,y.y));}
float4 vec4(float3 x,float y){return float4(float3(x.x,x.y,x.z),y);}


float3 vec3(float x,float y,float z){return float3(x,y,z);}
float3 vec3(float x){return float3(x,x,x);}
float3 vec3(float2 x,float y){return float3(float2(x.x,x.y),y);}

float2 vec2(float x,float y){return float2(x,y);}
float2 vec2(float x){return float2(x,x);}

float vec(float x){return float(x);}



struct VertexInput {
float4 vertex : POSITION;
float2 uv:TEXCOORD0;
float4 tangent : TANGENT;
float3 normal : NORMAL;
//VertexInput
};
struct VertexOutput {
float4 pos : SV_POSITION;
float2 uv:TEXCOORD0;
//VertexOutput
};
sampler2D _MainTex; 


VertexOutput vert (VertexInput v)
{
VertexOutput o;
o.pos = UnityObjectToClipPos (v.vertex);
o.uv = v.uv;
//VertexFactory
return o;
}





fixed4 frag(VertexOutput vertex_output) : SV_Target
{

float2 R = 1; U = (U+U-R)/R.y; 
U = vec2(atan2(U.x,U.y)*3./3.1416,log(length(U))); // conformal polar
// multiply U for smaller tiles
U.y += U.x/6.; // comment for concentric circles instead of spiral
O = tex2D(_MainTex, frac(-U+iDate.w));

}
ENDCG
}

}
}

no matching 3 parameter intrinsic function

Shader error in 'ShaderMan/Wythoff': 'tex2D': no matching 3 parameter intrinsic function; Possible intrinsic functions are: tex2D(sampler2D, float2|half2|min10float2|min16float2) tex2D(sampler2D, float2|half2|min10float2|min16float2, float2|half2|min10float2|min16float2, float2|half2|min10float2|min16float2) at line 125 (on metal)

Compiling Vertex program
Platform defines: UNITY_NO_DXT5nm UNITY_ENABLE_REFLECTION_BUFFERS UNITY_NO_CUBEMAP_ARRAY UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_COLORSPACE_GAMMA UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_DLDR_ENCODING

https://www.shadertoy.com/view/Md3yRB

Issues with function fmod, numeric type constructor, matrix multiplication

Recently I created simple shader to test ShaderMan converter.
ShaderToy code:
mat3 rotationX( float x)
{
return mat3
(
1.0,0.0,0.0,
0.0,cos(x),sin(x),
0.0,-sin(x),cos(x)
);
}
float map (vec3 p)
{
vec2 t=vec2(0.20,0.1);
vec2 q = vec2(sqrt( p.x*p.x + p.z*p.z )-t.x,p.y);
q = q*q; q = q*q;q = q*q;
float s = pow( q.x + q.y, 0.125 )-t.y;
vec3 h = vec3(atan(p.x,p.z)/6.2831,p.y,0.02+0.5*length(p));
vec3 g = mod(h,vec3(0.05,1.0,0.05))-0.5*vec3(0.05,1.0,0.05);
vec2 d = (vec2(length(g.xz),g.y)) - vec2(0.02,0.6);
float u = -(min(max(d.x,d.y),0.0) + abs(max(d.x,0.0)));
return max( s,u);
}
vec3 set_normal (vec3 p)
{
vec3 x = vec3 (0.001,0,0);
vec3 y = vec3 (0,0.001,0);
vec3 z = vec3 (0,0,0.001);
return normalize(vec3 (map(p+x)-map(p-x),map(p+y)-map(p-y),map(p+z)-map(p-z)));
}
vec4 lighting (vec3 ro,vec3 rd)
{
vec4 AmbientLight = vec4 (0.2);
vec3 LightDirection = normalize(vec3(0,0,-20));
vec3 NormalDirection = set_normal(ro);
vec4 LightColor = vec4(0.7) ;
return max(dot(LightDirection,NormalDirection),0.0)*LightColor+AmbientLight;
}
vec4 raymarch (vec3 ro, vec3 rd)
{
for (int i=0;i<128;i++)
{
float t = map (ro);
if (t<0.001) return lighting(ro,rd);
ro+=t*rd;
}
return vec4(0.0,0.0,0.0,1.0);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = (2.0 * fragCoord.xy - iResolution.xy) / iResolution.y;
vec3 ro = vec3 (0,0.35,-0.75);
vec3 rd = normalize(vec3(uv,2.0)*rotationX(-0.5));
fragColor = raymarch(ro,rd);
}

Converter doesn't translate matrix multiplication properly (should be "mul" function, not * operator), also not generate correct number of arguments for HLSL variables (for example AmbientLight).
Also there are differences between GLSL "mod" and HLSL "fmod".
In the most of cases direct "mod" to "fmod" conversion is enough, but in above shader it doesn't work properly. Here is my solution with source code:

https://github.com/przemyslawzaworski/Unity3D-CG-programming/blob/master/gear_wheel.shader

Explanation :
HLSL fmod:
float3 fmod(float3 x, float3 y)
{
return x - y * trunc(x/y);
}
GLSL mod:
vec3 mod(vec3 x, vec3 y)
{
return x - y * floor(x/y);
}

Julia - Quaternion not converting

Hiya! Thanks so much for making this tool.
So I'm trying to get this shader working: https://www.shadertoy.com/view/MsfGRr

and I get this error message after converting:
Shader error in 'ShaderMan/Juila': 'abs': no matching 3 parameter intrinsic function; Possible intrinsic functions are: abs(float|half|double|min10float|min16float|int|uint|min12int|min16int|min16uint) at line 101 (on d3d11)

Any help appreciated.

Also- Is there a way to have Unity lights affect the surface of the object in the shader? Or a way to expose change of color and or material properties like roughness/ metalness/ specularity?

type mismatch (metal)

Tried converting the shader below in Unity 2018.1.2 and received this error -

Shader error in 'ShaderMan/Seascape': type mismatch at line 125 (on metal)

Compiling Vertex program
Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_COLORSPACE_GAMMA UNITY_LIGHT_PROBE_PROXY_VOLUME UNITY_LIGHTMAP_RGBM_ENCODING

https://www.shadertoy.com/view/Ms2SD1

Every single shader broken in unity 2018.4.20.f1

Shader "ShaderMan/MyShader"
{
Properties{
_MainTex("MainTex",2D) = "white"{} 

}
SubShader
{
Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
		


float4 vec4(float x,float y,float z,float w){return float4(x,y,z,w);}
float4 vec4(float x){return float4(x,x,x,x);}
float4 vec4(float2 x,float2 y){return float4(float2(x.x,x.y),float2(y.x,y.y));}
float4 vec4(float3 x,float y){return float4(float3(x.x,x.y,x.z),y);}


float3 vec3(float x,float y,float z){return float3(x,y,z);}
float3 vec3(float x){return float3(x,x,x);}
float3 vec3(float2 x,float y){return float3(float2(x.x,x.y),y);}

float2 vec2(float x,float y){return float2(x,y);}
float2 vec2(float x){return float2(x,x);}

float vec(float x){return float(x);}



struct VertexInput {
float4 vertex : POSITION;
float2 uv:TEXCOORD0;
float4 tangent : TANGENT;
float3 normal : NORMAL;
//VertexInput
};
struct VertexOutput {
float4 pos : SV_POSITION;
float2 uv:TEXCOORD0;
//VertexOutput
};
sampler2D _MainTex; 


VertexOutput vert (VertexInput v)
{
VertexOutput o;
o.pos = UnityObjectToClipPos (v.vertex);
o.uv = v.uv;
//VertexFactory
return o;
}

// Created by inigo quilez - iq/2013

// Turbulence and Day/Night cycle added by Michael Olson - OMGparticles/2015
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

// Volumetric clouds. It performs level of detail (LOD) for faster rendering and antialiasing

float fTurbulence = 0.35;
float fSunSpeed = 0.35;

float3 vNightColor = vec3(.15, 0.3, 0.6);
float3 vHorizonColor = vec3(0.6, 0.3, 0.4);
float3 vDayColor = vec3(0.7,0.8,1);

float3 vSunColor = vec3(1.0,0.8,0.6);
float3 vSunRimColor = vec3(1.0,0.66,0.33);

float3 v3sunDir;
void updateSun() {
float fSpeed = fSunSpeed * _Time.y;
v3sunDir = normalize( vec3(cos(fSpeed),sin(fSpeed),0.0) );
}

float noise( in float3 x )
{
float3 p = floor(x);
float3 f = frac(x);
f = fff*(3.0-2.0*f);
float2 uv = (p.xy+vec2(37.0,17.0)p.z) + f.xy;
float4 rg = tex2D( _MainTex, (uv+ 0.5)/256.0, -100.0 );
return (-1.0+2.0
lerp( rg.g, rg.r, f.z ));
}

float map5( in float3 p )
{
float3 q = p - vec3(0.0,0.1,1.0)_Time.y;
float f;
f = 0.50000
noise( q ); q = q2.02 + _Time.y * fTurbulence * 1.0;
f += 0.25000
noise( q ); q = q2.03 + _Time.y * fTurbulence * 2.0;
f += 0.12500
noise( q ); q = q2.01 + _Time.y * fTurbulence * 4.0;
f += 0.06250
noise( q ); q = q2.02 + _Time.y * fTurbulence * 8.0;
f += 0.03125
noise( q );
return clamp( 1.5 - p.y - 2.0 + 1.75*f, 0.0, 1.0 );
}

float map4( in float3 p )
{
float3 q = p - vec3(0.0,0.1,1.0)_Time.y;
float f;
f = 0.50000
noise( q ); q = q2.02 + _Time.y * fTurbulence * 1.0;
f += 0.25000
noise( q ); q = q2.03 + _Time.y * fTurbulence * 2.0;
f += 0.12500
noise( q ); q = q2.01 + _Time.y * fTurbulence * 4.0;
f += 0.06250
noise( q );
return clamp( 1.5 - p.y - 2.0 + 1.75f, 0.0, 1.0 );
}
float map3( in float3 p )
{
float3 q = p - vec3(0.0,0.1,1.0)
_Time.y;
float f;
f = 0.50000noise( q ); q = q2.02 + _Time.y * fTurbulence * 1.0;
f += 0.25000noise( q ); q = q2.03 + _Time.y * fTurbulence * 2.0;
f += 0.12500noise( q );
return clamp( 1.5 - p.y - 2.0 + 1.75
f, 0.0, 1.0 );
}
float map2( in float3 p )
{
float3 q = p - vec3(0.0,0.1,1.0)_Time.y;
float f;
f = 0.50000
noise( q ); q = q2.02 + _Time.y * fTurbulence * 1.0;
f += 0.25000
noise( q );
return clamp( 1.5 - p.y - 2.0 + 1.75*f, 0.0, 1.0 );
}

float4 integrate( in float4 sum, in float dif, in float den, in float3 bgcol, in float t )
{
// lighting
float3 lin = vec3(0.9,0.95,1.0) + 0.5vec3(0.7, 0.5, 0.3)dif * smoothstep(-0.3, 0.3, v3sunDir.y);
float4 col = vec4( lerp( 1.15
vec3(1.0,0.95,0.8), vec3(0.65), den ), den );
col.xyz = lin;
//col.xyz = lerp( col.xyz, bgcol, 1.0-exp(-0.003
t
t) );
// front to back blending
col.a *= 0.4;
col.rgb = col.a;
return sum + col
(1.0-sum.a);
}

#define MARCH(STEPS,MAPLOD) [unroll(100)]
for(int i=0; i<STEPS; i++) { float3 pos = ro + trd; if( pos.y<-3.0 || pos.y>2.0 || sum.a > 0.99 ) break; float den = MAPLOD( pos ); if( den>0.01 ) { float dif = clamp((den - MAPLOD(pos+0.3v3sunDir))/0.6, 0.0, 1.0 ); sum = integrate( sum, dif, den, bgcol, t ); } t += max(0.01float(i),0.02t); }

float4 raymarch( in float3 ro, in float3 rd, in float3 bgcol )
{
float4 sum = vec4(0.0);

float t = 0.0;

MARCH(20,map5);
MARCH(30,map4);
MARCH(40,map3);
MARCH(50,map2);

return clamp( sum, 0.0, 1.0 );

}

float3x3 setCamera( in float3 ro, in float3 ta, float cr )
{
float3 cw = normalize(ta-ro);
float3 cp = vec3(sin(cr), cos(cr),0.0);
float3 cu = normalize( cross(cw,cp) );
float3 cv = normalize( cross(cu,cw) );
return float3x3( cu, cv, cw );
}

float4 render( in float3 ro, in float3 rd )
{
float sun = clamp( dot(v3sunDir,rd), 0.0, 1.0 );

float fSunHeight = v3sunDir.y;

// below this height will be full night color
float fNightHeight = -0.8;
// above this height will be full day color
float fDayHeight   = 0.3;

float fHorizonLength = fDayHeight - fNightHeight;
float fInverseHL = 1.0 / fHorizonLength;
float fHalfHorizonLength = fHorizonLength / 2.0;
float fInverseHHL = 1.0 / fHalfHorizonLength;
float fMidPoint = fNightHeight + fHalfHorizonLength;

float fNightContrib = clamp((fSunHeight - fMidPoint) * (-fInverseHHL), 0.0, 1.0);
float fHorizonContrib = -clamp(abs((fSunHeight - fMidPoint) * (-fInverseHHL)), 0.0, 1.0) + 1.0;
float fDayContrib = clamp((fSunHeight - fMidPoint) * ( fInverseHHL), 0.0, 1.0);

// sky color
float3 vSkyColor = vec3(0.0);
vSkyColor += lerp(vec3(0.0),   vNightColor, fNightContrib);   // Night
vSkyColor += lerp(vec3(0.0), vHorizonColor, fHorizonContrib); // Horizon
vSkyColor += lerp(vec3(0.0),     vDayColor, fDayContrib);     // Day

float3 col = vSkyColor;

// atmosphere brighter near horizon
col -= clamp(rd.y, 0.0, 0.5);

// draw sun
col += 0.4 * vSunRimColor * pow( sun,    4.0 );
col += 1.0 * vSunColor    * pow( sun, 2000.0 );

// stars
float fStarSpeed = -fSunSpeed * 0.5;

float fStarContrib = clamp((fSunHeight - fDayHeight) * (-fInverseHL), 0.0, 1.0);

float3 vStarDir = rd * float3x3( vec3(cos(fStarSpeed), -sin(fStarSpeed), 0.0),
                           vec3(sin(fStarSpeed),  cos(fStarSpeed), 0.0),
                           vec3(0.0,             0.0,            1.0));
                          
col += pow((tex2D(_MainTex, vStarDir.xy).r + tex2D(_MainTex, vStarDir.zy).r) * 0.5, 42.0) * fStarContrib * 40.0;

// raymarch clouds
float4 res = raymarch( ro, rd, col );

// partially tint clouds to match sky color
res *= vec4(pow(vSkyColor, vec3(0.25)), 1.0);
    
col = col*(1.0-res.w) + res.xyz;

return vec4( col, 1.0 );

}

fixed4 frag(VertexOutput vertex_output) : SV_Target
{

float2 p = (-1 + 2.0*vertex_output.uv)/ 1;

float2 m = _iMouse.xy/1;

updateSun();

// camera
float3 ro = 4.0*normalize(vec3(sin(6.28*m.x + 1.5), 0.4 * m.y, cos(6.28*m.x + 1.5)));
float3 ta = vec3(0.0, -1.0, 0.0);
float3x3 ca = setCamera( ro, ta, 0.0 );
// ray
float3 rd = ca * normalize( vec3(p.xy,1.5));

return render( ro, rd );

}

void mainVR( out float4 fragColor, in float2 vertex_output.uv, in float3 fragRayOri, in float3 fragRayDir )
{
return render( fragRayOri, fragRayDir );

}
ENDCG
}

}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.