Giter Site home page Giter Site logo

hecomi / uraymarching Goto Github PK

View Code? Open in Web Editor NEW
1.3K 67.0 130.0 35.38 MB

Raymarching Shader Generator in Unity

Home Page: http://tips.hecomi.com/entry/2019/01/27/233137

License: MIT License

C# 5.80% ShaderLab 38.79% HLSL 52.11% GLSL 3.30%
unity raymarching shader

uraymarching's Introduction

uRaymarching

uRaymarching is a raymarching shader templates using uShaderTemplate. The following functions are implemented:

  • Create a ray-marching object by simply writing a distance function
  • Legacy pipelines (Forward / Deferred) and URP (Forward / Deferred) are supported
    • HDRP is not yet supported
  • Intersects polygonal objects because it writes depth
  • VR support
  • Lit / Unlit (+ Transparent)
  • Shadows for Directional / Spot / Point lights
  • Object-space and full-screen (Full screen only for legacy pipelines)

Screenshots

The following shapes are rendered inside a 12-polygon cube.

Check more examples here:

Install

  • Unity Package
  • Git URL (UPM)
    • Add the following git URLs to Package Manager.
      • https://github.com/hecomi/uShaderTemplate.git#upm
      • https://github.com/hecomi/uRaymarching.git#upm
  • Scoped Registry (UPM)
    • Add a scoped registry to your project.
      • URL: https://registry.npmjs.com
      • Scope: com.hecomi
    • Install uRaymarching in Package Manager.

How to use

  1. Select Create > Shader > uShaderTemplate > Generator in the Project view.
  2. Input Shader Name and select Shader Template from Inspector.
  3. Edit items in Conditions, Variables, Properties, Distance Function, and Post Effect.
  4. Press Export button or Ctrl + R to create shader from the Generator.
  5. Create material in the Project view (or press Create Material button).
  6. Create Cube in the Hierarchy view.
  7. Apply the generated material to the cube.

Please also see uShaderTemplate to learn the detail of shader generation function.

Inspector

The UI is generated by uShaderTemplate automatically from template files located in the Assets/uRaymarching/Editor/Resources/ShaderTemplates.

Shader Templates

  • Forward > Standard
    • The lighting is done by the same method as a standard surface shader in ForwardBase/Add pass.
  • Forward > Unlit
    • No lighting by default so you have to write output colors manually.
  • Deferred > Standard
    • The lighting is done by the same method as a standard surface shader.
  • Deferred > Direct GBuffer
    • Write values directly into GBuffers without effects like GI and LightProbe.
  • UniversalRP > Lit
    • Same lighting as the built-in Universal Render Pipelin/Lit shader.
  • UniversalRP > Unlit
    • No lighting, and same as the built-in Universal Render Pipelin/Unlit shader.

The items in Conditions and Variables are different depending on the selected template. Please see each page for further details:

Properties

This block is inserted into a Property section in a shader.

[Header(Additional Parameters)]
_Grid("Grid", 2D) = "" {}

Distance Function

Write a distance function here. The following code is the one generating the example of morphing sphere in Screenshots section in this document.

inline float DistanceFunction(float3 pos)
{
    float r = abs(sin(2 * PI * _Time.y / 2.0));
    float d1 = RoundBox(Repeat(pos, float3(6, 6, 6)), 1 - r, r);
    float d2 = Sphere(pos, 3.0);
    float d3 = Plane(pos - float3(0, -3, 0), float3(0, 1, 0));
    return SmoothMin(SmoothMin(d1, d2, 1.0), d3, 1.0);
}

Math.cginc and Primitives.cginc are included in the generated shader, so in this example some functions like RoundBox() and Repeat() come from these include files (of cource you can write them by yourself).

Post Effect

Post Effect is similar to a surface function in a surface shader. The following code is used in the hexagon-tile example in Screenshots section.

float4 _TopColor;

inline void PostEffect(RaymarchInfo ray, inout PostEffectOutput o)
{
    float3 localPos = ToLocal(ray.endPos);
    o.Emission += smoothstep(0.48, 0.50, localPos.y) * _TopColor;
    o.Occlusion *= 1.0 - 1.0 * ray.loop / ray.maxLoop;
}

