Generate Height Map from Object

This is a basic OSL shader which generates a height map from an object. Its intention is to be used to create bump/displacement maps or brush textures from objects.

There is no way to acces object’s bounding box directly from OSL. So, you have to use FromZ and ToZ to tell the shader which range should be mapped to a height map.
(Height map <- a color range from 0 to 1).

Happy blending.

shader zMapping(
    point Point = P,
    float FromZ = 0,
    float ToZ = 1,
    output closure color E = 0*emission()
    )
{
    if (raytype("camera")) {
        float l = ToZ - FromZ;
        E = ( P[2] - FromZ ) / l  * emission();
    } 
}


heightMap.blend (245.4 KB)

Unfortunatelly no… but you can still feed the ‘generated’ coordinates to the script, which are from 0 to 1 in each side of the bounding box. Getting values at real scales requires some other efforts (for example, if the object is almost flat, you’ll still get values near 1).

About your script, you are using P[2], which is the world coordinates… I think you wanted to use Point[2]?!

Also, you don’t need to use OSL for such a simple task. In this case, separating XYZ from the ‘generated’ (or any other coordinate system) and plugging the Z to the emission, can give you a similar result.

Hi Secrop,
your answer gave me an idea.

We could not use bounding box, but we could use drivers for ToZ/FromZ.

In example file there is
Empty …………(Driver → zMapping // FromZ)
and
Empty.001 ……(Driver → zMapping // ToZ)

Moving Empty or Empty.001 in z direction, we could edit shader range interactively.

heightMap.blend (248.3 KB)

here’s the same thing with nodes:

It could be also possible to automatically assign the drivers to the node, or even having two object dropdowns in the node interface, but that must be done in Python, not in OSL.

Updated script. Using in Appleseed.
(Cycles does not support metadata for node widgets.)

The shader could generate height maps or normal maps.

shader geomMapping
[[
    string as_node_name = "geomMapping",
    string as_category = "util"
]]
(
    string Mode = "Z mapping"
    [[ string label = "Chose Mode",
       string widget = "popup",
       string options = "Z mapping|Normals" ]],
    float FromZ = 0
    [[ string label = "From Z" ]],
    float ToZ = 1
    [[ string label = "To Z" ]],
    output closure color E = diffuse()
    )
{
    if (Mode == "Z mapping") {
            float l = ToZ - FromZ;
            E = ( P[2] - FromZ ) / l  * emission();
    } 
    if (Mode == "Normals") {
        float dx = 0.5*(1+N[0]);
        float dy = 0.5*(1+N[1]);
        float dz = N[2];
        E = color(dx, dy, dz) * emission();
    }
}

1 Like

Nice!! Didn’t know that Appleseed supported metadata! :slight_smile:

1 Like