<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leszek Godlewski on Medium]]></title>
        <description><![CDATA[Stories by Leszek Godlewski on Medium]]></description>
        <link>https://medium.com/@TheIneQuation?source=rss-ba304e204257------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HswJ4YBLCB1VTOAY.jpeg</url>
            <title>Stories by Leszek Godlewski on Medium</title>
            <link>https://medium.com/@TheIneQuation?source=rss-ba304e204257------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:01:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@TheIneQuation/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bringing shaders to contest programming]]></title>
            <link>https://medium.com/@TheIneQuation/bringing-shaders-to-contest-programming-2b5ac72dc75?source=rss-ba304e204257------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b5ac72dc75</guid>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[shadertoy]]></category>
            <category><![CDATA[programming-contest]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Leszek Godlewski]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 22:08:20 GMT</pubDate>
            <atom:updated>2023-08-05T12:24:42.390Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Graphics programming has not been a domain prominently featured in programming contests up until now, in no small part due to difficulty in grading code quality. We present a practical method for running a contest in shader programming with automatic judging, as well as report findings from the first edition of such a contest.</em></p><p>The above was meant to be the abstract of a more formal version of this article, but it didn’t happen for a confluence of reasons. After sitting on a draft for several years, I finally got the green light to publish it on my blog.</p><p>In the summer of 2019, during the run-up to the <a href="https://gic.gd/">Game Industry Conference</a> of that year, we ran an online <strong>shader programming contest, </strong>with <strong>automatic judging of both image quality and performance</strong>, and even some <a href="https://polskigamedev.pl/category/konkurs-shaderow/">nice prizes and news coverage</a> (linked website is in Polish).<strong> </strong>Participation was limited to Poland — it was meant to be a geographically-limited soft launch of sorts; the first edition of a recurring event. Which obviously hasn’t worked out just yet; we (all the people involved) still hope it will at some point, though.</p><p>In this article, I’d like to describe how the automatic judging system works, how the five contest problems were formulated, and then explain the choices I made for all the different trade-offs. It assumes a basic degree of understanding of the graphics rendering pipeline, as well as some elementary concepts from the area of optimising compilers. I’m also going to skip over OPTIL.io itself, since the platform has been covered in <a href="https://dl.acm.org/citation.cfm?id=2869098">its own</a> <a href="https://arxiv.org/abs/1807.06002">publications</a>; please refer to them for more details.</p><p>All of my contributions to this project were volunteering; I did the work in spare time simply because I found it exciting. Everything concerning graphics has been my doing, except one contest problem contributed by Kris Narkowicz. The OPTIL.io team provided great support getting my judging pipeline working on their platform.</p><h4>Table of contents</h4><p>· <a href="#68f0">The quick run-down</a><br> ∘ <a href="#2719">Judging pipeline</a><br>· <a href="#c4f9">Origins</a><br>· <a href="#f862">Constraints</a><br>· <a href="#f2fe">Trade-offs</a><br> ∘ <a href="#fc76">Why not GCN?</a><br> ∘ <a href="#bab9">SPIR-V it is</a><br>· <a href="#1a92">Enter “VGPU-1”</a><br> ∘ <a href="#1644">Instruction latency tables</a><br>· <a href="#83f5">SPIRV-Tools customisation</a><br> ∘ <a href="#6e8a">Fuse multiply-add pass</a><br> ∘ <a href="#ba4c">Pessimistic loop analysis</a><br> ∘ <a href="#0a83">Register pressure sensor pass</a><br> ∘ <a href="#d374">Disassembler</a><br>· <a href="#d897">Content comparison</a><br> ∘ <a href="#3cb3">Timings</a><br>· <a href="#4891">Designing the problems</a><br> ∘ <a href="#4ff7">Scoring</a><br> ∘ <a href="#82d8">GLSL tutorial</a><br> ∘ <a href="#6b13">Problem #1</a><br> ∘ <a href="#4223">Problem #2</a><br> ∘ <a href="#91f2">Problem #3</a><br> ∘ <a href="#8581">Problem #4</a><br> ∘ <a href="#7445">Problem #5</a><br>· <a href="#c815">Conclusions and future work</a><br>· <a href="#ef88">Appendix — OPTIL.io VGPU-1 Programming Manual</a></p><h3>The quick run-down</h3><p>The contest consisted of five problems, each of them exercising a different technique or concept from real-time rendering, in the form of a single-pass <a href="https://www.shadertoy.com/">Shadertoy</a>. Each involved looping time-based animation, and was designed to have at least two “levels of depth” in the playing field: basic (e.g. completing a 3D scene to match reference), and advanced (e.g. adding anti-aliasing), in order to make room for competition. The problem description would always contain:</p><ul><li>a numerical definition of key properties (e.g. material values, object dimensions),</li><li>a video clip (plus sometimes a static screenshot, if pixel scrutiny might be helpful to a particular problem),</li><li>a “starting point” shader that would take the participant the first few steps of the way,</li><li>detailed explanation of the scoring structure, and</li><li>an example output of the judging pipeline for this problem, in the form of a SPIR-V disassembly listing, with annotations describing the latency of each individual SPIR-V opcode, as well as key statistics: total ALU operations’ latency, loop penalty exponent (more on that later), register pressure and the resulting occupancy, and total execution cycle count.</li></ul><p>Scoring itself is a game of minimisation — the general formula was:<br><em>score = a · RMSE + b · execution cycles</em><br>where <em>a</em> and <em>b</em> were tweaked per problem to put more weight either on image quality or performance. Due to the orders of magnitude of the quantities themselves, typical values were <em>a</em>=100 and <em>b</em>=1.</p><p>Image correctness is controlled by a simple per-channel RMSE computation against a reference animation. There are countermeasures in place against solutions fine-tuned to specific render target resolutions (yes, people actually attempted that); details on that later.</p><p>Probably the most interesting part is judging the performance. I achieved it by coming up with a fictional GPU architecture, simple enough not to overwhelm programmers without graphics experience, but detailed enough in the key areas to develop good intuitions about the cost of things. SPIR-V blobs are statically analysed to come up with a number of GPU cycles necessary to execute it. Long story short, the static analyser makes the following assumptions:</p><ul><li>the GPU is strictly a vector processor — all SIMD lanes execute the same instruction, but are subject to a lane execution mask; this essentially allows “ignoring” branches in the analysis, as GPU time is always spent on both sides of a branch,</li><li>all loops are either unrolled, or penalised by raising the total ALU cost of the shader to the power of a <em>loop penalty exponent</em>; again, details on that later,</li><li>memory access latency is 120+ cycles, while the typical ALU operation takes 4 cycles,</li><li>in order to introduce occupancy as a factor, the register file is shared among all lanes and partitioned between them for the worst case of register pressure per lane, limiting how many lanes can execute in parallel (this is obviously different from real GPUs, but good enough to develop the intuition),</li><li>the contestant’s Shadertoy is the only program running on the GPU, we don’t need to concern ourselves with preemption, OS, or other applications taking up GPU time.</li></ul><p>Several weeks into the contest, a stand-alone binary of the static analyser (i.e. no rendering capability, just performance analysis) was provided to contestants as a download, for Windows, Linux, and MacOS. This allowed a shorter, local feedback loop when working on optimisations.</p><p>At the end of this article you’ll find an appendix with a “programming manual” for this fictional GPU that goes into more detail about all of those.</p><h4>Judging pipeline</h4><p>Once a participant submits their solution (a Shadertoy main image shader), a Docker image of an Ubuntu 16.04 install is spun up in a VM. The machine sport sno GPU whatsoever, and only a single CPU core is allocated to it. Once booted, a custom-built C++ application is launched.</p><p>The application reads a problem definition from JSON, which is essentially a Shadertoy JSON for the reference shader, augmented with contest-specific metadata. It then proceeds to attach a preamble and epilogue to the contestants’s Shadertoy to make it compilable, and compiles it twice: once for performance judgement, and once for the actual rendering. More on why the double compilation later, but the gist is that we compile it for different architectures: the fictional VGPU-1, and the x86–64 running a software renderer.</p><p>It then hands off the resulting GLSL source to <a href="https://github.com/KhronosGroup/glslang">glslang</a> to compile without optimisations. If that succeeds, the SPIR-V blob gets passed over to <a href="https://github.com/KhronosGroup/SPIRV-Tools/">SPIRV-Tools</a>’ optimiser, configured with special considerations (e.g. aggressive loop unrolling), as well as several custom optimisation passes (fuse multiply-add, and information-gathering passes). A custom disassembler then generates a listing of the SPIR-V opcodes, annotating them with contest-relevant information, such as opcode latency and register pressure/occupancy.</p><p>If successful up to this point, a headless OpenGL renderer, <a href="https://docs.mesa3d.org/osmesa.html">OSMesa</a> with <a href="https://docs.mesa3d.org/drivers/llvmpipe.html">LLVMpipe</a>, is spun up. An atlas, of typically 5x5=25 frames, of the contestant’s shader is rendered. The atlas is then compared for RMSE against the reference atlas (with a caching mechanism to avoid re-rendering the reference in vain).</p><p>Finally, the judging application combines the information from both parts into the final score, and the contest orchestration returns all this information to the contestant.</p><p>If I still have your attention, the remainder of the article flows more chronologically, and explains the individual design choices.</p><h3>Origins</h3><p>I had been volunteering on the program board of <a href="http://www.gic.gd/">GIC</a> for a few years when on April 4, 2019, I got a call from the conference’s chair and my friend, Jakub Marszałkowski. He was looking for novel ideas for a programming contest, targeting entry-level game programmers. The event would be run jointly by the <a href="http://igp.org.pl/">Indie Games Poland foundation</a> (which Jakub is also a co-founder of) and the <a href="https://cat.put.poznan.pl/en">Faculty of Computing at the Poznań University of Technology</a>, on the <a href="https://www.optil.io/">OPTIL.io</a> programming contest platform created by the latter.</p><p>Since I don’t know any better, I racked my brains for a graphics-related idea. And of course, <a href="http://www.shadertoy.com/">Shadertoy </a>came to mind. It seemed perfect: small, bite-sized algorithms, with real-time, rewarding feedback, and a wide range of possible challenges. The issue was that, while image comparison is a relatively simple problem, performance evaluation for shaders can be difficult. Save for strlen(shader) that some Shadertoy competitions actually use, which hardly translates to performance, there isn’t any good metric by which to grade. And I insisted we need to grade performance.</p><p>Or is there?</p><p>It occurred to me that high-level shading languages compile down to bytecode, a sequence of assembly-like, simple operations, which are easy to count individually. If we just assumed the worst case of control flow and “executed” both sides of each branch, and for the maximum possible number of loop iterations… A solution started to take shape in my head, and my mind started racing.</p><h3>Constraints</h3><p>Of course, the absolute simplest solution to grading the quality of a shader would be to run it on an actual GPU for, say, 100 frames, and take frame time measurements. Or better yet, take a capture with a dedicated GPU profiling tool such as <a href="https://gpuopen.com/gaming-product/radeon-gpu-profiler-rgp/">Radeon GPU Profiler</a>, and reap the benefits of detailed performance metrics, both for grading purposes, and to better inform and educate the user.</p><p>However, I was operating under two hard constraints:</p><ul><li>I had exactly 42 days until the competition would be announced, and the first problem made available, all while normally handling my day job. This would need to happen during my time off work.</li><li>The judging pipeline had to tie in with the existing OPTIL.io infrastructure: a cluster of virtual machines running Docker containers with Ubuntu 16.04. I would only have a single CPU core available to me, no GPU of any kind.</li></ul><p>The latter blew the real GPU idea out of the water. The former turned the whole affair into a game of trade-offs.</p><h3>Trade-offs</h3><p>The main issue was, of course, having no GPU. We needed to render at least a still frame from a shadertoy to confirm its correctness, before we even think about grading performance.</p><p>If this was Windows, we’d have <a href="https://docs.microsoft.com/en-us/windows/win32/direct3darticles/directx-warp">WARP</a> available to us, supporting Direct3D 10, 11, and 12. It wasn’t; but from earlier adventures, I already knew Mesa3D and its <a href="https://www.mesa3d.org/llvmpipe.html">LLVMpipe</a> software renderer, supporting OpenGL up to version 3.3, plus extensions, which is plenty enough to rasterise Shadertoys. As for Vulkan, at the time of development, no mature software implementation of it existed (this has changed since, e.g. <a href="https://www.khronos.org/assets/uploads/developers/library/2019-siggraph/Vulkan-11-SwiftShader-Update-SIGGRAPH_Jul19.pdf">SwiftShader became compliant</a>).</p><p>How do we measure performance, though? Measuring the x86 code generated by LLVM is a bad idea — CPUs have vastly different execution characteristics from GPUs. In the absence of actual GPUs, the alternative is either emulation, which looked way too complex for the time constraints, or static analysis: compiling the high-level shader code to some sort of assembly, making some assumptions about execution, data, and control flow, and adding up the “cycles” that our make-believe GPU would “spend executing” the assembly. The options for that were as follows:</p><ul><li><strong>DXBC</strong>, as produced by the <a href="https://docs.microsoft.com/en-us/windows/win32/api/d3dcompiler/nf-d3dcompiler-d3dcompile">D3DCompile API</a>; in a video game rendering engineer’s job, this used to be the compiled representation of your shaders you were most likely to see. However, being a product of HLSL, as well as its ties to Windows and the D3D ecosystem, on top of being deprecated, made it an unlikely candidate.</li><li><strong>DXIL</strong>, as produced by the new <a href="https://github.com/microsoft/DirectXShaderCompiler">Microsoft DirectX Shader Compiler</a>; the replacement for DXBC and, similarly, a product of HLSL (though solutions exist for producing it from GLSL), but at least somewhat untangled from Windows.</li><li><strong>SPIR-V</strong>; the Khronos graphics ecosystem’s equivalent (of sorts) of DXBC/DXIL. It comes with a cross-platform, MIT-licensed, open source <a href="https://github.com/KhronosGroup/glslang">compiler/optimiser/disassembler stack</a>. The faux “assembly” is quite high-level, with instructions encompassing complex operations like matrix multiplication, as its intended purpose is different from what we’d be using it for. But I could still work with that.</li><li><strong>AMD GCN ISA</strong>; this was a very tempting option, as it would make the contest most life-like. GCN-powered consoles are the platforms of most interest to actual graphics programmers.</li></ul><h4>Why not GCN?</h4><p>I suppose this warrants a small detour to explain. One has to be practical about picking battles.</p><p>At that point, I had but a casual familiarity with the ISA, and with the deadline looming on the horizon, I wasn’t willing to commit to the issues of constructing a <a href="https://en.wikipedia.org/wiki/Control-flow_graph">control flow graph</a> for it. I recalled <a href="http://www.joshbarczak.com/blog/?p=823">Josh Barczak’s Scrutinizer</a>, and the sheer number of assumptions and guesses that he had to make due to lack of detailed information was discouraging. I had no time to bring myself up to speed. There are also practical considerations: the parts of <a href="https://github.com/jbarczak/Pyramid">Pyramid</a> (the tool encompassing Scrutinizer) I’m interested in are written in <a href="https://en.wikipedia.org/wiki/C%2B%2B/CLI">C++/CLI</a>, which might be hard to get running under Linux, and the entire project is licensed under GPL, which would complicate the licensing situation of the code I was going to write.</p><p>Lastly, AMD provides a <a href="https://gpuopen.com/gaming-product/radeon-gpu-analyzer-rga/">Radeon GPU Analyzer</a>, which contains an offline GCN ISA compiler, and even what seems to be a shot at an emulator. However, <a href="https://github.com/GPUOpen-Tools/RGA/blob/f3f9539759c22e1a01bf184397ff089e95638d86/RadeonGPUAnalyzerBackend/Emulator/Parser/ISAProgramGraph.cpp#L516">even AMD themselves don’t trust it</a>, and the code has been rotting since at least February 3rd, 2017 (date of the original git commit; original spelling of the comment, emphasis mine):</p><blockquote>This code is intentionally commented out. We need to update this function to pass the device name when calculating the number of cycles that an instruction costs. This functionality of ISAProgramGraph is no longer being used anyway since <strong>the Analysis features which are provided by this class were found to be inaccurate in not useful.</strong> When we will get back to this implementation, this function’s body should be adjusted accordingly.</blockquote><h4>SPIR-V it is</h4><p>SPIR-V, on the other hand, has <strong>structured control flow</strong>, which means that any flow that isn’t strictly sequential is explicitly marked as such. Or, in other words, loops aren’t just a side effect of conditional jumps backwards. Control flow opcodes can only occur in certain parts of <a href="https://en.wikipedia.org/wiki/Basic_block">basic blocks</a>, they explicitly reference their jump targets, and thanks to some other rules’ side effects, non-looping branches are only allowed to jump forward. More details are available in the <a href="https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#_control_flow">SPIR-V specification, section 2.2.5</a>. Plus, the <a href="https://github.com/KhronosGroup/SPIRV-Tools">SPIRV-Tools</a> library takes the burden of <a href="https://en.wikipedia.org/wiki/Control-flow_graph">CFG</a> construction off of my shoulders entirely.</p><p>A feasible solution emerged:</p><ol><li>Render a GLSL shadertoy in software using Mesa3D (the <a href="https://www.mesa3d.org/osmesa.html">display-less OSMesa</a>, to be precise) using the LLVMpipe backend. Note that this isn’t using the SPIR-V that we compile to below: LLVMpipe doesn’t support the ARB_gl_spirv extension at the time of writing, and we’re running the shader on vastly different hardware than the one we’re judging performance on.</li><li>Perform image comparison as <a href="https://en.wikipedia.org/wiki/Root-mean-square_deviation">Root Mean Square Error</a> of quantised frame buffers. This method doesn’t correspond well with perceptual differences, but it’s good enough to stifle deviations in content.</li><li>Compile and optimise the same GLSL to SPIR-V via <a href="https://github.com/KhronosGroup/glslang">glslang</a> and <a href="https://github.com/KhronosGroup/SPIRV-Tools">SPIRV-Tools</a>.</li><li>Analyse the resultant SPIR-V statically: using a variant of SPMD execution model (more on that later), model <strong>pessimistic</strong> SPIR-V kernel execution in a pretty much linear fashion.</li><li>Count the “cycles” spent “executing” its SPIR-V opcodes.</li></ol><p>This has both bases covered: image output for testing correctness, and assembly-like output for measuring performance.</p><h3>Enter “VGPU-1”</h3><p>One thing I learned as a participant in programming contests before was that it was essential to codify things which are critical to scoring. This meant that my hand-wavy, “pessimistic SPMD” faux GPU needed describing in some detail. To that end, <a href="https://www.optil.io/optilion/shadertoy-tutorial">I wrote a document to serve as reference</a> for the contestants, as much as for myself. The original is in Polish; you can find an appendix with a direct English translation of the “VGPU-1 Programming Manual” at the end of this article. It goes to some length to justify treating a shader as a nearly completely sequential kernel, and hand-waving away a huge chunk of complexity of modern graphics pipelines. Keeping the idea of a teaching aid at the forefront, I reasoned that it’s acceptable to sacrifice some realism and gloss over complexity, if it helped develop the understanding and intuitions.</p><p>One such simplified detail that I insisted on introducing is the concept of occupancy. In real GPUs, occupancy is a measure of how many waves/warps are in flight; in VGPU-1, it applies at a lower level — since only one “wave” can ever be in flight, partitioning of the register file affects the live <em>lane</em> count (i.e. initial execution mask) instead. I would argue this will still develop the right kind of instincts in a novice graphics programmer, given how prevalent in the domain the theme of resource allocation for the worst case is.</p><p>Another obvious issue, especially for static analysis, is loops. I initially aggressively unroll them, but the resulting disassembly listings started getting out of hand for later problems. On top of that, the inlining pass sometimes left one-iteration “dummy loops” behind, an ugliness of resulting SPIR-V that proved difficult to eliminate. I ended up switching to just multiplying loop body latency by the iteration count, which is a number the optimiser is capable of determining. Instruction cache effects notwithstanding — they are not significant to the VGPU-1 model.</p><p>Where that isn’t possible (e.g. because the iteration count depends on external inputs), I apply an artificial penalty — every such loop increases the power to which the “cycle count” is raised. I dislike it due to its intangibility, but in practice, this is rarely an issue in Shadertoy-style shaders — there are hardly any external inputs, and capping the maximum iteration count in fundamentally unbounded loops (like ray marching, or binary searches) almost always enables determination of the iteration count. I believe it’s also good practice in production rendering code — you certainly want it to perform predictably.</p><p>Again, for details, I refer you to the <em>VGPU-1 Programming Manual</em> appendix at the end of this article.</p><h4>Instruction latency tables</h4><p>Each instruction still needed assigning a latency cost. I’ll spare you the entire latency table <a href="https://www.optil.io/optilion/shadertoy-tutorial">which you can view at OPTIL.io</a>, if you’re so inclined (search for the paragraph headed with “Tabele opóźnień instrukcji”). Instead, here’s how I built it:</p><ol><li>Inspired by AMD GCN’s 4-cycle dispatch, I took 4 cycles as the base latency value to initialise the tables with.</li><li>I then bumped all transcendental functions to 8 cycles.</li><li>Then modelled memory accesses as taking 120 cycles (remember, the VGPU-1 has no latency hiding hardware, so no cache either).</li><li>Then bumped some more instructions that I remembered at the time should be expensive: matrix operations, dot product, pow(), exp(), log(), modf(), and so on.</li></ol><p>This left some obvious inaccuracies with regard to representing real world hardware, but reveal day was coming up fast, so I called it a day and moved on to the next loose end.</p><p>In follow-up updates, the instruction tables have been updated to more closely resemble AMD Vega microarchitecture latencies. I have compiled them by going over the instruction list and compiling tiny GLSL snippets that executed the given operation to GCN ISA using the <a href="https://github.com/GPUOpen-Tools/RGA/">Radeon GPU Analyzer</a>. I then cross-referenced the generated instructions with the <a href="https://github.com/GPUOpen-Tools/RGA/blob/f3f9539759c22e1a01bf184397ff089e95638d86/RadeonGPUAnalyzerBackend/Emulator/Parser/Instruction.cpp">performance tables</a> to determine a realistic cycle count. Some operations, such as abs() and floating point negation, have been made to cost 1 cycle — on GCN, they’re typically merged into other opcodes as flags, but the VGPU-1 model is too simple to express that. This near-zero cost is the next best thing.</p><p>All these changes were meant to align optimisation instincts between GCN and the VGPU-1.</p><h3>SPIRV-Tools customisation</h3><p>One of the reasons I decided to go with SPIR-V in the end was the open-source compiler stack. This afforded me an existing disassembler implementation that I could leverage, as well as the optimiser scaffolding, which, for instance, allows querying for register pressure in a given <a href="https://en.wikipedia.org/wiki/Basic_block">basic block</a>.</p><p>I ended up using the following optimiser pass setup:</p><pre>// Start with the default SPIRV-Tools performance optimisation.  <br>if (!(Opt.RegisterPerformancePasses()<br> // Fuse multiplication and addition/subtraction sequences into single FMA ops.<br> .RegisterPass(CreateFuseMultiplyAddPass(true))<br> // This isn&#39;t an optimization pass. The Opt scaffolding affords us access to control flow analysis.<br> .RegisterPass(CreatePessimisticLoopAnalysisPass())<br> // This isn&#39;t an optimization pass. The Opt scaffolding affords us access to register pressure analysis.<br> .RegisterPass(CreateRegisterPressureSensorPass(RegisterPressure))<br> // Run the optimiser.<br> .Run(Words, Count, &amp;OptimizedSPIRV)))<br>{<br> fprintf(stderr, &quot;Internal error - Error optimizing SPIR-V\n&quot;);<br> exit(2);<br>}</pre><h4><em>Fuse multiply-add</em> pass</h4><p>This pass does exactly what it says: it leverages the intermediate representation context to identify floating point multiplication instructions, whose results are used only by addition/subtraction operations, and fuses them together. I’ve made the source code for this pass <a href="https://github.com/inequation/spirv-tools-custom-opt-passes">available on Github</a>.</p><h4>Pessimistic loop analysis</h4><p>This implements the pessimistic iteration count inference, as described earlier. It again taps into analyses already performed by SPIRV-Tools, extracting the maximum loop iteration counts from it (if available) and putting them into annotations of the loop instructions: the OpMerge instruction takes bit flags, so depending on whether iteration count is or is not available, it sets a MaxIterations = 0x20, or a DontUnroll = 0x2 flag. In the former case, an operand is also added to the opcode with the actual iteration count.</p><p>An occasional side effect of SPIRV-Tools function inlining passes is that former function bodies are wrapped in dummy, single-trip loops. These are also properly detected, and tagged with Unroll|MaxIterations = 0x21 flags, as well as an iteration count operand of 1.</p><p>All these flags and operands are later read by the disassembler and factored into the score result.</p><h4>Register pressure sensor pass</h4><p>This is a strictly read-only pass that takes a reference to an external integer, iterates over all basic blocks in the shader, and queries the intermediate representation context for the “register liveness” (i.e. the number of used registers) in that basic block. The external integer is populated with the maximum of all basic blocks’ livenesses, and is later used for determining shader occupancy.</p><h4>Disassembler</h4><p>Based loosely upon <em>glslangValidator</em>’s disassembler, it serves two functions: it generates the text output that is displayed to the user, and counts the cycles. In the most basic case, it processes the SPIR-V opcodes sequentially, looks them up in the latency tables, and accumulates the number of cycles.</p><p>Upon encountering a control flow opcode, it pushes its location onto a stack. This aids both text indentation, and loop counting: when exiting the control flow scope, the stack is popped, and the cycles from inside it are multiplied by the annotation generated by the pessimistic loop analysis pass, or the loop penalty exponent gets incremented.</p><p>Finally, the disassembler output is augmented with the number of cycles spent executing each opcode.</p><h3>Content comparison</h3><p>It’s pointless to grade performance without validating the correctness of of output. The problem appeared to me to be three-fold:</p><ol><li><strong>Pixel content</strong>: intuitively and obviously, we need to ensure the content of the pixels matches a reference image.</li><li><strong>Animation</strong>: a lot of Shadertoys’ attractiveness rides on motion. In order to ensure correctness of the shaders submitted by contestants, we need to capture that aspect, too.</li><li><strong>Obfuscation</strong>: depending on problem type, disclosing the source code of the reference shader may reduce the problem’s difficulty level; it is therefore undesirable.</li></ol><p>The first part I’ve decided to solve with a trivial Root Mean Square Error computation. While I’m painfully aware of its deficiencies as a non-perceptual metric, it was trivial to implement, and to explain to contestants. The contest’s FAQ describes the algorithm like so:</p><blockquote><strong>Q: What is the definition of the error function, RMSE?</strong></blockquote><blockquote>A: It is the simplest possible one:</blockquote><blockquote>The operation is performed on the final value, quantised to 8 bits per channel (0–255 range), as written to the frame buffer.</blockquote><blockquote>1. Sum S = 0.</blockquote><blockquote>2. For each channel (RGB) of each pixel of the tested image:</blockquote><blockquote>2.1. Compute the difference against the corresponding channel of the corresponding pixel of the reference image.</blockquote><blockquote>2.2. Square this difference and add it to the sum S.</blockquote><blockquote>3. Average the sum S: divide it by the number of all accumulated samples, i.e. S = S / (image width x height x 3) (RGB channels).</blockquote><blockquote>4. The image RMSE value is the square root of S.</blockquote><figure><img alt="An atlas of frames from problem #4, the Cornell box." src="https://cdn-images-1.medium.com/max/640/1*xrspNuRhaaeWMXyrQwr8Cg.png" /><figcaption>An atlas of frames for problem #4, the ray traced Cornell box. While not obvious to the naked eye, the frame dimensions vary between rows and columns: from 126 to 130 pixels.</figcaption></figure><p>As for the animation, while there is no discussion that multiple frames are required, rendering many with a software renderer would be impractically expensive. I also didn’t want to randomise the frames rendered — determinism and reproducibility of results have been among my requirements for fairness of judging. I settled on rendering a flipbook-type atlas of frames. The start frame, frame time delta, and the atlas dimensions are configurable per problem. Additionally, the dimensions of the atlas cells vary from frame to frame — this is a defence against contestants reverse-engineering and hardcoding frame dimensions (an actual problem we encountered).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*DQrayw2hC8mWOjBCZcHyOw.png" /><figcaption>Numerical scene description for problem #4, the ray traced Cornell box. From the top to the bottom: planes, boxes and a sphere. The columns contain geometry information, as well as Phong shading constants.</figcaption></figure><p>Finally, obfuscation — we only disclose the source code for 2 out of 5 problems, as their definition is simply the optimisation of preexisting code. For the others, we display a video clip to the contestants, as well as numerical data, where applicable. In the future, I would like to disclose the source code of the reference shader more often, but this particular contest happened under considerable time pressure, and some semblance of security against exploitation of loopholes in the problems was desired.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHt0lo-74KU0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHt0lo-74KU0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHt0lo-74KU0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/79aa52ec688e4f087b5975f00c5f8af0/href">https://medium.com/media/79aa52ec688e4f087b5975f00c5f8af0/href</a></iframe><h4>Timings</h4><p>Finally, the performance of the judging pipeline is of obvious interest. Thankfully, OPTIL.io collects some telemetry about the runs submitted by contestants. At the time of writing, after pruning the dataset of 3 entries with a time of 0 seconds, there are 115 graded entries across the 5 problem rankings. The basic statistical properties of the <strong>wall clock run time</strong> of the judging pipeline are as follows:</p><ul><li>minimum: 0.33s</li><li>maximum: 6.9s</li><li>average: 1.89s</li><li>standard deviation: 1.09s</li></ul><p>Not bad for a software renderer chucking out 25 frames of animation, and an optimising compiler doing some optimisations.</p><h3>Designing the problems</h3><p>The direction I was given by Jakub for problem design was to make them approachable for programmers competent with CPU programming, but without prior experience in graphics. I proceeded to draw a list problem spaces, which are relatable and realistic from a real-time rendering engineer’s point of view, that I could be testing, and came up with the following:</p><ol><li>breaking problems with global state down to independent ones</li><li>reduction of recursion to iteration</li><li>decoupling/separation by axes (e.g. separable filters, or parallel sorting)</li><li>partial derivatives ( dFdx()/dFdy())</li><li>register pressure optimisation</li><li>floating point numbers (rounding, binary representation, transcendental function quirks)</li><li>colour space operations (gamma correction, mixing, blending)</li><li>texture sampling (UV(W) space, bi-, trilinear, and anisotropic filtering)</li><li>signal sampling (aliasing and mitigation)</li><li>image processing (colour-spatial filtering)</li><li>geometric transformations (conversion between spaces)</li><li>shading models (Lambert, Blinn-Phong, GGX…)</li><li>analytical collision detection (ray-sphere, ray-plane, ray-polyhedron, ray-signed distance field…)</li><li>CSG operations</li></ol><p>Obviously, I didn’t get to test them all. Still, 9 of these points are represented in some way.</p><h4>Scoring</h4><p>This is, in essence, an optimisation contest: contestants aim to minimise both the error against the reference image, and the VGPU-1 cycle count. As such, the obvious solution was to define the final score in a problem as a weighted sum of RMSE and cycle count, with an RMSE threshold beyond which we qualify the answer as incorrect.</p><p>The weights, as well as the threshold, are configurable per problem.</p><p>The judging pipeline can produce a an absolute difference image (against the reference image) as a way of providing feedback to contestants as to where their submission diverges. Unfortunately, we didn’t manage to ship this feature in time for the first edition of the contest, but we hope to make it available eventually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qaz1mvCF5dChV5BzDLa1HA.png" /><figcaption>Example output of the absolute difference from reference feature. This is the image for “starting point” shader of problem #4 against its reference. Note how this clearly shows that the start shader is missing parts of the scene (remember, this is the absolute difference between colour channels), and that the box sides are slightly misaligned.</figcaption></figure><h4>GLSL tutorial</h4><p>One significant facet of the entire endeavour was that the contest was expected to have a “knowledge base”. I decided to tackle this by writing a crash course tutorial of GLSL, targeting a programmer familiar with a C-style language (e.g. C itself, C++, C#, or Java). I’ve tried to quickly explain the following concepts:</p><ul><li>Basic GLSL syntax: control flow statements, types, operators, vector swizzling, function library.</li><li>Writing code from the point of view of an individual pixel, with no communication between neighbours beyond partial derivatives.</li><li>The screen space.</li><li>Shader execution model.</li><li>A “first shader”.</li><li>Texture sampling: UV space, linear filtering, mip-mapping.</li><li>GLSL intrinsics for explicit filtering.</li><li>Basics of ray tracing, pinhole camera, and their relation to the frame buffer.</li><li>Shading models, focusing on lambertian, Phong and Oren-Nayar models.</li><li>Ray marching, interpreted as discrete sampling of an analog signal.</li></ul><h4>Problem #1</h4><p>I was asked to make the first problem “not too difficult” to avoid deterring potential participants. I settled on a trivial problem that would help a member of the “target audience” readjust to the shader mindset. I settled on converting this bouncy box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*sps7n6cAOhRA72i43DAoUw.gif" /></figure><p>To this bouncy ellipse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*NqVJoHPhTqB0b4wfKnys4Q.gif" /></figure><p>If you’ve ever written a shader, you’ll know that each of those are one-liners. Still, the objective of the problem is to familiarise oneself with Shadertoy, GLSL, and the contest in general.</p><p>In order to create some headroom for competition between the top contestants, the reference shader has a twist — it’s anti-aliased with 1024x supersampling. The triviality of the basic shape is reflected in the weights — this problem’s score is determined as RMSE·1000 + cycles·1.</p><p>This problem was a trial by fire — the relatively successful launch, thanks to the novelty and exposure at the Pixel Heaven festival, exposed many bugs and shortcomings of my design. I’ll spare you the details of the bugs, but contestant behaviour was what prompted the flipbook atlas dimension variation, as well as throttling of competition submissions on the web application side, due to a certain contestant attempting to brute-force submit many runs with different settings for his fake anti-aliasing technique.</p><h4>Problem #2</h4><p>I really wanted to start delving into more graphics-specific problems, while keeping them simple. The idea to make a classic demoscene tunnel popped into my mind:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6gIFjq3gQv4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6gIFjq3gQv4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6gIFjq3gQv4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/00aa92c1a568d440a1e045e2873779fc/href">https://medium.com/media/00aa92c1a568d440a1e045e2873779fc/href</a></iframe><p>The contestants were given a shader that already correctly computed the UV coordinates; all that was needed to get a passing grade was to sample the textures. Some room for competition was created by using the Bayer filter pattern as one of the textures, plus sampling it using the nearest neighbour filter; this texture sample could be trivially substituted by a significantly cheaper <em>select</em> operation. There was also a V coordinate discontinuity causing a horizontal seam artifact along it — fixing it was not necessary to pass, but obviously improved a contestant’s RMSE.</p><h4>Problem #3</h4><p>This one was contributed by my friend <a href="https://www.shadertoy.com/user/knarkowicz">Kris Narkowicz</a>. His idea was to make a classic “here’s some code, make it fast” problem. We disclose the entire shader to the contestants.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCTWwSV0gCEs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCTWwSV0gCEs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCTWwSV0gCEs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e146e4af9b63f299da45648d0f1d241d/href">https://medium.com/media/e146e4af9b63f299da45648d0f1d241d/href</a></iframe><p>It posed a significant problem to the original judging pipeline, which used to attempt to aggressively unroll loops, as opposed to the aforementioned pessimistic analysis. SPIRV-Tools is quite strict when it comes to conditions that loops need to meet in order to be unrollable, and Kris’s code generated SPIR-V that wasn’t meeting many of them, even after changing the loop counters from floats to integers. It’s what prompted the pessimistic analysis approach in the first place: the checks for known iteration count were passing, it was the ones further down the CanUnroll() function that failed. Skipping over that complexity also had quality of life benefits: the disassembly didn’t need to be as long and verbose anymore.</p><h4>Problem #4</h4><p>The Cornell box is my favourite test scene. It’s extremely simple, has real-life source material, and its physical properties have been measured, making it beautifully well-defined.</p><p>While going full-physically-based would be impractical for this contest, I still felt it would still serve as a nice data set for analytical ray tracing. I built the reference scene, then removed some elements from it, and replaced the cheap tests for the walls with more expensive box tests: I wanted the contestants to understand how the scene was built, how the collision detection worked, and notice that while some things are missing, others are superfluous.</p><p>The scene also features a point light, single ray traced shadows and a Phong-inspired shading model.</p><h4>Problem #5</h4><p>For the final problem, I considered three possibilities. First was an image filter; I toyed with the idea of non-separable motion blur, but without multipass rendering — which is only partially implemented in the system for now — the problem quickly reduced to just a few texture taps. The second one was another ray tracing scene, but with GGX specular shading and a wider variety of materials, in an attempt to drive up the register pressure and force the contestants to work on occupancy, but it felt too similar to problems #3 and #4. The third idea was ray marching; however, Jakub was opposed to introducing new, difficult concepts in the last problem.</p><p>In the end, I went with a spin on ray marching: namely, ray marching a displacement map for a light source floating at a low altitude above the surface.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fw9ZTncMU4jo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dw9ZTncMU4jo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fw9ZTncMU4jo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/466ecd83d6dc854defd64258a5a940e4/href">https://medium.com/media/466ecd83d6dc854defd64258a5a940e4/href</a></iframe><p>For this one, we also provide full reference source code. I wanted this problem to hark back to the property of computer graphics where human perception allows compromises in precision. Tweaking the ray march sample count was just the first optimisation space; the shader uses the Oren-Nayar diffuse shading model <a href="http://www1.cs.columbia.edu/CAVE/publications/pdfs/Oren_SIGGRAPH94.pdf">in the form described in the paper</a>, which requires expensive inverse trigonometric functions. The strict form of the sRGB transfer function is used as well. In both these cases, cheaper approximations may produce a result practically indistinguishable from the original.</p><h3>Conclusions and future work</h3><p>To us organisers, the contest has been a moderate success. It was also one of the most interesting ̶c̶h̶a̶l̶l̶e̶n̶g̶e̶s̶ nerd snipes ever aimed at me (thanks, Kuba!). I’m proud to have delivered something that actually works at a very tight schedule, and — I admit — I relish in the cleverness of a few of the ideas I implemented here. 🙂</p><p>It was also, to the best of our knowledge, the first contest of its kind. As such, it suffered from significant teething problems.</p><p>Despite the short term over which the software was developed and deployed, the judging pipeline has already accrued technical debt, resulting from cutting corners and haste. It’s currently built using makefiles; its versioning mechanism was designed to affix the goal posts for already released problems and is actually just gating design deficiencies; and some workarounds to SPIRV-Tools issues deserve to be reported and replaced with actual upstream fixes.</p><p>Since a software Vulkan renderer is now available, and it has the potential to bring multi-faceted improvements to the table, I want to move to it. We’d finally leave OpenGL behind, and considering that both glslang and DXC can compile HLSL to SPIR-V, we could enable contestants to use that language. We might even get some more esoteric languages that compile down to SPIR-V, such as RLSL.</p><p>Being able to take advantage of the SPIR-V stack delivered on the promise of hitting the ground running quickly; however, it prevented us from going as close to emulating real GPUs as we would have liked, and had some reliability issues. Some optimisation passes deliver disappointing results, others were extremely sensitive to input conditioning and would frequently fail for obscure reasons. In the future, we would like to depend on the AMD tech stack instead: perhaps we could work with AMD to make their emulator more “accurate and useful.” Their compiler is already battle-tested.</p><p>An extremely important facet of future shader contests would be multipass rendering. Shadertoy already supports this feature natively, and having it would afford us a wider variety of problem scenarios, such as deferred shading, or separable image filtering. I would like to explore exposing other stages of the graphics pipeline for similar reasons: ideally, I envision a contest in generic graphics programming, exercising everything from geometry processing, through compute, all the way to post effects.</p><p>The next logical step from that would be command buffer assembly (i.e. enqueueing draws, compute dispatches, data transfers, barriers, and state setting onto command queues). Render pass architecture is a critical element of graphics algorithms, and enabling free form design of it would provide the contest with an exciting amount of flexibility. For instance, contestants could use very different approaches to render a scene, such as forward vs deferred shading. While this kind of work is usually done on the CPU, not much stands in the way of doing on the GPU instead, using a shading language for the sake of consistency; especially if we are in control of the GPU and the API for enqueueing and executing commands.</p><p>AMD’s <a href="https://gpuopen.com/rps/">Render Pipeline Shaders</a> implement a lof of the ideas I had for how that would play out.</p><p>The first edition of the contest relied on Shadertoy itself for client-side code editing and rendering. The goals outlined above make it clear that Shadertoy’s feature set will not remain sufficient for that purpose for much longer. We need our own client-side application that can do all of these things, and more.</p><p>While RMSE is a simple difference metric and got the job done for the first edition, we would prefer one that was more strongly rooted in human perception. It would go much better with the spirit of the contest: approximations and trading precision for speed — as long as the results still look believable — are common themes of graphics programming.</p><p>Finally, I would like the judging pipeline to become open-source software. We failed to ship the difference image feature in time, and the decision to release binaries of the emulator/analyser came late into the contest’s time frame. Therefore, contestants could not take as much advantage of it as we’d like them to. This is something clearly fixable, with problem-specific information, such as reference images, being completely contained in data.</p><h3>Appendix — OPTIL.io VGPU-1 Programming Manual</h3><p>This is a direct translation from Polish. Note that this “programming manual” is a loosely versioned document — it contains changes made as the contest developed.</p><blockquote><strong>Processor characteristics</strong></blockquote><blockquote>OPTIL.io VGPU-1 is an experimental graphics processor of performance characteristics similar to modern, commercial GPUs, but greatly simplified. It has been designed solely with executing <a href="http://www.shadertoy.com/">Shadertoy</a>-style fragment shaders, written in the GLSL language, version 3.30.</blockquote><blockquote>Below is a detailed technical specification of the VGPU-1.</blockquote><blockquote><strong>Rendering pipeline and the instruction set</strong></blockquote><blockquote>The VGPU-1 implements a subset of <a href="https://www.khronos.org/opengl/wiki/Rendering_Pipeline_Overview">the OpenGL 3.3 pipeline</a>, namely, the programmable fragment (pixel) shading stage. The stages that precede Fragment Processing are simplified down to a full-screen quad without a depth buffer, while the stages that follow fragment processing (Sample Processing) are discarded — the output of the fragment shader is the final result written directly to the frame buffer.</blockquote><blockquote>The VGPU-1 driver consumes code written in <a href="https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.3.30.pdf">The OpenGL® Shading Language (GLSL) 3.30</a>, and compiles it down to the binary representation of <a href="https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html">SPIR-V 1.0</a>. SPIR-V, together with the <a href="https://www.khronos.org/registry/spir-v/specs/1.0/GLSL.std.450.html">SPIR-V Extended Instructions for GLSL</a>, serves as the instruction set and is directly executed by the VGPU-1. The driver of the VGPU-1 may provide the programmer with an assembly listing of the generated SPIR-V code.</blockquote><blockquote>Starting with problem no. 3, the VGPU-1 and its driver have been receiving updates, or revisions. In the description of each of the problems we indicate which revision of the VGPU-1 ecosystem is used to grade it. We also highlight the differences between the revisions in this document.</blockquote><blockquote><strong>Execution model</strong></blockquote><blockquote>The VGPU-1 is a vector processor, operating in the Single Instruction, Multiple Threads paradigm: every shader instruction executes simultaneously on multiple threads, and every variable is a vector (with several well-defined exceptions), whose elements correspond to the threads. The processor contains no execution pipelining, or latency hiding hardware, such as out-of-order execution.</blockquote><blockquote>The VGPU-1 is composed of 16 Arithmetic Logic Units, also called shader cores. Each core carries out computation for a single thread, but all threads share the program counter (instruction pointer), which is singular, scalar and uniform.</blockquote><blockquote>The VGPU-1 is ticked by a 1 GHz clock signal. Its driver runs a watchdog mechanism: it is assumed that the GPU has “hung” (i.e. entered a state which it cannot leave) if the time to execute a single command (rendering a shadertoy) exceeds 2 seconds. Upon hitting this timeout, the GPU is reset. This means that the maximum number of cycles to execute a shadertoy is 1 GHz * 2 seconds = 2,000,000,000 cycles.</blockquote><blockquote><strong>Branching (conditional jumps)</strong></blockquote><blockquote>From sharing the program counter it follows that the VGPU-1 does not support divergent branching (i.e. different threads jumping to different addresses), which translates to limited support for conditional jumps and loops.</blockquote><blockquote>This is done by evaluating tests to a Boolean vector register, executing both branches (i.e. both the <em>if</em> and the <em>else </em>branch). Their results are masked with the aforementioned Boolean vector, containing the test results. This provides that the observable side effects will match those of actually executing the diverging branches as expected, while paying the time cost of executing both, in a serial manner.</blockquote><blockquote>Loops</blockquote><blockquote><strong>Base revision (problems 1 and 2)<br></strong>In a similar manner — that is, by maintaining uniform loop counters shared across all threads — the VGPU-1 driver will attempt to unroll all loops whose iteration count can be determined at compilation time. Every loop which cannot be unrolled (e.g. its counter is dynamic) will increment the <strong>loop penalty exponent</strong> by 1. The total number of cycles <em>cₜ</em> spent by the VGPU-1 on executing a shader is raised to the power of the aforementioned exponent <em>Eₗₚ</em>, in accordance with the formula below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/66/1*5Y4UI2SUP8Gtjz4K0yp07w.gif" /></figure><blockquote>Where <em>c_b</em> is the “base” cycle count that the VGPU-1 would have spent executing the entire shader, if the given loop was to be executed only once. Please note that <strong>every single loop with a dynamic counter translates to one increment of the loop penalty exponent</strong>: multiple such loops will cause an explosion in shader execution time.</blockquote><blockquote><strong>Revisions 1 and 2 (problems no. 3 and subsequent)<br></strong>Starting with problem no. 3, the judgement is passed on revision 1 of the processor.</blockquote><blockquote>The difference against base revision is the replacement of aggressive loop unrolling with pessimistic iteration count estimation. In practice, this means that instead of copying the loop body <em>n</em> times, a loop’s execution cost is tracked as a stack of scopes (loop bodies), where the number of cycles spent in a particular scope (loop body) is multiplied by <em>n</em>.</blockquote><blockquote>In the case of unknown iteration count, the loop penalty mechanism stays in effect.</blockquote><blockquote><strong>Thread scheduling and register file</strong></blockquote><blockquote>The number of simultaneously dispatched threads in the VGPU-1 ranges from 4 to 16. For architectural reasons, it must always be a multiple of 4; it is also the minimum number of dispatched thread. Dividing this number of threads in flight by the total thread count yields the value of <strong>occupancy</strong>, which lies in the [0; 1] range and depends on <strong>register pressure</strong>. <strong>Occupancy is a key performance limiter</strong>: it is a direct multiplier of the processor’s bandwidth. For instance, a 50% occupancy will bring down the processor’s compute throughput also to 50%.</blockquote><blockquote>This is due to the fact that fast, static memory is expensive, both in production, and in chip surface area. Therefore, while shader cores own independent arithmetic logic units, they share the register file. It is a fast memory bank (1-cycle latency for reading and writing), organised in 4-component vectors, 32 bits each (128 bits per register), for a total of 256 registers. The register file is statically partitioned between shader cores by the driver at the thread scheduling stage.</blockquote><blockquote>Register pressure (i.e. the maximum number of registers in simultaneous use over the execution of an entire shader) determines the occupancy of the VGPU-1. If a shader requires 16 or fewer registers, the entire file can be partitioned optimally, and all 16 threads can be in flight.</blockquote><blockquote>The formula for calculating occupancy is as follows:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*H5Dq-ArLOJIvmdFvZsEixQ.gif" /></figure><blockquote>Where <em>Nₜ</em> is the total thread count of the VGPU-1 (16), <em>Nᵣ</em> is the total register count in the file (256), and <em>pᵣ</em> is the register pressure value. As register pressure grows, occupancy drops, and with it — performance, since a smaller number of threads can be dispatched to process data. Please note that once register pressure goes beyond 256/4=64 (i.e. the shader requires more registers than that), occupancy drops to 0, and the shader cannot be scheduled. The driver will raise an error in such case.</blockquote><blockquote><strong>Memory model</strong></blockquote><blockquote>The VGPU-1 inherits its memory model from GLSL. There is no stack or heap to allocate memory from, and all variables are placed in the register file. Including arrays, which implies that array dimensions must be known at shader compilation time (i.e. arrays cannot be sized dynamically).</blockquote><blockquote>As for accessing the main memory of the VGPU-1, since the processor is limited to fragment (pixel) processing, shaders can only access:</blockquote><blockquote>- uniform (constant) buffers,</blockquote><blockquote>- read-only textures, sampled using OpenGL-compliant filters:<br> — magnification: bilinear (<em>GL_LINEAR</em>),<br> - minification: trilinear (<em>GL_LINEAR_MIPMAP_LINEAR</em>),</blockquote><blockquote>- as well as read-and-write access to the pixel in the frame buffer that the thread is assigned to.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b5ac72dc75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic curation algorithms are broken]]></title>
            <link>https://medium.com/@TheIneQuation/automatic-curation-algorithms-are-broken-faa1e223612a?source=rss-ba304e204257------2</link>
            <guid isPermaLink="false">https://medium.com/p/faa1e223612a</guid>
            <category><![CDATA[curation]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Leszek Godlewski]]></dc:creator>
            <pubDate>Tue, 09 Apr 2019 17:21:44 GMT</pubDate>
            <atom:updated>2019-04-09T17:21:44.853Z</atom:updated>
            <content:encoded><![CDATA[<p>And are driving me away from social media services.</p><p>I just spent some 20 minutes scrolling through my Facebook feed, unliking fanpages and unfollowing “friends” posting content which I find completely uninteresting, but Facebook’s “curation algorithm” decides worth showing to me. I removed the app’s icon from my home screen, because I realised it’s simply wasting my time on things I don’t even want to see. Still can’t decide if the time weeding out my wall is time well spent.</p><p>Seldom do I make use of Spotify’s radio feature, or the generated “Discover Weekly” playlist, as it’s been consistently underwhelming, and sometimes even annoying. Inferior copycats of music I already know, as well as suggestions I have explicitly marked as “I don’t like it” making returns constitute the bulk of the algorithm’s suggestions.</p><p>This very website, Medium, has driven me away with its email notifications. Exploring different viewpoints, I read an article from an “alt-righter” here, a belligerent feminist there, an anti-NATO, possibly Russian troll on the side, and a Bellingcat contributor, too. The result? Flooding my inbox with increasingly extremist, poor quality propaganda writing of opposing ideologies, with half of the content paywalled. The aggressive advertising of Medium subscriptions was the icing on the cake.</p><p>There was a moment when my Youtube main page consisted of wonderful handicraft videos: wood- and metalworking, restoration of old tools, building machines, designing furniture, etc. Nowadays, it’s full of video game “let’s plays” and poor quality travel vlogs from the dead centre of the beaten path, which — needless to say — are not what I come there for.</p><p>Even Reddit gets it wrong, as much as I adore some of the subreddits out there. I’m not interested in “popularity” or “controversy”, I just want a chronologically ordered feed of all things in the spaces I care about. The “infinite scroll” on the “new Reddit” is an anti-feature in my eyes, it makes it very difficult to keep track of my reading. So yeah, my personal Reddit front page is <a href="https://old.reddit.com/new/">https://old.reddit.com/new/</a>, which is wonderfully schizophrenic in its own right.</p><p>Does anyone do it well?</p><p>I can’t really say with full conviction that they’re doing it “well”, but the least offensive curation so far for me has, surprisingly, come from… Twitter. However, I fear that might not be entirely to Twitter’s merit: quite probably, it’s an artifact of my Twitter network being laser-focused on game industry tech, and thus, its contents are singularly relevant to me (and by that I mean that I click on roughly 30–40% of links in the “most relevant to you” emails; following my actual feed is impossible, thanks to the gargantuan volume of traffic). Because on the flip side, Twitter also spams out the completely useless “see news from X” email with just the numbers of the likes and retweets made by people I follow. To add insult to injury, of course it isn’t possible to unsubscribe from the latter emails, while keeping the former.</p><p>All of this leaves me wondering whether I’m just an outlier, with a taste so nuanced and sophisticated (haha, yeah, right) that the algorithms can’t quite optimise for me? Or are they simply too superficial and based on a way too narrow understanding of the complex interactions happening here?</p><p>For now, I’ll stick with good, ol’ RSS feeds. They are reliable, they only come from sources I’ve hand-picked, and I never miss anything because some algorithm made a decision for me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faa1e223612a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Vanishing of Milliseconds]]></title>
            <link>https://medium.com/@TheIneQuation/the-vanishing-of-milliseconds-dfe7572d9856?source=rss-ba304e204257------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe7572d9856</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unreal-engine]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[virtual-reality]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Leszek Godlewski]]></dc:creator>
            <pubDate>Wed, 13 Jul 2016 21:06:01 GMT</pubDate>
            <atom:updated>2016-11-07T08:19:14.156Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimizing the UE4 renderer for Ethan Carter VR</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cO6vW4Kb1yV4ZJJeRoBl4g.jpeg" /><figcaption><a href="https://www.youtube.com/watch?v=gl5zfx2-E20">Screencap source.</a></figcaption></figure><p>As a game with very rich visuals, <strong><em>The Vanishing of Ethan Carter</em></strong> (available for the <a href="https://www2.oculus.com/experiences/rift/1048901365146027/">Oculus Rift</a> and <a href="http://store.steampowered.com/app/457880/">Steam VR</a>) has been a difficult case for hitting the VR performance targets. The fact that its graphics workload is somewhat uncommon for Unreal Engine 4 (and, specifically, largely dissimilar to existing UE4 VR demos) did not help. I have described the reasons for that at length in <a href="https://medium.com/@TheIneQuation/leszek-godlewski-s-blog-you-re-on-ue4-why-do-you-need-an-engine-programmer-1a21ccbc917d">a previous post</a>; the gist of it, however, is that <em>The Vanishing of Ethan Carter’s</em> game world is <strong>statically lit</strong> in some 95% of areas, with dynamic lights appearing only in small, contained, indoors.</p><p><strong>Important note:</strong> Our (<em>The Astronauts’</em>) work significantly pre-dates <a href="https://developer.oculus.com/blog/introducing-the-oculus-unreal-renderer/">Oculus VR’s UE4 renderer</a>. If we had it at our disposal back then, I would probably not have much to do for this port; but as it were, we were on our own. That said, I highly recommend the aforementioned article and code, especially if your game does not match our rendering scenario, and/or if the tricks we used simply do not work for you.</p><p>Although the studied case is a VR title, the optimizations presented are mostly concerned with general rendering and may be successfully applied to other titles; however, they are closely tied to the UE4 and may not translate well to other game engines.</p><p>There are Github links in the article. Getting a 404 error does not mean the link is dead — you need to have your <a href="https://www.unrealengine.com/ue4-on-github">Unreal Engine and Github accounts connected</a> to see UE4 commits.</p><h3>Show me the numbers</h3><p>To whet the reader’s appetite, let us compare the <a href="https://docs.unrealengine.com/latest/INT/Engine/Performance/GPU/">graphics profile</a> and <a href="https://docs.unrealengine.com/latest/INT/Engine/Performance/StatCommands/">timings</a> of a typical frame in the <a href="http://www.theastronauts.com/2015/09/the-vanishing-of-ethan-carter-redux-out-now/">PS4/Redux</a> version to a corresponding one from the state of the VR code on my last day of work at <em>The Astronauts</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MK2ZGj8-IdocRTlEht2Aug.png" /><figcaption>GPU profiles from the PS4/Redux and VR versions, side by side. Spacing has been added to have the corresponding data line up. Detailed textual log data available as Gists: <a href="https://gist.github.com/inequation/e86908e4c7cae293962479ac57355e14">PS4/Redux</a> and <a href="https://gist.github.com/inequation/5fe125ae635ba68b01c16e870f524466">VR version</a>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*3hiobOX8DLWpIaTcmi5yYg.png" /><figcaption>Timing graphs displayed with the <em>STAT UNITGRAPH</em> command, side by side.</figcaption></figure><p>Both profiles were captured using the UE4Editor -game -emulatestereo command line in a <em>Development</em> configuration, on a system with an NVIDIA GTX 770 GPU, at default game quality settings and 1920x1080 resolution (960x1080 per eye). Gameplay code was switched off using the PAUSE console command to avoid it affecting the readouts, since it is out of the scope of this article.</p><p>As you can (hopefully) tell, the difference is pretty dramatic. While a large part of it has been due to code improvements, I must also honour the art team at <em>The Astronauts </em>— <a href="http://www.theastronauts.com/2012/10/the-art-of-adam-bryla/">Adam Bryła</a>, <a href="http://www.theastronauts.com/2012/10/btw-who-are-we/">Michał Kosieradzki, Andrew Poznański</a>, and <a href="http://www.theastronauts.com/2012/12/the-imagination-of-kamil-wojciekiewicz/">Kamil Wojciekiewicz</a> have all made a <strong>brilliant</strong> job of optimizing the game assets!</p><p>This dead-simple optimization algorithm that I followed set a theme for the couple of months following the release of <em>Ethan Carter PS4</em>, and became the words to live by:</p><ol><li>Profile a scene from the game.</li><li>Identify expensive render passes.</li><li>If the feature is not essential for the game, switch it off.</li><li>Otherwise, if we can afford the loss in quality, turn its setting down.</li></ol><h3>Hitting the road to VR</h3><p>The beginnings of the VR port were humble. I decided to start the transition from the PS4/Redux version with making it easier to test our game in VR mode. As is probably the case with most developers, we did not initially have enough HMDs for everyone in the office, and plugging them in and out all the time was annoying. Thus, I concluded we needed a way to emulate one.</p><p>Turns out that UE4 already has a handy -emulatestereo command line switch. While it works perfectly in game mode, it did not enable that <em>Play in VR</em> button in the editor. I hacked up the FInternalPlayWorldCommandCallbacks::PlayInVR_*() methods to also test for the presence of FFakeStereoRenderingDevice in GEngine-&gt;StereoRenderingDevice, apart from just GEngine-&gt;HMDDevice. Now, while this does not accurately emulate the rendering workload of a VR HMD, we could at least get a rough, quick feel for stereo rendering performance from within the editor, without running around with a tangle of wires and connectors. And it turned out to be good enough for the most part.</p><p>While trying it out, Andrew, our lead artist, noticed that game tick time is heavily impacted by having miscellaneous editor windows open. This is most probably the overhead from the editor running a whole lot of <a href="https://docs.unrealengine.com/latest/INT/Programming/Slate/"><em>Slate</em> UI code</a>. Minimizing all the windows apart from the main frame, and setting the main level editor viewport to <a href="https://docs.unrealengine.com/latest/INT/Engine/UI/LevelEditor/Viewports/Basics/#immersivemode"><em>immersive mode</em></a> seemed to alleviate the problem, so I automated the process and added a flag for it to ULevelEditorPlaySettings. And so, the artists could now toggle it from the <a href="https://docs.unrealengine.com/latest/INT/Engine/UI/EditorSettings/"><em>Editor Preferences</em></a> window at their own leisure.</p><p>These changes, as well as several of the others described in this article, may be viewed in <a href="https://github.com/inequation/UnrealEngine/commit/c0037c4aa8c1dd8251194a201ded669fd843e4b7">my fork of Unreal Engine on Github</a> (<em>reminder: you need to have your </em><a href="https://www.unrealengine.com/ue4-on-github"><em>Unreal Engine and Github accounts connected</em></a><em> to see UE4 commits</em>).</p><h3>Killing superfluous renderer features</h3><p>Digging for information on UE4 in VR, I discovered that Nick Whiting and Nick Donaldson from Epic Games have delivered an interesting presentation at Oculus Connect, which you can see below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0oM6Xe7fT-8%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0oM6Xe7fT-8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0oM6Xe7fT-8%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8fad3e23d108ea7a592ee95e4e48ed7/href">https://medium.com/media/c8fad3e23d108ea7a592ee95e4e48ed7/href</a></iframe><p>Around the 37 minute mark is a slide which in my opinion should not have been a “bonus”, as it contains somewhat weighty information. It made me realize that, by default, Unreal’s renderer does a whole bunch of things which are absolutely unnecessary for our game. I had been intellectually aware of it beforehand, but the profoundness of it was lost on me until that point. Here is the slide in question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*zKeEuMs8qWAlHbXo.jpg" /></figure><p>I recommend going over every one of the above console variables in the engine source and seeing which of their values makes most sense in the context of your project. From my experience, their help descriptions are not always accurate or up to date, and they may have hidden side effects. There are also several others that I have found useful and will discuss later on.</p><p>It was the first pass of optimization, and resulted in the following settings — an excerpt from our DefaultEngine.ini:</p><pre>[SystemSettings]<br>r.TranslucentLightingVolume=0<br>r.FinishCurrentFrame=0<br>r.CustomDepth=0<br>r.HZBOcclusion=0<br>r.LightShaftDownSampleFactor=4<br>r.OcclusionQueryLocation=1</pre><pre>[/Script/Engine.RendererSettings]<br>r.DefaultFeature.AmbientOcclusion=False<br>r.DefaultFeature.AmbientOcclusionStaticFraction=False<br>r.EarlyZPass=1<br>r.EarlyZPassMovable=True<br>r.BasePassOutputsVelocity=False</pre><h4>The fastest code is that which does not run</h4><p>May I remind you that <em>Ethan Carter</em> is a statically lit game; this is why we could get rid of <a href="https://docs.unrealengine.com/latest/INT/Engine/Rendering/LightingAndShadows/LitTranslucency/">translucent lighting volumes</a> and <a href="https://docs.unrealengine.com/latest/INT/Engine/Rendering/LightingAndShadows/AmbientOcclusion/">ambient occlusion</a> (right with its <a href="https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/Engine/FPostProcessSettings/AmbientOcclusionStaticFraction/index.html">static fraction</a>), as these effects were not adding value to the game. We could also disable the <a href="https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/PostProcessMaterials/#customdepth">custom depth</a> pass for similar reasons.</p><h4>Trade-offs</h4><p>On most other occasions, though, the variable value was a result of much trial and error, weighing a feature’s visual impact against performance.</p><p>One such setting is <strong>r.FinishCurrentFrame</strong>, which, when enabled, effectively creates a CPU/GPU sync point right after dispatching a rendering frame, instead of allowing to queue multiple GPU frames. This contributes to improving <a href="http://www.chioka.in/what-is-motion-to-photon-latency/">motion-to-photon</a> latency at the cost of performance, and seems to have originally been recommended by Epic (see the slide above), but they have <a href="https://github.com/EpicGames/UnrealEngine/commit/289fec44ff9117cdbafcc7bcc012a3e59c8216f8">backed out of it since</a> (<em>reminder: you need to have your </em><a href="https://www.unrealengine.com/ue4-on-github"><em>Unreal Engine and Github accounts connected</em></a><em> to see UE4 commits</em>). We have disabled it for <em>Ethan Carter VR</em>.</p><p>The variable <strong>r.HZBOcclusion</strong> controls the occlusion culling algorithm. Not surprisingly, we have found the simpler, occlusion query-based solution to be more efficient, despite it always being one frame late and displaying mild popping artifacts. So do <a href="https://answers.unrealengine.com/questions/117320/drawbackseffects-of-disabling-hzbocclusion.html">others</a>.</p><p>Related to that is the <strong>r.OcclusionQueryLocation</strong> variable, which controls the point in the rendering pipeline at which occlusion queries are dispatched. It allows balancing between more accurate occlusion results (the depth buffer to test against is more complete after the base pass) against CPU stalling (the later the queries are dispatched, the higher the chance of having to wait for query results on the next frame). <em>Ethan Carter VR’s</em> rendering workload was initially CPU-bound (we were observing randomly occurring stalls several milliseconds long), so moving occlusion queries to before base pass was a <strong>net performance gain</strong> for us, despite slightly increasing the total draw call count (somewhere in the 10–40% region, for our workload).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*75g0ppPVGrU_zvkePPpSCg.png" /><figcaption>Left eye taking up more than twice the time? That is <strong>not </strong>normal.</figcaption></figure><p>Have you noticed, in our pre-VR profile data, that the early Z pass takes a disproportionately large amount of time for one eye, compared to the other? This is a tell-tale sign that your game is suffering from inter-frame dependency stalls, and moving occlusion queries around might help you.</p><p>For the above trick to work, you need <strong>r.EarlyZPass</strong> enabled. The variable has several different settings (<a href="https://github.com/EpicGames/UnrealEngine/blob/master/Engine/Source/Runtime/Renderer/Private/DeferredShadingRenderer.cpp#L141">see the code</a> for details); while we shipped the PS4 port with a full Z prepass (r.EarlyZPass = 2) in order to have D-buffer decals working, the VR edition makes use of just opaque (and non-masked) occluders (r.EarlyZPass = 1), in order to conserve computing power. The rationale was that while we end up issuing more draw calls in the base pass, and pay a bit more penalty for overshading due to the simpler Z buffer, the thinner prepass would make it a net win.</p><p>We have also settled on bumping <strong>r.LightShaftDownSampleFactor</strong> even further up, from the default of 2 to 4. This means that our light shaft masks’ resolution is just a quarter of the main render target. Light shafts are very blurry this way, but it did not really hurt the look of the game.</p><p>Finally, I settled on disabling the “new” (at the time) UE 4.8 feature of <strong>r.BasePassOutputsVelocity</strong>. Comparing its performance against <a href="https://twitter.com/rcalocao">Rolando Caloca’s</a> hack of injecting meshes that utilize <a href="https://docs.unrealengine.com/latest/INT/Resources/ContentExamples/MaterialNodes/1_10/">world position offset</a> into the velocity pass with previous frame’s timings (which I had previously integrated for the PS4 port to have proper motion blur and anti-aliasing of foliage), I found it simply outperformed the new solution in our workload.</p><h3>Experiments with shared visibility</h3><p>If you are not interested in failures, feel free to skip to the next section (<em>Stereo instancing…</em>).</p><p>Several paragraphs earlier I mentioned stalls in the early Z prepass. You may have also noticed in the profile above that our draw time (i.e. time spent in the render thread) was several milliseconds long. It was a case of a <a href="https://en.wikipedia.org/wiki/Heisenbug">Heisenbug</a>: it never showed up in any external profilers, and I think it has to do with all of them focusing on isolated frames, and not sequences thereof, where inter-frame dependencies rear their heads.</p><p>Anyway, while I am still not convinced that the suspicious prepass GPU timings and CPU draw timings were connected, I took to the conventional wisdom that games are usually CPU-bound when it comes to rendering. Which is why I took a look at the <a href="https://docs.unrealengine.com/latest/INT/Engine/Performance/StatCommands/">statistics that UE4 collects and displays</a>, searching for something that could help me deconstruct the draw time. This is the output of STAT INITVIEWS, which shows details of visibility culling performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*kjC3hI1LDBlxFiu1Bh580A.png" /><figcaption>Output of <em>STAT INITVIEWS</em> in the PS4/Redux version.</figcaption></figure><p>Whoa, almost 5 ms spent on frustum and occlusion culling! That call count of 2 was quite suggestive: perhaps I could halve this time by sharing the visible object set data between eyes?</p><p>To this end, I had made several experiments. There was some plumbing required to get the engine not to run the view relevance code for the secondary eye and use the primary eye’s data instead. I had added drawing a debug frustum to the FREEZERENDERING command to aid in debugging culling using a joint frustum for both eyes. I had <a href="https://github.com/inequation/UnrealEngine/commit/38127610bd153c949213e95564a97b5808e52d5d">improved the </a><a href="https://github.com/inequation/UnrealEngine/commit/38127610bd153c949213e95564a97b5808e52d5d">DrawDebugFrustum() code</a> to better handle the <a href="https://developer.nvidia.com/content/depth-precision-visualized">inverse-Z projection</a> matrices that UE4 uses, and also to allow a plane set to be the data source. Getting one frustum culling pass to work for both eyes was fairly easy.</p><p>But occlusion culling was not.</p><p>For performance reasons mentioned previously, we were stuck with the occlusion query-based mechanism (UE4 runs a variant of the <a href="http://http.developer.nvidia.com/GPUGems/gpugems_ch29.html">original technique</a>). It requires an existing, pre-populated depth buffer to test against. If the buffer does not match the frustum, objects will be incorrectly culled, especially at the edges of the viewport.</p><p>There seemed to be no way to generate a depth buffer that could approximate the depth buffer for a “joint eye”, short of running an additional depth rendering pass, which was definitely not an option. So I scrapped the idea.</p><p>Many months and a bit more experience later, I know now that I could have tried reconstructing the “joint eye” depth buffer via reprojection, possibly weighing in the contributions of eyes according to direction of head movement, or laterality; but it’s all over but the shouting now.</p><p>And at some point, some other optimization — and I must admit I never really cared to find out which one, I just welcomed it — made the problem go away as a side effect, and so it became a moot point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*Apnd3wP7_cjZouQdOIfcOA.png" /><figcaption>Output of <em>STAT INITVIEWS</em> in the VR version.</figcaption></figure><h3>Stereo instancing: not a silver bullet</h3><p><em>Epic </em>have developed the feature of <a href="https://www.unrealengine.com/blog/unreal-engine-4-11-released">instanced stereo rendering</a> for UE 4.11. We had pre-release access to this code courtesy of <em>Epic</em> and we had been looking forward to testing it out very eagerly.</p><p>It turned out to be a disappointment, though.</p><p>First off, the feature was tailored quite specifically to the <em>Bullet Train </em>UE4 VR demo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDmaxmnPzMWE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDmaxmnPzMWE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDmaxmnPzMWE%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb10a21162eb2adc5ca76a378748c6c0/href">https://medium.com/media/bb10a21162eb2adc5ca76a378748c6c0/href</a></iframe><p>Note that this demo uses dynamic lighting and has zero instanced foliage in it. Our game was quite the opposite. And the instanced foliage would not draw in the right eye. It was not a serious bug; evidently, <em>Epic</em> focused just on the features they needed for the demo, which is perfectly understandable, and the fix was easy.</p><p>But the worst part was that it actually <strong>degraded</strong> performance. I do not have that code laying around anymore to make any fresh benchmarks, but from my correspondence with Ryan Vance, the programmer at <em>Epic </em>who prepared a code patch for us (kudos to him for the initiative!):</p><blockquote>Comparing against a pre-change build reveals a considerable perf hit: on foliage-less scenes (where we’ve already been GPU-bound) we experience a ~0.7 ms gain on the draw thread, but a ~0.5 ms loss on the GPU.</blockquote><blockquote>Foliage makes everything much, much worse, however (even after fixing it). <em>Stat unit</em> shows a ~1 ms GPU loss with vr.InstancedStereo=0 against baseline, and ~5 ms with vr.InstancedStereo=1!</blockquote><p>Other UE4 VR developers I have spoken to about this seem to concur. There is also a <a href="https://forums.unrealengine.com/showthread.php?110953-Instanced-Stereo-Rendering-increases-GPU-time-up-to-257-why-such-a-huge-performance-decrease">thread at the Unreal forums</a> with likewise complaints. As Ryan points out, this is a CPU optimization, which means trading CPU time for GPU time. I scrapped the feature for <em>Ethan Carter VR</em> — we were already GPU-bound for most of the game by that point.</p><h3>The all-seeing eyes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpUTLq033_Df-Hx7Bpyxuw.png" /><figcaption>The problematic opening scene.</figcaption></figure><p>At a point about two-thirds into the development, we had started to benchmark the game regularly, and I was horrified to find that the very opening scene of the game, just after exiting the tunnel, was suffering from poor performance. You could just stand there, looking forward and doing nothing, and we would stay pretty far from VR performance targets. Look away, or take several steps forward, and we were back under budget.</p><p>A short investigation using the <a href="https://docs.unrealengine.com/latest/INT/Engine/Performance/StatCommands/">STAT SCENERENDERING</a> command showed us that primitive counts were quite high (in the 4,000–6,000 region). A quick look around using the <a href="https://github.com/EpicGames/UnrealEngine/blob/master/Engine/Source/Runtime/Engine/Private/UnrealEngine.cpp#L2708">FREEZERENDERING</a> command did not turn up any obvious hotspots, though, so I took to the <a href="https://docs.unrealengine.com/latest/INT/Programming/Rendering/Overview/">VIS<em> </em>command</a>. The contents of the Z-buffer after pre-pass (but <strong>before </strong>the base pass!) explained everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvaO-Ir0IFxKa0hoCQDPDA.png" /><figcaption>Note the missing ground in the foreground, in the bottom-left visualizer panel.</figcaption></figure><p>At the beginning of the game, the player emerges from a tunnel. This tunnel consists of the wall mesh and a landscape component (i.e. terrain tile) that has <a href="https://docs.unrealengine.com/latest/INT/Engine/Landscape/Materials/#landscapeholematerials">a hole in it</a>, which resulted in the entire component (tile) being excluded from the early Z-pass, allowing distant primitives (e.g. from the other side of the lake!) to be visible “through” large swaths of the ground. This was also true of components with traps in them, which are also visible in this scene.</p><p>I simply special-cased landscape components to be rendered as occluders <a href="https://github.com/inequation/UnrealEngine/commit/97cbc38b7718690460f6247a179623456a1f60c0">even when they use masked materials</a> (<em>reminder: you need to have your </em><a href="https://www.unrealengine.com/ue4-on-github"><em>Unreal Engine and Github accounts connected</em></a><em> to see UE4 commits</em>). This cut us from several hundred to a couple thousand draw calls in that scene, depending on the exact camera location.</p><h3>Fog so thick one might have spread it on bread</h3><p>Still not happy with the draw call count, I took to <a href="http://renderdoc.org/"><em>RenderDoc</em></a>. It has the awesome <a href="https://renderdoc.org/docs/window/texture_viewer.html?highlight=overlay#render-overlay">render overlay</a> feature that helps you quickly identify some frequent problems. In this case, I started clicking through occlusion query dispatch events in the frame tree with the <strong>depth test</strong> overlay enabled, and a pattern began to emerge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Q3VYN_DdGz91BVt1wWPfDg.png" /><figcaption><em>RenderDoc’s </em><a href="http://docs.renderdoc.org/window/texture_viewer.html?highlight=overlay#render-overlay">depth test overlay</a>. An occlusion query dispatched for an extremely distant, large (about 5,000 x 700 x 400 units) object, showing a positive result (1 pixel is visible).</figcaption></figure><p>Since UE4 dispatches bounding boxes of meshes for occlusion queries, making it somewhat coarse and conservative (i.e. subject to false positives), we were having large meshes pass frustum culling tests, and then occlusion, by having just 1 or 2 pixels of the bounding box visible through thick foliage. Skipping through to the actual meshes in the base pass would reveal all of their pixels failing the depth test anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*AKwxTaX7zPVIu3cMBQXlvw.png" /><figcaption><em>RenderDoc’s </em><a href="http://docs.renderdoc.org/window/texture_viewer.html?highlight=overlay#render-overlay">depth test overlay</a> in UE4’s base pass. A mesh of decent size (~30k vertices, 50 x 50 x 30 bounding box), distant enough to occupy just 3 pixels (L-shaped formation in the centre). Successful in coarse occlusion testing, but failing the per-pixel depth tests.</figcaption></figure><p>Of course, every now and then, a single pixel would show through the foliage. But even then, I could not help noticing that it would be almost completely washed out by the thick fog that encompasses the forest at the beginning of the game!</p><p>This gave me the idea: why not <strong>add another plane to the culling frustum</strong>, at the distance where fog opacity approaches 100%?</p><p>Solving the fog equation for the distance and <a href="https://github.com/inequation/UnrealEngine/commit/4841faec1ab6b9457118f246706012e0e7f3d16d">adding the far cull plane</a> shaved another several hundred draw calls. We had the draw call counts back under control and in line with the rest of the game.</p><h3>Insane LODs</h3><p>At some point late in development, AMD’s <a href="https://anteru.net/">Matthäus G. Chajdas</a> was having a look at a build of the game and remarked that we are using way too highly tessellated trees in the aforementioned opening scene. He was right: looking up the asset in the editor had revealed that <a href="https://docs.unrealengine.com/latest/INT/Engine/Content/Types/StaticMeshes/HowTo/LODs/">screen sizes of LODs 1+</a> were set to ridiculous amounts in the single-digit percentage region. In other words, the lower LODs would practically never kick in.</p><p>When asked why, the artists responded that when using the same mesh asset for hand-planted and instanced foliage, they had the LODs kick in at different distances, and so they used a “compromise” value to compensate.</p><p>Needless to say, I absolutely hate it when artists try to clumsily work around such evident bugs instead of reporting them. I whipped up a test scene, confirmed the bug and started investigating, and it became apparent that instanced foliage does not take <strong>instance scaling</strong> into account when computing the LOD factors (moreover, it is not even really technically feasible without a major redecoration, since the LOD factor is calculated per foliage type per entire cluster). As a result, all instanced foliage was culled as if it had a scale of 1.0, which usually was not the case for us.</p><p>Fortunately, the scale does not vary much within clusters. Taking advantage of this property, I put together <a href="https://github.com/inequation/UnrealEngine/commit/9c2b0400cbc123c4c4ecb0ff023fa5e04e37c45b">some code for averaging the scale</a> over entire instance clusters, and used that in LOD factor calculations. Far from ideal, but as long as scale variance within the cluster is low, it will work. Problem solved.</p><h3>The money shot</h3><p>But the most important optimization — the one which I believe put the entire endeavour in the realm of possibility — was the <strong>runtime toggling of G-buffers</strong>. I must again give <a href="https://anteru.net/">Matthäus G. Chajdas</a> credit for suggesting this one; seeing a GPU profile of the game prompted him to ask if we could maybe reduce our G-buffer pixel format to reduce bandwidth saturation. I slapped my forehead, hard. ‘Why, of course, we could actually get rid of <em>all</em> of them!’</p><p>At this point I must remind you again that <em>Ethan Carter</em> has almost all of its lighting baked and stowed away in lightmap textures. This is probably <strong>not true</strong> for <strong>most </strong>UE4 titles.</p><p><em>Unreal</em> already has a console variable for that called r.GBuffer, only it requires a restart of the engine and a recompilation of base pass shaders for changes to take effect. I have extended the variable to be an enumeration, assigning the value of 2 to automatic runtime control.</p><p>This entailed a bunch of small changes all around the engine:</p><ul><li>Moving light occlusion and gathering to before the base pass.</li><li>Having TBasePassPS conditionally define the NO_GBUFFER macro for shaders, instead of the global shader compilation environment.</li><li>Creating a new shader map key string.</li><li>Finally, adjusting the draw policies to pick the G-buffer/no G-buffer shader variant at runtime.</li></ul><p><a href="https://github.com/inequation/UnrealEngine/commit/ead931530360781bb7d4c768532af09dc60ebfe2">This change</a> saved us a whopping <strong>2–4 milliseconds per frame</strong>, depending on the scene!</p><p>It does not come free, though — short of some clever caching optimization, it doubles the count of base pass shader permutations, which means significantly longer shader compiling times (offline, thankfully) and some additional disk space consumption. Actual cost depends on your content, but it can easily climb to almost double of the original shader cache size, if your art team is <a href="https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/MaterialInstances/">overly generous with materials</a>.</p><h4>The fly in the ointment</h4><p>Except <strong>of course</strong> the G-buffers would keep turning back on all the time. And for reasons that were somewhat unclear to me at first.</p><p>A quick debugging session revealed that one could easily position themselves in such a way that a point light, hidden away in an indoor scene at the other end of the level, was finding its way into the view frustum. UE4’s pretty naive light culling (simple frustum test, plus a screen area fraction cap) was simply doing a bad job, and we had no way of even knowing which lights they were.</p><p>I quickly <a href="https://github.com/inequation/UnrealEngine/commit/c986362a92c56b498982b200b0f36a09723202a4">whipped up a dirty visualisation</a> in the form of a new <a href="https://docs.unrealengine.com/latest/INT/Engine/Performance/StatCommands/"><em>STAT</em> command</a> — STAT RELEVANTLIGHTS — that lists all the dynamic lights visible in the last frame, and having instructed the artists on its usage, I could leave it up to them to add manual culling (visibility toggling) via trigger volumes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94CJ5nthr6uA3hPlM4tDqg.png" /><figcaption><em>STAT RELEVANTLIGHTS</em> output. Left: scene with fully static lighting. Right: fully dynamic lighting; one point light has shadow casting disabled.</figcaption></figure><p>Now all that was left to optimize was game tick time, but I was confident that <a href="http://www.theastronauts.com/2012/11/the-code-of-adam-bienias/">Adam Bienias</a>, the lead programmer, would make it. I was free to clean my desk and leave for my new job!</p><h3>Conclusions</h3><p>In hindsight, all of these optimizations appear fairly obvious. I guess I was simply not experienced enough and not comfortable enough with the engine. This project had been a massive crash course in rendering performance on a tight schedule for me, and there are many corners I regret cutting and not fully understanding the issue at hand. The end result appears to be quite decent, however, and I allow myself to be pleased with that. ;)</p><p>It seems to me that renderer optimization for VR is quite akin to regular optimization: profile, make changes, rinse, repeat. Original VR content may be more free in their choice of rendering techniques, but we were constrained by the already developed look and style of the game, so the only safe option was to fine-tune what was already there.</p><p>I made some failed attempts at sharing object visibility information between eyes, but I am perfectly certain that it is possible. Again, I blame my ignorance and inexperience.</p><p>The problem of early-Z pass per-eye timings discrepancy/occlusion query stalling calls for better understanding. I wish I had more time to diagnose it, and the knowledge how to do it, since all the regular methods failed to pin-point it (or even detect it), and I had only started discovering <a href="https://randomascii.wordpress.com/category/xperf/">xperf/ETW</a> and <a href="https://graphics.stanford.edu/~mdfisher/GPUView.html">GPUView</a>.</p><p>Runtime toggling of G-buffers is an optimization that should have made it into the PS4 port already, but again — I had lacked the knowledge and experience to devise it. On the other hand, perhaps it is only for the better that we could not take this performance margin for granted.</p><p>Fun times!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe7572d9856" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“You’re on UE4, why do you need an engine programmer?”]]></title>
            <link>https://medium.com/@TheIneQuation/leszek-godlewski-s-blog-you-re-on-ue4-why-do-you-need-an-engine-programmer-1a21ccbc917d?source=rss-ba304e204257------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a21ccbc917d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unreal-engine]]></category>
            <dc:creator><![CDATA[Leszek Godlewski]]></dc:creator>
            <pubDate>Fri, 10 Jul 2015 00:00:00 GMT</pubDate>
            <atom:updated>2016-07-16T19:37:27.726Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Originally published on </em><a href="http://gamasutra.com/blogs/LeszekGodlewski/20150710/247996/quotYoure_on_UE4_why_do_you_need_an_engine_programmerquot.php"><em>Gamasutra</em></a><em> on July 10, 2015.</em></p><p>Over nine months ago, when I first reached out to <em>The Astronauts</em>, I, too, didn’t think that there’s much to do in graphics programming on a team that runs the Unreal Engine. But Adrian Chmielarz did, and last November, I ended up as the eighth member of the pack.</p><p>It probably won’t come as a surprise that I haven’t done any ground-breaking research; thus, I won’t go into much detail describing the changes I have made to help ship <em>The Vanishing of Ethan Carter</em> for the Playstation 4, as they have mostly been of the workmanlike variety: application of generally available tech, bug fixing and reporting, that kind of thing. In general, my job was <em>to support the artists</em>.</p><h3>The Remaking of Ethan Carter</h3><p>The situation we’ve found ourselves in was somewhat unusual: we had a (still) pretty fresh game that we were to remake in another game engine. And one that is different in pretty much every key aspect: rendering architecture, lighting model, gameplay scripting engine. Game design and assets were out of the way, but we still had a pretty firm visual benchmark to meet in the form of the UE3 version of the game, and much to learn to find our way around UE4, lest we deliver a “remake” that looks worse than the original…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lItbgcYFzan1mkNG.jpg" /></figure><p>From the graphics point of view, one of the things that gave TVoEC that eerie, dreamy look was the static global illumination, with soft shadows and a lot of light bounce. That means static, baked lightmaps. However, UE4 has a deferred renderer, optimized for dynamic lighting. Add to that UE4’s physically-based rendering pipeline, and you can probably start getting a sense of divergence of goals. This divergence proved extremely significant in the development of the PS4 edition of the game: we were using code paths and workflows that almost no one else used anymore. In other words, we were very likely to encounter issues that went unnoticed for a long time. And so we did.</p><h3>Adding features</h3><p>I love UE4. It’s much nicer to work with than UE3, it feels like much more forethought was put in it, I fully support the elimination of UnrealScript. But it is still a younger engine than UE3, obviously. Most features are already in place, but some are yet to come, others are implemented partially. Some were present in Unreal Engine 3, but haven’t made their comeback yet (and may not make it at all, as, again, UE4 goes in a different direction to UE3), and our artists wanted them back, and wanted them quickly.</p><p>One such thing were <a href="https://udn.epicgames.com/Three/LightingReference.html#LightingChannels">lighting channels</a>. Epic had the feature on <a href="https://trello.com/b/gHooNW9I/ue4-roadmap">their roadmap</a>, but since was not a definitive date, its introduction was my first assignment. And a highly instructive one it was, as I gained my first insight into many of UE4’s layers: I intruded everywhere, from shaders all the way down to base engine data structures.</p><p>Another example was the “screen door” effect for LOD transitions, a.k.a. dithered LOD transitions: an effect designed to hide popping using a symmetric per-pixel dissolution effect (the fading-out LOD discards the pixels that the fading-in LOD displays, and the other way around). At the time it was already implemented for instanced static meshes (i.e. foliage), but not for regular ones. And again, it was on the engine roadmap, but we wanted it now, so I set out to fill that gap. Eventually, though, Epic has provided their own solution, which I had integrated and replaced mine with.</p><p>One missing UE3 feature that I couldn’t really implement in a reasonable way was depth priority groups. It allows rendering primitives as if they had separate depth buffers, which is useful to ensure that foreground objects never intersect surrounding geometry. This approach cannot be easily used in deferred rendering, however, since it would make screen-space resolves difficult. Instead I put together a clip-space offset that flattened the foreground objects along clip-space Z axis and moved them to the near clipping plane, making them render in front of everything while not changing their apparent size or shape. Far from perfect (lighting behaves slightly differently), but got the job done.</p><h3>Things work differently now</h3><p>As I had mentioned before, there is quite a discrepancy between what our game needs, and what UE4 does best. PBR was — quite surprisingly to me, actually — the least of our worries. The deferred renderer, on the other hand, gave me some headaches.</p><p>In UE4, lightmaps are meant to contain indirect (bounced) lighting only; setting light source mobility to “static” causes lightmaps affected by it to also include direct lighting, but it is an exceptional situation, not the default. Such lights are not even considered for dynamic lighting. This means that they don’t have specular highlights. <em>None at all.</em> You can probably imagine how flat and uninteresting the game looked because of that.</p><p>I’ve “fixed” that by adding a forward, fake Phong specular highlight to emissive lighting. I still feel <em>super filthy</em> because of it. It violates the energy conservation principle and uses a non-PBR specular distribution, but the artists were happy with it.</p><p>Now, the only problem that remained was that this fake specular was not shadowed… This in turn was fixed by emitting additional per-texel factor in the lightmaps, describing how much light in a given lightmap texel was contributed by direct, and how much by indirect lighting. Texels with zero direct lighting were assumed to be in shadow. Crazy and dangerous, but for a mostly outdoor game with only the sun shining, it worked!</p><p>Yet another place where engine behaviour changed was in translucent mesh rendering. The game has a puzzle minigame of setting up the chronology of events with translucent ghosts. Those ghosts would not self-occlude, so front-facing, inner polygons were rendered, producing ugly artifacts.</p><p>The artists fixed this in UE3 by doing manual alpha-blending, as it would cause the engine to do some state changing and resolve scene colour to a readable texture, effectively capturing previously rendered meshes in that texture. In UE4 this wouldn’t work (at least not fully), as the scene colour texture resolve is done per mesh element, not per entire mesh. As a result, inner polygons of a mesh element would be correctly occluded, but intersections with neighbouring elements would still contain ugly artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b5_RrVtURL0WiQOc.png" /></figure><p>Initially, we had used Tom Looman’s <a href="http://www.tomlooman.com/ue4-hologram-material/">hologram material</a>; it worked only partially, as the foremost character would cull out the ones behind him, and the ghosts are often in close proximity to each other, making it a no-go. In the end, I followed <a href="https://knarkowicz.wordpress.com/">Krzysztof Narkowicz’s</a> suggestion and added a just-in-time, per entire mesh depth prepass for those characters. Since the primitives were already sorted by depth, this gave us the exact effect we needed.</p><p>UE4 also did away with planar reflections. In hindsight, I probably should’ve implemented them, as that would save us a lot of pain when dealing with water rendering, but we decided to stick with what UE4 gave us out of the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UYejM3B73ciNYEPI.png" /></figure><p>Immediately after setting up <a href="https://docs.unrealengine.com/latest/INT/Engine/Rendering/LightingAndShadows/ReflectionEnvironment/index.html">reflection environment captures</a>, however, I was made aware of our lake apparently reflecting not one, but multiple suns, and all of them in the wrong place. This was due to depth-unaware blending of reflection cubemaps. Short of moving the game to a planet in a ternary star system, I had to fix that. Remember how I mentioned our and Epic’s goal being divergent? I ended up hacking the reflection capture system to discard our sky dome pixels, and injected a pre-rendered sky cube map to the rendering pipeline, pretending to be a <a href="https://docs.unrealengine.com/latest/INT/Engine/Rendering/LightingAndShadows/LightTypes/SkyLight/index.html">sky light</a> instead.</p><h3>Up to the whim of the artists</h3><p>Most of the time I was simply fulfilling the requests of our artists.</p><p>Don’t like lower LOD meshes having separate sets of lightmaps? Sure, I’ll make them use LOD 0’s. Don’t want any changes you make in the level to cause lighting to “unbuild”, or preview with dynamic lighting? All right, tricky, but there you go. You liked the tonemapper from 4.7 better than the new one from 4.8? Okay, rolling back the update. Want to spare some memory by compressing normal maps with DXT1 instead of BC5? Sure. Bring back simple depth of field as you know it from UE3? Yeah, done. Per-vertex fog on translucents needs to take light shaft occlusion into account? There you go.</p><p>Oh, you don’t like the temporal anti-aliasing? Erm… Let me check our options.</p><p>Even though I loved it, our artists didn’t like the way Epic’s temporal AA solution froze subpixel movement of the foliage and blurred the detail of textures up close. Tweaking its parameters didn’t help much. FXAA was temporally unstable, so that wouldn’t work either. So I set out to check out other options.</p><p>Eventually, I’ve integrated SMAA T2x. The artists liked it best: it exhibited reasonable temporal stability and no excessive detail blurring. However, due to being a mutlipass algorithm (edge detection, blend weight calculation and neighbourhood blurring in SMAA 1x, plus velocity integration and temporal resolve for SMAA T2x — for a total of five full-screen passes), it takes about 4 times as much time to complete as FXAA (single-pass), or about 1.5–2 times against Epic’s TAA. Plus, I never got around to properly resolving object motion coherency, so we ended up choosing FXAA after all. It works well enough for the game.</p><p><strong>Updated July 16, 2016:</strong> The Redux version for Windows eventually shipped with SMAA T2x, and I have recently <a href="https://github.com/inequation/UnrealEngine/tree/SMAA-4.12">released the code for that integration on Github</a> (<em>make sure to </em><a href="https://www.unrealengine.com/ue4-on-github"><em>have your Unreal Engine and Github accounts connected</em></a><em>, or the link will give you a 404 error</em>).</p><p>I’ve mentioned that due to the game relying heavily on static lighting, we were likely to hit unexplored corner cases. Quite a few times a particular setup of content made otherwise well-performing features break, and it was up to me to find out the reason and recommend a way to fix the content accordingly. For instance, we had particles spawning causing flickering of movable objects due to attachment group bounds being too large, or object position in materials resolving to a seemingly incorrect location, also due to excessive object bounds. In those cases, the fault was entirely on our side.</p><h3>Fixing bugs</h3><p>Any game engine in the world is a work in progress, and UE4 is no exception. While Epic’s support is pretty great and very competent, they have a gazillion of users to attend to, and you may simply need to wait to have your issue addressed. Having an engine programmer on the team brings you the advantage of (usually) shorter response time; these bugs are usually not that complicated and fixable in your own, local codebase (thanks for the full source, Epic!), and even if not, an engine programmer may be better equipped to provide proper diagnostics to Epic. We do try to get those fixes merged upstream when possible.</p><p>For Ethan on PS4 I’ve fixed a number of small issues, such as incorrect post-process material screen coordinates for non-full-screen viewports, imprecise occlusion for world position offset-rotated billboards, stale samples in the static lighting cache after level visibility changes, incorrect shader complexity visualization on masked meshes, shadow precision errors on large-bounds objects close to light sources, dithered LOD transitions not working when crossing <em>MinDrawDistance</em>, decals not rendering in one eye in VR…</p><p>Of course, it happens quite often that a bug is beyond my abilities. Here I’d like to give a shout-out to Marcus Wassmer of Epic, who provided priceless direct support to us with some really serious problems. Actually, we would like to to thank everyone at Epic who helped us with our game. The support we asked for was unique in a way that we needed some features that partially don’t even make sense for UE4, and were the result of us moving the game from UE3 to UE4. And yet Epic helped us with every such issue, and made Ethan Carter on UE4 possible.</p><p>Finally, while these weren’t bugs, I had made some tweaks to improve workflows and diagnostics. Based on the existing XGE distributed shader compilation code, I’ve created an integration with Sony’s <a href="http://www.snsystems.com/tech-blog/2014/01/06/building-with-the-network/">SN-DBS</a>, which dramatically improved shader build times (a small change in e.g. the base pass shader gave us 80k of shaders to compile! normally, that’s a two hours break in your work day!). Our version of the engine also freezes LOD transitions upon the <em>FreezeRendering </em>console command. The <em>r.CompositionGraphDebug</em> console command dumps paths to the post-process material to the logs, so you no longer have to guess which blendable it was. Our version of the <em>DisplayAll </em>command takes an optional noempty argument to filter out all the empty values. I’ve added a <em>stat relevantlights</em> command to dump all dynamic lights that were rendered last frame. And so on, and so on.</p><h3>Where does it go from here</h3><p>You may say, “fine, a graphics/engine programmer was useful for a port; but what about original games?”</p><p>That’s precisely where the fun part is!</p><p>Think about all the Unreal Engine 3 games of the previous generation. You got all kinds of genres, stories, art styles; but there is something in the visuals of most of those games that instantly gives away that they’ve got UE3 under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MBddHRtcSl1IiLJI.jpg" /></figure><p>Personally, I think it’s because of the lighting model and the post-process effects. Not everyone can afford — or even consider it viable — to change these, but subconsciously, our mind recognizes the way specular highlights work, the light shafts, the depth of field, the bloom etc. It’s not necessarily a bad thing, mind you! It’s just that we’ve seen it somewhere before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*dwHSoPX4pKnThxU2.jpg" /></figure><p>At <em>The Astronauts</em>, we take extreme care to make sure our games get a distinctive look. While UE4 is much more flexible than UE3, and it is now easier than ever for any game to achieve its own, original look, it’s always good to have extended control over your creation. For example, and I am aware this might not be anything that most people care about, but the way screen-space reflections are culled on the sides of the screen in a trapezoid shape is currently a dead giveaway of UE4 for me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GyXYcsHYAalvznYC.png" /></figure><p>I realize that tinkering with the post-process effects and lighting model is risky and ambitious; but this little band of 8 people called <em>The Astronauts</em> is all about aiming for the stars! ;)</p><p><em>Originally published on </em><a href="http://gamasutra.com/blogs/LeszekGodlewski/20150710/247996/quotYoure_on_UE4_why_do_you_need_an_engine_programmerquot.php"><em>Gamasutra</em></a><em> on July 10, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a21ccbc917d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building for Linux, the smart way]]></title>
            <link>https://medium.com/@TheIneQuation/leszek-godlewski-s-blog-building-for-linux-the-smart-way-25fe8784ec6f?source=rss-ba304e204257------2</link>
            <guid isPermaLink="false">https://medium.com/p/25fe8784ec6f</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Leszek Godlewski]]></dc:creator>
            <pubDate>Thu, 03 Apr 2014 00:00:00 GMT</pubDate>
            <atom:updated>2016-01-21T14:36:05.197Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Originally published on </em><a href="http://gamasutra.com/blogs/LeszekGodlewski/20140403/209842/Building_for_Linux_the_smart_way.php"><em>Gamasutra</em></a><em> on April 3, 2014.</em></p><p>The Linux land has a reputation, especially among developers used to Windows, of being — let’s say — somewhat savage, uncivilized. We’ve all heard the ghost stories: things being downright broken, lack of documentation and general despair; people coming, exclaiming: “what the fuck?!” and going right back.</p><p>Well, I’ve been exposed to the <a href="https://en.wikipedia.org/wiki/Unix_philosophy">Unix philosophy</a>, coding practices and general way of things for just under 10 years. This experience makes me comfortable with the platform, but I’ve still had <strong>a lot</strong> to learn in the past year in making the transition from Linux development as a hobby to making a living out of it. I’d like to share some of the less obvious tricks I’ve put up my sleeve — this time regarding the <strong>build system</strong>.</p><p>Unless mentioned otherwise, I will assume a 64-bit Debian system, “testing” branch (this is what SteamOS is based off of).</p><h3>Multilib</h3><p>This section may not apply to you if you don’t meet these two conditions:</p><ul><li>you still need to provide 32-bit binaries,</li><li>you are wary of the build environment provided by Steam Runtime (because e.g. you like alternating between gcc and Clang, or want to use gold for linking — more on that later).</li></ul><p>If you’re fine with 64-bit only or the SR toolchain, you may skip all the way to <em>Clang</em>.</p><p>If you, however, try building a 32-bit program on a 64-bit system (or the other way around) with the stock toolchain, you will most likely fail to build it, despite setting the correct architecture on it with a -m32, -m64 or a -march switch. Apparently, you are somehow missing the right libc and libgcc packages, even though they may seem to be installed.</p><p>The point of failure may be different, if any <strong>dependencies</strong> apart from the standard library are used in the program. That is usually a trivial issue, though, fixed by enabling <strong>multiarch</strong> and getting the :i386 package (for Debian, more on that <a href="https://wiki.debian.org/Multiarch">here</a>).</p><p>I used to maintain a <em>schroot</em> (kind of like a VM, but native — the kernel and some parts of the file system are shared with the host) with a 32-bit variant of the system just for the sake of building 32-bit binaries; however, there is a better way.</p><p>Enter <strong><em>gcc-multilib</em></strong>. Install <a href="https://packages.debian.org/search?keywords=gcc-multilib">this package</a> and suddenly the 32/64-bit cross-compiles start working as expected. It’s magic!</p><h3>Clang</h3><p>Okay, this one has been repeated ad nauseam recently, but it really makes a world of difference; also in terms of build times. A full rebuild of my current project takes:</p><ul><li>with gcc: 3m47s</li><li>with Clang: 3m05s</li></ul><p>You may say ~40 seconds is not a big deal; it is to me.</p><p>Not mentioning the not-so-obvious benefit of having another point of reference. And, given the fact that Clang aspires for full <strong>command line compatibility with gcc</strong> and usually <strong>builds everything that gcc can</strong> (it even defines the __GNU__ macro alongside __clang__, and supports the GNU extensions to the language), it really is a <strong>drop-in replacement</strong>.</p><p>It brings a lot of good and can be quickly switched back for gcc. What’s not to like?</p><h3>Linking</h3><p>This build step is a major source of grief for anyone who’s ever worked with a AAA codebase, as linking several hundred of object files and libraries can take <strong>ages</strong>. The Linux situation is made even worse by its aging linker, the GNU linker a.k.a. ld, which is single-threaded, requires objects and libraries to be specified in the order of dependency etc.</p><h3>gold</h3><p>The good news is that we are not doomed to use GNU ld. A few years back a small team at Google recognized the problem and decided to fix it, resulting in the development of <strong>GNU gold</strong> — a brand new linker built from scratch, whose most prominent feature is that it’s <strong>multi-threaded</strong>.</p><p>Switching from ld to gold in most cases is a question of a command line switch for GCC/Clang, or at most making a symlink. Here’s the command I use to link my current project’s binary on a Debian system, stripped of all irrelevant options:</p><pre>clang++ -B/usr/lib/gold-ld</pre><p>For my current project, switching the linker from GNU ld to gold <strong>took the link time down from 18 to 5 seconds</strong> on my Xeon E3–1240 v3.</p><h3>Library groups</h3><p>Another thing the GNU ld is infamous for is the seemingly unreasonable requirement of specifying libraries in the order of reverse dependence (i.e. an object’s or library’s dependencies follow the object or library; there is a <a href="http://stackoverflow.com/a/409470/398098">great explanation of that on Stack Overflow</a>, if you’re interested). This can get very annoying once you have to deal with circular dependencies, and while there is a way to do this “properly” — specify the library <em>again</em> — I’d much rather not have to think about it.</p><p>Turns out there are command-line switches that do just that (see the ld manual) — we can define a group of archives:</p><blockquote><strong>--start-group</strong> <em>archives </em><strong>--end-group</strong><br> The archives should be a list of archive files. They may be either explicit file names, or -l options.</blockquote><p>Or the short-hand version:</p><blockquote><strong>-(</strong> <em>archives</em> <strong>-)</strong></blockquote><p>Just dump your libs within the brackets and you’re set.</p><p><strong>There is a caveat</strong>, though: this causes the linker to perform an exhaustive search through all the libs in the group until all symbols are resolved. The manual warns of this having a possible performance impact. I haven’t noticed any in my project, but just keep that in mind.</p><h3>Debugigng symbols</h3><p>Bruce Dawson has given <a href="https://www.youtube.com/watch?v=xTmAknUbpB0">an excellent talk about Linux debugging</a> at Steam Developer Days 2014, so I’m not going to repeat here what he said. Instead I’ll just reiterate the two main points about symbols:</p><ul><li>use <em>objcopy --only-keep-debug</em> and <em>--add-gnu-debuglink</em> to split the debug symbols from the binary,</li><li>use the build IDs (GNU ld option <em>--build-id</em>, see manual) and a network storage to set up a symbol server.</li></ul><p>There is one thing that Bruce has not mentioned in the talk, though, and which is — in my opinion — crucial to daily work. <strong><em>Update:</em></strong> He did suggest it to me in a tweet post-factum, though, so kudos to him anyway!</p><h3>Caching the gdb-index</h3><p>When working with a large codebase, such as a triple-A-grade game engine, you may notice that the debugging symbols may be… well, somewhat heavy:</p><pre>$ ls -sh ADVGame-Linux32-Debug.dbg<br>244M ADVGame-Linux32-Debug.dbg<br>$ ls -sh SuperSecretProject.dbg<br>254M SuperSecretProject.dbg</pre><p>Ouch.</p><p>What’s even worse is that those ~250 megs need to be loaded by the debugger and processed to build an internal data structure for quick symbol lookup; with the files above, this can take <strong>10 to 30 seconds</strong> on my machine, and it happens <strong>every single time you load the binary in GDB</strong>.</p><p>There goes fast iteration time.</p><p>We can, however, <strong>cache this data structure offline</strong> instead and fold it into the build process! I think it’s a fair tradeoff between build time and runtime, considering that the latter almost always implies the index generation cost anyway. The <a href="https://sourceware.org/gdb/onlinedocs/gdb/Index-Files.html">GDB manual describes the method</a> well and concisely; here’s what I’m using for my project (assuming <em>SuperSecretProject </em>is the game binary):</p><pre>mkdir -p $(OUTPUT_PATH)/gdb-index<br>gdb -batch -ex “save gdb-index $(OUTPUT_PATH)/gdb-index” SuperSecretProject<br>objcopy --add-section .gdb_index=$(OUTPUT_PATH)/gdb-index/SuperSecretProject.gdb-index --set-section-flags .gdb_index=readonly SuperSecretProject SuperSecretProject</pre><p>Some trivial variable substitution makes this look less like a magic incantation. I promise!</p><p>As David Konerding has pointed out in the comments, newer releases of the gold linker can build the gdb-index for you at link time, which should be faster and is obviously easier (no GDB batch mode commands hodgepodge!). It’s now a question of appending <em>--gdb-index</em> to your linker command line, or <em>-Wl,--gdb-index</em>, if you’re using the <em>gcc</em> or <em>clang</em> compiler driver to link.</p><p>Thanks, David!</p><h3>Conclusions</h3><p>Hopefully, at least some of these tricks have been new and useful to you. If that’s the case — glad I could help! If not — why not share your tricks in the comments?</p><p>Also, I know what some developers are thinking: we shouldn’t need to be doing all this, we shouldn’t need to do so much research and documentation crunching just to do such basic things. And you’re probably right. I’d like to explore this non-orthogonality between the Unix philosophy and the game developer mindset in a future blog post.</p><p><em>Originally published on </em><a href="http://gamasutra.com/blogs/LeszekGodlewski/20140403/209842/Building_for_Linux_the_smart_way.php"><em>Gamasutra</em></a><em> on April 3, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25fe8784ec6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning your Steam Machine into a devkit]]></title>
            <link>https://medium.com/@TheIneQuation/turning-your-steam-machine-into-a-devkit-67159710eb13?source=rss-ba304e204257------2</link>
            <guid isPermaLink="false">https://medium.com/p/67159710eb13</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Leszek Godlewski]]></dc:creator>
            <pubDate>Sat, 01 Feb 2014 00:00:00 GMT</pubDate>
            <atom:updated>2016-01-21T14:23:01.865Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Originally published on </em><a href="http://gamasutra.com/blogs/LeszekGodlewski/20140201/209839/Turning_your_Steam_Machine_into_a_devkit.php"><em>Gamasutra</em></a><em> on February 1, 2014.</em></p><p>I happen to be one of the lucky lessees of the Gigabyte BRIX Pro (Intel Corporation makes no mistake about it making it clear it’s their property on lease) thanks to my participation in Steam Dev Days. Even though these days my main development system is a Debian Linux box, the BRIX’s somewhat unique hardware — the Intel Iris Pro 5200 GPU — combined with SteamOS, makes it desirable to be able to treat the little Steam Machine in the same way as a console devkit.</p><p>In this article I will try to explain how to achieve the following with a SteamOS box:</p><ul><li>easy deployment of software,</li><li>remote control (starting and killing of processes, grabbing screenshots),</li><li>remote debugging.</li></ul><p>As you can see, this does not include building, which I think is better to do locally and not remotely, but with a little bit of general Linux knowledge you should be able to set it up without too much effort.</p><p>SteamOS is based upon Debian Linux. Having used Debian daily for more than I care to remember made things easier to start with. For all kinds of remote access, including file system access, we will use SSH. Remote debugging over network can be achieved using <em>gdbserver</em>.</p><h3>SteamOS setup</h3><p>After installation, SteamOS has two user accounts: <em>steam</em> for the Big Picture mode, which is the one the system boots into by default, and <em>desktop</em>, which has a Gnome-based desktop interface. Both accounts are password-less, which will turn out to be significant in a moment.</p><p>We need to do some setting up on the machine itself first, so go to Settings -&gt; Interface and Enable access to the Linux desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*ct-d-50Lb6y1pEI8.png" /></figure><p>Then we have to actually access the desktop, which we can do by going to the Exit menu and choosing Return to Desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*Pj_YM-RTKJ1Sve9z.png" /></figure><p>That should switch us to the <em>desktop</em> user and present us with a Gnome user interface. Click <em>Activities</em> in the top-left corner to bring out the menu, then choose <em>Applications</em>, and then <em>Terminal</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*Dwzaak8kUUL1R5Vk.png" /></figure><p>The first thing we need to do is to set up a password for this account. This is necessary to be able to acquire system administrator (<em>root</em>) permissions to install software and what not.</p><p>From this point on in this article, a line starting with the dollar sign (<em>$</em>) means a shell command to be executed as a regular user, while the pound sign (<em>#</em>) means a shell command executed as root. The command sudo allows a regular user to acquire root rights, for the duration of a single shell command, by typing your regular user’s password.</p><p>In order to change the password, type:</p><pre>$ passwd</pre><p>And type any password you like, twice. Note that the characters you input will not be displayed.</p><p>Cool, now we can start installing software. The first, and basically the only thing we need is the OpenSSH server — it will allow us full remote access to the machine. Here’s how to install it:</p><pre>$ sudo apt-get install openssh-server</pre><p>This should get the SSH server up and running. The last thing we need to know is the IP address of the SteamOS box (note the fragment in bold; if you have more network interfaces, such as wifi, they may be listed as wlan0 or something similar):</p><pre>$ /sbin/ifconfig<br> eth0 Link encap:Ethernet HWaddr 74:d4:35:4e:38:2c <br> <strong>inet addr:192.168.0.25</strong> Bcast:192.168.0.255 Mask:255.255.255.0<br> inet6 addr: fe80::76d4:35ff:fe4e:382c/64 Scope:Link<br> UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1<br> RX packets:82606 errors:0 dropped:0 overruns:0 frame:0<br> TX packets:36889 errors:0 dropped:0 overruns:0 carrier:0<br> collisions:0 txqueuelen:1000 <br> RX bytes:95247271 (90.8 MiB) TX bytes:45690367 (43.5 MiB)</pre><pre>lo Link encap:Local Loopback <br> inet addr:127.0.0.1 Mask:255.0.0.0<br> inet6 addr: ::1/128 Scope:Host<br> UP LOOPBACK RUNNING MTU:65536 Metric:1<br> RX packets:214 errors:0 dropped:0 overruns:0 frame:0<br> TX packets:214 errors:0 dropped:0 overruns:0 carrier:0<br> collisions:0 txqueuelen:0 <br> RX bytes:17236 (16.8 KiB) TX bytes:17236 (16.8 KiB)</pre><p>You can now go back to your main development box, we’ll be controlling SteamOS remotely from this point on.</p><h3>Logging in without a password</h3><p>I will now assume you are on a Linux box, since SteamOS development requires a Linux development machine anyway; however, all of the required SSH functionality can be achieved on Windows by using <a href="http://www.putty.org/">PuTTY</a>, and on MacOS as well.</p><p>Working with the SteamOS has a catch: the user accounts are by default password-less. This means that you can neither easily acquire root rights, which is necessary to e.g. install software, nor log in via SSH to remotely control the machine. We have fixed that <strong>only partially</strong> in the previous step — we can now use SSH to get into the <em>desktop</em> account, but we still can’t log into the <em>steam</em> account, which is what we should be doing to launch games. <strong>Setting up a password for the <em>steam</em> account is not a viable option</strong>, though — some things in SteamOS expect it to have no password, and by setting one we may break some stuff. We do not want that.</p><p>Fortunately, SSH has a very useful feature called <strong>authorized keys</strong>, which is a list of public keys (if you don’t know what these are, <a href="https://en.wikipedia.org/wiki/Public-key_cryptography">read up on asymmetric cryptography</a>) authorized to log into an account without typing the account’s password.</p><p>If you are on a Linux box, chances are you already have a public key associated with your development user account (look for a file called <em>~/.ssh/id_rsa.pub</em>). If not, use the <em>ssh-keygen</em> tool to generate one. The PuTTY suite has a key generator of its own which you can also use.</p><h3>The “desktop”<em> </em>account</h3><p>Once you have your key set, we need to upload the public key (<strong>do not confuse with the private one!</strong>) to the Steam Machine. This can be done via a single command:</p><pre>$ ssh-copy-id desktop@[IP address of your SteamOS box]</pre><p>The <em>ssh-copy-id</em> utility will ask for the password for the user desktop we have set in the previous section. Once you provide it, you will be able to SSH into that account without providing a password.</p><p>If for some reason this does not work, all you need to do is to append the contents of your <em>~/.ssh/id_rsa.pub</em> from the development machine to the <em>/home/desktop/.ssh/authorized_keys</em> file on the SteamOS devkit.</p><p>You may want to repeat this step for any user account on any development machine you want to use to connect to the devkit.</p><h3>The “steam” account</h3><p>Unfortunately, we can’t just <em>ssh-copy-id</em> into the steam account, since it still has no password. We can, however, just copy the authorized key list into that account, so let’s log onto the devkit:</p><pre>$ ssh desktop@[IP address of your SteamOS box]</pre><p>Make sure the <em>.ssh</em> directory exists for the <em>steam</em> account and that it’s accessible to that account (i.e. it belongs to the <em>steam</em> user and group):</p><pre>$ sudo mkdir -p ~steam/.ssh \<br>    &amp;&amp; sudo chown steam ~steam/.ssh \<br>    &amp;&amp; sudo chgrp steam ~steam/.ssh</pre><p>And finally, copy the authorized key list:</p><pre>$ sudo cp ~/.ssh/authorized_keys ~steam/.ssh/authorized_keys</pre><p>You will also need to repeat the above steps (<em>ssh-copy-id</em> and authorized key list copying) for new developer accounts wanting to connect to the devkit.</p><h3>Remote file system access</h3><p>SSH provides access not only to the command shell on a remote system, but also to its file system. There are many tools for that — the OpenSSH client for Linux includes <em>scp</em> and <em>sftp</em> (on Windows, the PuTTY suite provides PSFTP), but for transparent access I highly recommend using <a href="http://fuse.sourceforge.net/sshfs.html"><em>sshfs</em></a> (should be available in your Linux distro’s package manager) — it makes the remote volume accessible just like a locally mounted hard drive partition, for instance.</p><p>There are conceptually similar tools for Windows, such as <a href="https://code.google.com/p/win-sshfs/">win-sshfs</a> and <a href="http://dokan-dev.net/">Dokan</a>, allowing mapping of SSH connections as Windows network drives, but the projects seem dormant — they may or may not work for you.</p><h3>Remote control</h3><p>Controlling the devkit remotely boils down to sending commands to it via SSH. A rule of thumb is that for any application which is not just a command line tool, but interacts with X11 (i.e. the graphics layer in Linux), you need to prepend the command with a string like <em>DISPLAY=:0</em>. What it does, is it sets the environment variable <em>DISPLAY</em> for the duration of the shell command that follows to the X11 display used by the <em>steam</em> account (this is basically always <em>:0</em>).</p><p>You can also start all your SSH sessions by typing:</p><pre>$ export DISPLAY=:0</pre><p>Which will set the variable for the duration of the session, or better yet — add it at the end of the <em>~/.profile</em> file (it’s like the autostart script for the command line shell).</p><p>Here are a few examples. You might want to turn those commands into scripts for quick issuing from the developer machine.</p><h3>Taking screenshots</h3><p>The easiest way is to use Gnome’s screenshot utility:</p><pre>$ DISPLAY=:0 gnome-screenshot</pre><p>This will save the frame grabs to the <em>~/Pictures</em> directory of the steam account in PNG format, complete with a timestamp. An error message could be shown; disregard it, it will still work.</p><h3>Launching your game</h3><p>This most essential feature is currently broken, as the game works but does not display. :) Working to fix it. Read on for a temporary workaround.</p><p>Since the “easy” way (<em>DISPLAY=:0</em>) currently does not make your game display, you can work around it by using the desktop account and <em>DISPLAY=:1</em> instead and running the “legacy” non-Big Picture Steam client from there. To do that, we will first need to install the legacy client launcher:</p><pre>$ sudo apt-get install steam-launcher</pre><p>Then we can launch Steam (<strong>not from the desktop “Return to Steam” icon!</strong> you can use the <em>Activities</em> menu instead or type <em>steam</em> into a terminal, or press Alt+F2 for the “Run” dialog) and let it bootstrap itself. Then proceed as above, but staying on the desktop account and <em>DISPLAY=:1</em>.</p><h3>Killing a process</h3><p>If your game has crashed and you need to kill it, simply issue the <em>kill </em>or <em>killall </em>command:</p><pre>$ kill [PID of process to kill]</pre><pre>$ killall [name of process executable]</pre><p>The subtle difference being that <em>killall </em>will kill all processes of that executable, not just the chosen PID.</p><p>The above sends the <em>SIGTERM</em> signal, which is a request for a graceful exit. If the process has crashed so badly it cannot do a graceful termination, you may need to issue a <em>SIGKILL</em> signal instead (forceful termination):</p><pre>$ kill -9 [PID of process to kill]</pre><pre>$ killall -9 [name of process executable]</pre><h3>System shutdown or reboot</h3><p>To do this, you need root access, so log into the <em>desktop</em> account and type:</p><pre>$ sudo poweroff</pre><pre>$ sudo reboot</pre><p>According to the desired effect.</p><h3>Setting up the remote debugger</h3><p>This is a little bit more tricky, since <em>gdb</em> is not present in Valve’s SteamOS package repository. However, we can hook up Debian repositories with your SteamOS installation — Steam user Shark has written <a href="http://steamcommunity.com/groups/steamuniverse/discussions/1/648814396114274132/">a really good guide to installing Debian packages on SteamOS</a>. You can skip steps 1–4, log into the desktop account via SSH and pick up at 5.</p><p>Once you have done that, simply use APT to install the <em>gdb</em> and <em>gdbserver</em> packages (note the <em>-t</em> option, which makes for a greater chance the install will go smoothly):</p><pre>$ sudo apt-get -t install gdbserver</pre><p>And you’re all set!</p><h3>Debugging via SSH</h3><p>If you’re comfortable with the command line, the easiest thing to do is to simply run your game in <em>gdb</em>, just like running it normally.</p><pre>$ DISPLAY=:0 gdb [path to your game executable]</pre><p>However, this will not work if you are using a GUI frontend for <em>gdb</em>. If that’s the case, read on.</p><h3>“Real” remote debugging</h3><p>The <em>gdbserver </em>is exactly what it sounds like: it’s the back-end portion of the <em>gdb </em>debugger glued to a simple server accepting connections. Once started, it will wait for a gdb front-end to connect. From the front-end point of view, it makes almost no difference in your mode of operation, which also allows you to use GUI front-ends.</p><p>Log back into the steam account for testing and launch your game on the devkit:</p><pre>devkit$ DISPLAY=:0 gdbserver [devkit hostname]:[port number] [path to your game executable]</pre><p>Port number is arbitrary, any free TCP port will do.</p><p>Then connect to the server from your development machine (note that we’re still launching the game executable in <em>gdb </em>— this is to pull in the debug symbols, which will not be loaded otherwise):</p><pre>developer-machine$ gdb [path to your game executable]</pre><pre>(gdb) target remote [devkit hostname]:[port number]</pre><p>From this point on, the client <em>gdb </em>has full control of the executable running on the devkit.</p><h3>Summary</h3><p>Well, that’s it! Now hack away and make that game of yours run smoothly on Linux and SteamOS!</p><p>Found any errors? Got questions? Comment away!</p><p><em>Originally published on </em><a href="http://gamasutra.com/blogs/LeszekGodlewski/20140201/209839/Turning_your_Steam_Machine_into_a_devkit.php"><em>Gamasutra</em></a><em> on February 1, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67159710eb13" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>