RaymarchInfo is the input and the output of a raymarching calculation and this is defined in Struct.cginc.

struct RaymarchInfo
{
    // Input
    float3 startPos;    // start position of ray
    float3 rayDir;      // ray direction
    float3 projPos;     // ComputeScreenPos-applied position
    float3 polyNormal;  // normal on polygon surface
    float minDistance;  // minimum ray distance (comes from material setting)
    float maxDistance;  // maximum ray distance (changes by the raymarching setting)
    int maxLoop;        // maximum number of loop (comes from material setting)

    // Output
    int loop;           // total number of loop of the calculation (<= maxLoop)
    float3 endPos;      // last position (= surface of the distance function)
    float lastDistance; // the final distance of the raymarching
    float totalLength;  // total ray length
    float depth;        // depth (encoded)
    float3 normal;      // normal (encoded)
};

So ray.loop / ray.maxLoop is a normalized value and becomes close to 0.0 on the position where a ray reaches easily and becomes close to 1.0 when hard. So you can use it as a factor of a rechability or 1.0 - ray.loop / ray.maxLoop as an simple and a light-weight occlusion factor.

PostEffectOutput is defferent depending on the selected shader template. For example, it is an alias of SurfaceOutputStandard in Standard template. Please see the following pages for more details.

Please see each template file by clicking Edit button on the right side of the Shader Template drop-down list for more details.

Export

Press Export button or Ctrl + R to export shader. Then, press Create Material button to generate a material which uses the shader (or create a material manually from the Project pane).

Material

  • Loop
    • The maximum number of loops of raymarching in basic passes.
  • Minimum Distance
    • If the distance returned by a distance function becomes lower than this value, the loop finishes.
  • Distance Multiplier
    • This value is multiplied by the output of a distance function.
  • Shadow Loop
    • The maximum number of loops of raymarching in shadow pass.
  • Shadow Minimum Distance
    • Minimum Distance in shadow pass.
  • Shadow Extra Bias
    • Additional shadow bias to avoid shadow acne.

uraymarching's People

Contributors

hecomi 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uraymarching's Issues

Fix "cutout" effect on full screen

Setting to full screen makes it only render on the inner half of the screen, you can fix this by changing

#ifdef FULL_SCREEN
    o.pos = v.vertex;
#else

To

#ifdef FULL_SCREEN
    o.pos = UnityObjectToClipPos(v.vertex);
#else

In whatever shader your generated code imports, for example at the bottom mine had

...
    ZWrite [_ZWrite]

    CGPROGRAM
    #include "Assets\uRaymarching\Shaders\Include\Legacy/ForwardBaseStandard.cginc"
    #pragma target 3.0
    #pragma vertex Vert
    #pragma fragment Frag
    #pragma multi_compile_instancing
    #pragma multi_compile_fog
    #pragma multi_compile_fwdbase
    ENDCG
...

So I needed to modify that line in

#include "Assets\uRaymarching\Shaders\Include\Legacy/ForwardBaseStandard.cginc"

Unable to make Cubes subtraction

Unity 2018.3.2f1
Im unable to make subtraction of two cubes.
visual glitches appear:

image

distance function:
inline float DistanceFunction(float3 pos)
{
float x = Box(pos,float3(1,1,1));
pos-= float3(0.5,0.5,0.5);
float y = Box(pos,float3(1,1,1));
//float v = Sphere(pos, 1); (uncoment and change -x to -v below to see it working with sphere)
return max(y,-x);
}

Trying to test but not sure if I did something wrong.

I think I followed the how to use instructions correctly.
I have a generater, a shader and material.
Unity_bKBjFOJyCC
The only thing I added to the shader was the distance function that I copied and pasted thats supposed to be the morphing sphere cube on the main page.
Unity_x286MtCUls
When initially making(exporting) the shader and/or material I get these errors on console. I'm not sure if that's why my cube with the material applied doesn't do anything? Hoping to get some thoughts on this.

Unity_ysPDMrfuQQ
Unity_ZogkxhmHo6
Unity_MqI5DNQ1ZW

