yum-mirror/slang
Making it easier to work with shaders
git clone https://git.yummers.dev/yum-mirror/slang
78d34f3b3
master
1// example-effect.slang 2 3// This file provides an example of how a shader 4// toy effect can be compiled as a Slang module. 5// 6// Every effect will depend on the module that 7// defines out shader toy infrastructure: 8// 9import shader_toy; 10 11// The `shader_toy` module defines the interface 12// that each effect must implement, and our 13// specific effect will be a type that implements 14// the interface: 15// 16struct ExampleEffect : IShaderToyImageShader 17{ 18 // Our goal is that we can mostly just copy-paste 19 // the code for an effect from shadertoy.com into 20 // this file, and have something that works. 21 // 22 // Due to limitations in compatibility between 23 // GLSL and Slang, that won't always work, but 24 // it still helps to note where the original 25 // GLSL code begins/ends. 26 27 // Note: the verison of this file that is checked 28 // in uses a placeholder effect so that this file 29 // does not need to concern itself with the license 30 // terms of particular effects on shadertoy.com. 31 32// BEGIN GLSL 33 34float rand(float n) 35{ 36 return fract(sin(n) * 43758.5453123); 37} 38 39void mainImage(out vec4 fragColor, in vec2 fragCoord) 40{ 41 float screenScale = length(iResolution.xy); 42 vec2 uv = fragCoord / screenScale; 43 44 float frequency = 5.0f; 45 vec2 pos = (uv + iTime*vec2(0.25f, 0.0f)) * frequency; 46 47 vec2 center = floor(pos + vec2(0.5)); 48 49 float r0 = rand(center.x*3.0f + center.y*7.0f); 50 float r1 = rand(center.x*7.0f + center.y*13.0f); 51 float r2 = rand(center.x*13.0f + center.y*3.0f); 52 53 float p = mix(0.0f, 4.0f, r0); 54 float f = mix(5.0f, 8.0f, r1); 55 56 float a = 0.5f * (1.0f + cos(iTime*f + p)); 57 58 float rad0 = mix(0.1, 0.4, r2); 59 float rad1 = mix(0.2, 0.9, r0); 60 61 float radius = 0.5f*mix(rad0, rad1, a); 62 63 vec2 delta = pos - center; 64 float distance = length(delta); 65 66 fragColor.xyz = vec3(r0, r1, r2); 67 fragColor.w = 1.0f; 68 69 if(distance > radius) fragColor.xyz = vec3(0.25f); 70} 71 72// END GLSL 73 74 // The GLSL logic for the effect above might have included 75 // "global" declarations (which become fields since things 76 // are wrapped in a `struct`) with initializer, and we 77 // need a way for the code that uses an effect like this 78 // to get an instance that has been properly initialized. 79 // 80 // Right now, the `IShaderToyImageShader` interface requires 81 // a factory function `getDefault()`, so we will implement 82 // that here. 83 // 84 static This getDefault() 85 { 86 // Note: this code does not need to be updated for different 87 // GLSL effects, since it will default-initialize whatever 88 // members the `This` types has. 89 // 90 This value = {}; 91 return value; 92 } 93}