{"id":831,"date":"2015-01-19T00:41:33","date_gmt":"2015-01-19T00:41:33","guid":{"rendered":"http:\/\/www.migenius.com\/?p=831"},"modified":"2020-11-02T21:31:30","modified_gmt":"2020-11-02T21:31:30","slug":"procedurally-retro-with-mdl","status":"publish","type":"post","link":"https:\/\/www.migenius.com\/articles\/procedurally-retro-with-mdl","title":{"rendered":"Procedurally Retro with MDL"},"content":{"rendered":"

NVIDIA Iray 2015<\/a>\u00a0will introduce some great new features, including the ability to write your own procedural functions for use in materials. This is fantastic for creating resolution independent effects which can cover large areas without noticeable tiling artifacts (unless you want them of course).\u00a0Iray is built into our RealityServer<\/a> product so I\u00a0love to test out its latest features. To put procedural functions through their paces I decided to try to emulate something procedural from my childhood, the now famous 10 PRINT<\/a> program. This little one liner, originally designed to demonstrate the capabilities of the Commodore 64<\/a> prints a maze by randomly alternating between two diagonal characters. Iray uses the NVIDIA Material Definition Language<\/a> (MDL) both to define materials as well as custom functions, if you haven’t tried it out this little tutorial is a great way to get started.<\/p>\n

\n

10 PRINT appears extremely simple on the surface but hides considerable complexity. In fact an entire book<\/a> has been written exploring this single line of code from every angle. I highly recommend picking up a print copy<\/a> and supporting the authors who have intricately documented this little piece of computing history. Here is the program<\/em> in its full glory:<\/p>\n

\r\n10 PRINT CHR$(205.5+RND(1)); : GOTO 10\r\n<\/pre>\n

When you run this program it will character by character fill your screen and very soon a maze like pattern will emerge. If you are not lucky enough to have a C64 laying around there are some great emulators<\/a>.\u00a0What a perfect candidate for testing procedural pattern generation in Iray!<\/p>\n<\/div><\/div>\n

\"\"<\/p>\n

10 PRINT Running in an Emulator<\/p>\n<\/div>\n

 <\/p>\n<\/div><\/div><\/div>\n

\n
\r\nmdl 1.1;\r\n\r\nusing df import *;\r\nusing state import *;\r\nusing base import *;\r\nusing tex import *;\r\nusing math import *;\r\n\r\nexport texture_return tenprint() {\r\n\tcolor result = color(1.);\r\n\treturn texture_return(\r\n\t\tresult,\r\n\t\tluminance(result)\r\n\t);\r\n}\r\n\r\nexport material tenprint_example (\r\n\r\n) = let {\r\n\r\n\tbsdf diffuse_bsdf =\r\n\t\tdiffuse_reflection_bsdf(\r\n\t\t\ttint: tenprint().tint\r\n    \t);\r\n\r\n} in material(\r\n\tsurface: material_surface(\r\n\t\tscattering: diffuse_bsdf\r\n\t)\r\n);\r\n<\/pre>\n<\/div><\/div>\n

Let’s start with a bit of MDL boiler plate. Since we are creating a procedural function rather than a material we really need to have a simple material to wrap it in so we can test the output as we develop. Currently there are no interactive tools for creating MDL so the easiest way to test is to edit and reload in the NVIDIA Iview2 tool. To the left you can see our initial material, right now it just provides a diffuse material with its colour set to pure white (incidentally, you should never use pure white since that would never occur in real life). If you don’t know MDL you can check out the documentation<\/a> for more details and an introduction.<\/p>\n

You can see we have already put in a stub function for our 10 PRINT procedural. For now it takes no parameters and just returns our white colour. As we proceed we will only show the code for this function, towards the end we will show how it integrates back into the material. We have imported the\u00a0df, state, base, tex and math modules with the\u00a0<\/i>using<\/em> syntax so we don’t need to prefix calls to functions in these modules. Not all of these modules are used yet but we will need them later.<\/p>\n<\/div><\/div>\n<\/div>\n

Generating Randomness<\/h2>\n

The first thing I needed to verify to implement 10 PRINT was that I would be able to randomise the choice\u00a0of diagonal character. This wasn’t immediately obvious since MDL does not have a simple function to generate random or quasi-random numbers. For my purposes\u00a0something that looks random is sufficient. I am not trying to emulate how 10 PRINT actually runs on the C64 but rather just the results it generates. MDL functions must be able to compute and return everything they need based only on the input parameters and the state provided by the renderer. They have to be side effect free which means sometimes having to find alternative solutions.<\/p>\n

\n
\r\nexport texture_return tenprint(\r\n\ttexture_coordinate_info uvw\r\n\t\t= texture_coordinate_info()\r\n) {\r\n\treturn(\r\n\t\tperlin_noise_texture(\r\n\t\t\tcolor1: color(1),\r\n\t\t\tcolor2: color(0),\r\n\t\t\tsize: 0.02,\r\n\t\t\tnoise_levels: 4,\r\n\t\t\tuvw: uvw\r\n\t\t)\r\n\t);\r\n}\r\n<\/pre>\n<\/div><\/div>\n

While MDL does not have a built in feature for random number generation, it does have functions for generating noise patterns, specifically Perlin Noise<\/a>. This would seem to be suitable for getting something random looking to drive our algorithm. So let’s modify our initial stub function to return some noise based on the perlin_noise_texture<\/em> function available in the base<\/em> module. On the left you can see our first attempt at this. We have added a parameter to our function to accept UV texture coordinates which will become important later on. Selecting a suitable value for the size<\/em> parameter is a matter of trial and error, after some tests I arrived at the number shown\u00a0here. I recommend setting noise_levels<\/em> to at least 4.<\/p>\n<\/div><\/div>\n<\/div>\n

\n
\"noise_base\"<\/p>\n

Output of Perlin Noise from the Function Above<\/p>\n<\/div>\n<\/div><\/div>\n

\"noise_binary\"<\/p>\n

Noise with Modified UV and Thresholding from the Function Below<\/p>\n<\/div>\n<\/div><\/div>\n<\/div>\n

\n
\r\nexport texture_return tenprint(\r\n\ttexture_coordinate_info uvw\r\n\t\t= texture_coordinate_info(),\r\n\tuniform float tiling = 100.0\r\n) {\r\n\r\n\ttexture_coordinate_info tiled_uvw\r\n\t\t= transform_coordinate(\r\n\t\t\ttransform:\r\n\t\t\t\trotation_translation_scale(\r\n\t\t\t\t\tscaling: float3(tiling)\r\n\t\t\t\t),\r\n\t\t\tcoordinate: uvw\r\n\t\t);\r\n\r\n\tfloat rnd = perlin_noise_texture(\r\n\t\tcolor1: color(1),\r\n\t\tcolor2: color(0),\r\n\t\tsize: 0.02,\r\n\t\tnoise_levels: 4,\r\n\t\tuvw: texture_coordinate_info(\r\n\t\t\tposition: floor(\r\n\t\t\t\ttiled_uvw.position\r\n\t\t\t) \/ tiling\r\n\t\t)\r\n\t).mono;\r\n\r\n\tif(rnd > 0.5)\r\n\t\treturn(\r\n\t\t\ttexture_return(\r\n\t\t\t\tcolor(1.), 1.\r\n\t\t\t)\r\n\t\t);\r\n\telse\r\n\t\treturn(\r\n\t\t\ttexture_return(\r\n\t\t\t\tcolor(0.), 0.\r\n\t\t\t)\r\n\t\t);\r\n}\r\n<\/pre>\n<\/div><\/div>\n

This gives us some nice fairly random looking noise, however we need to turn this into something that can give a random looking selection between two choices. We also want to keep the choice constant within a character block so we don’t randomly switch characters within a single character. So what we want to get to is basically a black and white noise with a blocky appearance. To achieve this I have added another parameter for tiling, this will control how many characters we want to show in the [0,1]<\/em> UV space. Once scaled, the UV coordinates\u00a0start giving values\u00a0outside the [0,1]<\/em> range, to get a blocky appearance we discard the fractional part of the tiled UV coordinates with the built in floor()<\/em> function then divide out the tiling.<\/p>\n

Now the noise will give a blocky appearance but it’s still a smooth gradient of brightness between the blocks, we need them to be on or off. We can do this easily by just thresholding the noise and outputting one colour if the threshold is met and another if it’s not. Since I\u00a0setup the\u00a0noise between black and white I\u00a0take a threshold of 0.5, this value can have a big effect on the look of the noise and is worth breaking out as a parameter you can tune. With both of these elements in place we now get a nice black and white pixelated result.<\/p>\n<\/div><\/div>\n<\/div>\n

Encoding the Characters<\/h2>\n

Many implementations of 10 PRINT in modern software improve on the original with anti-aliasing, vector graphics and other enhancements. In contrast I wanted to replicate the original appearance including the low resolution encoding of the characters. The C64 character map encodes each PETSCII<\/a> character in 8×8 pixels, in the default mode each pixel is basically either on or off. 10 PRINT works by randomly adding either 0 or 1 to the 205 character code. It’s a happy coincidence that these characters happen to be adjacent in the PETSCII table.<\/p>\n<\/div><\/div>

\"\"<\/p>\n

PETSCII Characters, Left: 205, Right: 206<\/p>\n<\/div>\n

 <\/p>\n<\/div><\/div><\/div>\n

I first considered using textures for the characters\u00a0however it can be tricky to stop Iray from filtering them which would destroy the effect I wanted to achieve. Since there was only 64 values for the character I decided instead to just encode it within a local array of booleans in the function. MDL does not support multi-dimensional arrays so I’ve encoded it in a linear array.<\/p>\n<\/div><\/div>

\r\nbool[64] slash = bool[64](\r\n\ttrue , true , false, false, false, false, false, false,\r\n\ttrue , true , true , false, false, false, false, false,\r\n\tfalse, true , true , true , false, false, false, false,\r\n\tfalse, false, true , true , true , false, false, false,\r\n\tfalse, false, false, true , true , true , false, false,\r\n\tfalse, false, false, false, true , true , true , false,\r\n\tfalse, false, false, false, false, true , true , true ,\r\n\tfalse, false, false, false, false, false, true , true\r\n);\r\n<\/pre>\n<\/div><\/div><\/div>\n

Using the Characters and Putting it Together<\/h2>\n

You might have noticed I didn’t show both characters. We can actually easily obtain the second character by horizontally flipping the first. This means our random choice will be whether or not to horizontally flip the character when we draw it. Before we get there, we first need to actually lookup the elements in the character and draw them based on where we are in the UV space. First let’s just work out how to draw a repeating diagonal character, the one encoded into the slash<\/em> array. Here is how the index is computed.<\/p>\n

\r\nint row_length = 8;\r\nint u = frac(tiled_uvw.position[0]) * row_length;\r\nint v = frac(tiled_uvw.position[1]) * row_length;\r\nint idx = u + (v * row_length);\r\n<\/pre>\n

The row_length<\/em> refers to the width of our character, which I have\u00a0set to 8 since the\u00a0C64 character is originally 8 pixels wide. Then I calculate an adjusted UV index by taking just the fractional part of the tiled UV coordinates (where as for the random noise we took the whole number part). This causes the character to repeat, while the noise does not repeat but stays constant within a character. Finally I compute the linear position in the array from the U and V index. This all tells us which pixel of the character to output. Of course, in its current state this will always output the same character, which wouldn’t be much value. So we’ll now add the magic line which makes it behave like 10 PRINT.<\/p>\n

\r\nint row_length = 8;\r\nint u = frac(tiled_uvw.position[0]) * row_length;\r\nif(rnd > 0.5) u = row_length - u - 1;\r\nint v = frac(tiled_uvw.position[1]) * row_length;\r\nint idx = u + (v * row_length);\r\n<\/pre>\n

Now we can output\u00a0characters since we know whether to draw an area as on or off so we can return a result based on this. Here I just return the C64 default foreground or background colour depending on whether we should draw a solid pixel in the character or not. At this point, with all of the elements together we can start to generate\u00a0some output that really does resemble the original 10 PRINT program. Just a note, when looking at these top-down images, the shading you see is due to the light source above the plane, not our procedural function.\n

\r\nif(slash[idx])\r\n\treturn(\r\n\t\ttexture_return(\r\n\t\t\tcolor(0.0, 0.246200, 1.0), 1.\r\n\t\t)\r\n\t);\r\nelse\r\n\treturn(\r\n\t\ttexture_return(\r\n\t\t\tcolor(0.0 ,0.0 ,0.401978), 0.\r\n\t\t)\r\n\t);\r\n<\/pre>\n<\/div><\/div>
\"10print_plane\"<\/p>\n

10 PRINT Rendered with Iray 2015<\/p>\n<\/div>\n<\/div><\/div><\/div>\n

Taking It Further<\/h2>\n
\"\"

Example render with Iray 2015 and the material on the ground plane<\/p><\/div>\n

There is a lot you could do to improve on this little example. I haven’t exposed any significant parameters to allow you to tune the settings (such as the foreground and background colour) and the parameters which drive the noise could also be important to expose. You can see however that even in its simple form we get a great result, when you zoom in you can see the hard edges for the character pixels exactly as intended and we get a result that looks quite random despite using the deterministic Perlin noise.<\/p>\n

Alternatives to using the internal Perlin noise function of Iray would be to port a\u00a0Linear congruential generator<\/a> to MDL or perhaps even better to port\u00a0Stefan Gustavson\u2019s GLSL noise<\/a> implementations which are\u00a0actually very easy to translate to MDL (basically replace vecN<\/em> with floatN<\/em>, swap mix<\/em> for lerp<\/em> and fract<\/em> for frac<\/em>). There is a lot of good material out there and the requirements for doing noise in MDL are very similar to using languages like GLSL.<\/p>\n

Of course, my implementation here isn’t very flexible, we can’t experiment with different characters or reproduce the many variants of 10 PRINT shown in the book. You could take it much further but that is definitely left as an exercise for the reader, unfortunately I can’t see many customers generating demand for C64 procedurals but this new programmability in Iray opens a lot of new doors for our users. We’d love to hear more about how you might use this functionality\u00a0so please contact us<\/a>\u00a0if you want to know more.<\/p>\n

\"\" Download the Complete MDL File.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"

NVIDIA Iray 2015\u00a0will introduce some great new features, including the ability to write your own procedural functions for use in materials. This is fantastic for creating resolution independent effects which can cover large areas without noticeable tiling artifacts (unless you want them of course).\u00a0Iray is built into our RealityServer product so I\u00a0love to test out […]<\/p>\n","protected":false},"author":2,"featured_media":832,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[15],"tags":[16,17,14,27],"jetpack_featured_media_url":"https:\/\/www.migenius.com\/migenius\/wp-content\/uploads\/2015\/01\/10print-banner.png","_links":{"self":[{"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/posts\/831"}],"collection":[{"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/comments?post=831"}],"version-history":[{"count":44,"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/posts\/831\/revisions"}],"predecessor-version":[{"id":1079,"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/posts\/831\/revisions\/1079"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/media\/832"}],"wp:attachment":[{"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/media?parent=831"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/categories?post=831"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.migenius.com\/wp-json\/wp\/v2\/tags?post=831"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}