Unity 5.6.x support

Unity 5.6.x does not support UNITY_POSITION(), so replace it with simple float4 pos : SV_POSITION expression.

Unable to Export

Unity 2018.3.2f1
After creating new Shader generator, naming it and clicking Export. this exception occurs:

`Shader error in 'Raymarching/Tester': invalid subscript 'projPos' at Assets/uRaymarching/Shaders/Include/DeferredDirect.cginc(50) (on d3d11)

Compiling Vertex program with UNITY_PASS_DEFERRED
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_FULL_HDR`

Different rendering per object

Hi,

I am doing the union of two primitives in my distance function. But how can I have a different rendering between both? In my scene I'd like one to be textured and the others keep a unique color.

Thanks.

How to remove some objects raymarching.

I want to make it so that if any other object was placed inside the object with raymarching, then objects drawn by raymarching are not displayed.
image
and should be like this
image

Rendering breaks when using forward rather than deferred

I'm keen to use uRaymarching in VR but I've hit a couple of snags. I'll write up this one first as it's simple to describe.

I need to use the forward renderer to enable MSAA (which I guess won't benefit the raymarched objects but will benefit the rest of the scene).

However when I switch to forward - the placeholder geometry is rendered as well as the raymarched "geometry".

Rendering Mandelbulb black screen

Dear Hecomi,

I'm trying to render a MandelBulb, one described with a distance formula on http://blog.hvidtfeldts.net/index.php/2011/09/distance-estimated-3d-fractals-v-the-mandelbulb-different-de-approximations/. However, the screen is entirely black. Could you please give me some heads up on what I am doing wrong? I have also included the test project in a zip file. I have tried to stay as close to the working "Mod World" example from this repo for testing purposes.
Capture
Capture2
Capture3

mandelbulb-test-project.zip

Best regards,

daBlesr

Unity 5.5 compatibility ?

Hello,

First great coding and asset. Code is very clean and easy to read.

I am running your examples scenes from Windows and DX11. I did not try DX9. And the scene hex floor works good, while Mod world and Sphere box morphing don't.

I tried to use a simple: return Sphere(pos, 0.5); too but the cube still gets drawn.

So I guess there are some differences while running DirectX, do you plan to get it compatible at some point? Or you don't have a Windows computer and hope someone could participate?

Thanks.

Use for Volume Rendering of image slices

Hey hecomi. I'm really impressed by what you have built. I really love how much you can customise it. I was wandering if it is possible to use your library to do a volume render of a 3d Texture. Basically, I've got a set of images that have split a smoke image into image slices. I want to be able join all the 2d Textures as one volume (one 3d Texture) and then ray march through them with some noise level. Below is an image of what I would like.
smoke renderer icon test 4

I would be really good if there was a way to load the cube with a 3d Texture on the fly.
Is this possibly?
I appreciate any help on this. Thanks

Rendering issue in URP VR with Depth Texture enabled

Hi, I found a rendering issue when I enabled Depth Texture on the Camera or on the URP Settings Asset. I think the issue is only in VR. I'm using OpenVR and Single Pass, and I tried both Unity 2019.4.3 with URP 7.3.1 and Unity 2019.4.12 with URP 7.5.1.

I would greatly appreciate if you can take a look and suggest or push a fix! Great project! : )

uRaymarching Depth Texture Bug

Is this technique compatible with mobile platforms?

I developed a sample project with uRaymarching. There is no problem with PC. But, when I built project for mobile platform, i receive 5-10 fps. I also receive color problem. Character that i applied the shader turns black on mobile platform.

That's my project link : https://github.com/tunchasan/Blob-Runner3D-Clone

This is the shader : https://github.com/tunchasan/Blob-Runner3D-Clone/blob/main/Assets/_Main/Shader/TransformProvider.shader

I'm looking for some help :)

Metal Support

Really neat project. It doesn't work on Unity 2017.2/OSX when switching over to Metal API (which I want for a particular project that uses Compute Shaders on Metal as it's faster than OpenGL on my project), just switches over to a blank texture. Wondering what it would take to get that working.

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.