I'm Morgan McGuire (@CasualEffects). I've been working on computer graphics and games for 20 years at great places including NVIDIA, Williams College, Brown University, and Activision.

See my home page for a full index of my blog posts, books, research, and projects.

Monday, March 11, 2013

JavaScript Doc Strings



codeheart.js is an open source 2D web and mobile game Javascript framework designed to be extremely easy to learn and use, even for non-programmers. In fact, it intentionally avoids providing many support routines in order to encourage learning to program (this also allows advanced programmers to include or write their own rather than having a structure imposed).  I'm writing a book to help new programmers learn codeheart.js, but also needed an online reference for the 112 API entry points. 

Friday, February 15, 2013

Upcoming Graphics Codex 1.9 Features


I'm now working on a number of interactive features for the next update of The Graphics Codex to really take advantage of the mobile app (vs. printed book or PDF) platform.   It is already the case in version 1.8 that some of the diagram tables link to more information about a specific topic, for example, some of the elements in the radiometric quantities table shown below on iPad mini
link to detailed information about that quantity and how it is measured.

Screen Capture Animated GIF on OS X

Animated GIF is a terrible video format: a 256 color palette with a low compression ratio that trashes bandwidth and still looks bad. Unfortunately, browser vendors failed to agree on a modern video standard and many APIs (including Twitter and most HTML tags) don't support video in any format in place of images, so Animated GIF is the best that there is for embedding video inside other APIs.

Short animated GIFs suitable for posting on Twitter are simple and free to create on OS X.  I use the free OS X App Screen Record Pro-Lite to capture a QuickTime (MOV) format video of a screen region and then convert the MOV to GIF online at http://www.online-convert.com/. To produce an MP4 video instead, I could convert the MOV online or using iMovie.

I haven't been able to post animated GIF files to Twitter via their web interface, but the (also free) official Twitter app for OS X allows posting them by dragging the GIF into a new tweet window.






Morgan McGuire is a professor of Computer Science at Williams College and a professional game developer. He is the author of The Graphics Codex, an essential reference for computer graphics that runs on iPhone, iPad, and iPod Touch.

Tuesday, January 8, 2013

Computer Science for Other Domains

Crytek Sponza  rendered by
CS371 students with photon mapping

In the process of presenting the CS371: Computer Graphics that I teach at Williams College as an ACM/IEEE 2013 Curriculum for Computer Science exemplar in computer graphics, I had to answer the question, "why do you teach the course this way?" The the answer that I provided is below. It is currently a core part of my philosophy for teaching science at a liberal arts college*. 

Wednesday, August 29, 2012

Sol LeWitt's Art and Computer Science


Sol LeWitt was an early conceptual artist whose work I was first introduced to my first year at college by Prof. Bill Porter. His work is computational and geometric, yielding images in the space between graphic design and fine art.

Yale University, Williams College, and MASS MoCA collaborated on a long-term retrospective of his work that, because his work is created directly on the walls under the direction of the artist, will probably be the final gallery showing of his wall drawings ever. Below is the piece that I wrote for a related show on LeWitt at Williams, discussing how I use his artwork in my computer graphics and data structures courses.

Tuesday, August 7, 2012

Separating the Socket.IO application and web server

This post describes how to write a simple JavaScript program with real-time client server interaction that works with a regular web server instead of creating a custom one in Node.js. This is the framework that you probably want for extending your website with network-based interactive elements or writing a browser based multiplayer game. My previous posts explained how to install Node.js and Socket.IO and how to write your first Socket.IO program. This series is essentially a transcript of what I learned while setting up multiplayer game examples for codeheart.js.

Running a Web Server on OS X Mountain Lion

The point of this post is to extend your existing web server, which assumes that you have a web server. If your site is hosted somewhere else, you can just upload the files described below to it. If you are testing or are running directly on OS X Mountain Lion, you can do the following to launch the web server. Note that OS X Lion and earlier had a GUI for launching the web server directly in the Sharing pane of Preferences, but that was removed in Mountain Lion.

At a command prompt, type:

   sudo apachectl start

That launches your webserver.  Place the files described in the following sections in the

   /Library/WebServer/Documents

directory. The file is writeable only by root in the default install, so I ran:


   sudo chown $username /Library/WebServer/Documents
   chmod u+rwx /Library/WebServer/Documents


to be able to easily modify its contents from my developer account.  To stop your web server, remember to execute:


   sudo apachectl stop

when you're done testing. The web server will automatically stop if you reboot your machine as well.



Creating the Server-side Application

I'm going to call the server-side application app.js.  It will run under Node.js.  It can run on a different machine from the web server, although for simplicity in testing I'm going to describe running them both on the same machine.  The point is that the application is on a different port from the web server and only handles network traffic directly related to the application. It does not serve files to web browsers.

The server program is just:

app.js

// Listen on port 1080 (arbitrarily chosen here and in index.html
var io = require('socket.io').listen(1080)

io.sockets.on('connection', function (socket) {

  socket.emit('myMessageType', 'Hello world');

  // Example of how the client can filter for messages.  This one
  // will not go to the messages log.  Instead it will change the
  // color of a square.
  socket.emit('colorMessage', {color: '#0F0'});

  socket.on('myResponseType', function (data) {
    console.log(data);
  });
});
You run it by typing:
sudo node app.js
at the command line.  Note that you must have previously installed Socket.IO in the same directory (see previous post on how to install Node.js and Socket.IO).



Creating the Client-side Application


The client side application is stored on the web server. It is then downloaded to the client by a web browser and executed locally. On your server, you need to store the following index.html file and the complete contents of the node_modules/socket.io/node_modules/socket.io-client/dist/ directory, which were created by the install of the server-side Socket.IO library. Put the contents of that directory into a socket.io directory, so that you have a directory structure on your web server like this:



(if you're running your web server on OS X Mountain Lion, then this is the contents of your /Library/WebServer/Documents directory).

The index.html file for this demo is:


<html>
  <head>
    <!-- Load Socket.IO from our web server, which is separate from the
  application's server. -->
    <script src="http://localhost/socket.io/socket.io.js"></script>
    <script>
      // Tell Socket.IO where to find the Flash component if the browser needs it.
      WEB_SOCKET_SWF_LOCATION = 'http://localhost/socket.io/WebSocketMain.swf';
    </script>
  </head>
  <body>
    <h1>Socket.IO Demo</h1>

    <!-- A log for messages -->
    <div id="messages" style="border: 1px solid #000; width: 100%; color: #0F0; background: #000; font-family: monospace;">
      Connecting to server...<br/>
    </div>

    <div id="colorsquare" style="border: 1px solid #000; width: 32px; height: 32px; background: #F00; margin-top: 10px;"></div>

    <script>
      // Make the output visible
      var messages = document.getElementById('messages');

      // Connect to our app.js, which is listeninging on port 1080 
      var socket = io.connect('http://localhost:1080');
      
      socket.on('connect',
        function() {
          messages.innerHTML += 'Connected<br/>';
        });

      socket.on('myMessageType',
         function(data) {
           messages.innerHTML += 'Server says: "' + data.toString() + '"<br/>';

           // Respond to the server
           socket.emit('myResponseType', { my: 'data' });
        });

      socket.on('colorMessage',
         function(data) { 
            document.getElementById('colorsquare').style.background = data.color;
         });
    </script>

  </body>
</html>

In this case, I'm assuming that both the web server and node are running on the local machine. If you have a different web server, replace "localhost/" with your server's name (but do not replace "localhost:1080/"... that's Node.js's server!)

Now load the page in your browser, for example, by pointing your browser at http://localhost/index.html


You should see the following:



The green box had its color changed from red by a message from the server. The text in quotes in the black box was transmitted by the server.

The code above shows how to connect, modify an HTML page based on network messages, and how to filter different kinds of messages. That's everything that you need in order to build arbitrary networked browser-based applications in JavaScript.


Getting started with Socket.IO

Socket.IO is a library for Javascript (and ported to other languages) that provides client-server network connections. Under the hood it uses WebSockets, Flash, ActiveX, and other tools to provide an implementation that works on many browsers. It is a great tool, but the documentation is poor. So here's some information about how to get started that is missing from the manual.

Saturday, August 4, 2012

Installing Node.js and Socket.IO

This blog post describes how to set up Node.js for writing server code in Javascript. The following two posts show how to get started with Socket.IO and how to separate the web server and application server.

Tuesday, July 31, 2012

The Journal of Computer Graphics Techniques


I'm the Editor in Chief of the Journal of Computer Graphics Techniques (JCGT), the free, peer-reviewed, and open access journal of computer graphics practice. JCGT was founded in May 2012 by an influential group of computer graphics experts.  Our goal is to document and advance the state of the art, in the way that Graphics Gems and the Journal of Graphics Tools (jgt) each did. I don't mention those two publications casually. Both were created by Andrew Glassner, who is on the new JCGT advisory board, and all former jgt Editors-in-Chief and most of the 2012 jgt editorial board now serve on the JCGT board.

Next week, most of the JCGT board will be at SIGGRAPH. I encourage anyone to talk to them about the new journal.  The numbers alone are fascinating for a brand-new scientific publication with no commercial advertising:
I've received a lot of great questions by e-mail and in person at conferences about the nuts and bolts of the journal, such as how we handle copyright and publishing. Many of these are addressed on the submissions page of the website. I plan to add new information to the website in September about how our back-end systems work. This is important for helping others to create online scholarly publications and for explaining how papers published in JCGT will be available indefinitely despite inevitable change in how electronic documents are stored and retrieved.

Ronen Barzel suggested that I share the answer to one common question that many people are simply curious about: how is the JCGT board funding the journal?

The answer comes in three parts. First, it isn't that expensive to publish a graphics journal electronically. All of the writing, editing, and reviewing is done by volunteers and most of the software is free open source (LaTeX, BibTeX, Apache, MySQL, mod_xslt2, Emacs, Ubuntu, etc.)  The board is unpaid, as is the case for most academic editorial positions. Graphics authors and editors are capable of producing professional-quality typesetting, layout, and diagrams on their own.

Second, Williams College has a grant from the Mellon Foundation to create digital archives to match the quality and reliability of the college's substantial physical scholarly archives. Those physical archives are in rare books, visual art, scholarly journals, and congressional papers. I find the breadth and depth of those fascinating: the college's holdings include original drafts of the US Declaration of Independence and Constitution, first editions of major scientific works such as  Principia Mathematica , and paintings by major artists such as Picasso. The college is well-positioned to archive and conserve digital computer graphics papers and unlike a commercial publisher, an academic library has no agenda for those materials beyond preserving knowledge for all. 

Third, the minor incidental costs of advertising, hosting, and legal are being picked up out of pocket by a few of us. Of of the financial contributions and dues I've given to graphics organizations, this was the one I was most pleased to make. We're not accepting donations or seeking outside funding--that would subject us to bookkeeping overhead and legal requirements. If you want to support the journal, the best way to do so is to read it, write for it, and offer your services as a reviewer.

Saturday, June 9, 2012

Annecy 2012

Some short films that I enjoyed at the Annecy animated film festival 2012 are below.  Many of the graduation films were fantastic but unfortunately they are not listed online.  Some of these premiered in previous years and were repeated this year.

Una Furtiva Lagrima, stop motion of a real fish's journey to dinner sung as (ironically happy) opera.  Brilliantly witty, sad, and funny.
http://furtivalagrimafilm.blogspot.fr/p/making-of.html


Tram, http://www.michaelapavlatova.com/show/folder_anim/TRAM.html


Space Stallions, a mock 80's cartoon title sequence from film students in Denmark: http://www.youtube.com/watch?v=5Otaq2tmNMM

Une Historie Vertebrale, a romantic comedy about an L-shaped man, http://www.youtube.com/watch?v=Pq2hPgSzIwg

----

Aalterate, an abstract meditation on rebirth through an eclipse rendered in varying 2D and 3D styles http://videos.arte.tv/fr/videos/_aalterate_de_christobal_de_oliveira-6438028.html




Bydlo, allegory of struggle and conflict through claymation--of clay people http://www.nfb.ca/film/bydlo_trailer

Koisuru Nezumi, a mouse falls in love with a cheese, with dialog seemingly translated through several languages and recited by a computer http://www.youtube.com/watch?v=WGMOeg1-pQU

Hi-no-youjin, love, loss, and the danger of fire in a historical Japanese city. Clever combination of orthographic and linear perspectives http://www.annecy.org/edition-2012/festival/programmation/programme-fiche-film:f20121300

Second Handhttp://www.annecy.org/edition-2012/festival/programmation/programme-fiche-film:f20120830

The Centrifuge Brain Project, a seamless live action and animated faux science documentary http://www.youtube.com/watch?v=-kCFdVYojyg

Moya Iyubov, a beautifully rendered tale of unrequited love in Russia painted on glass, http://www.youtube.com/watch?v=dq7nLVoaPX8

Tsukumo, reminiscent of Studio Ghibli, http://www.annecy.org/edition-2012/festival/programmation/programme-fiche-film:f20121338



Tuesday, March 13, 2012

Pseudocode Motivations



I received a few e-mails asking about the choice of pseudocode for most algorithms in The Graphics Codex.  Presenting code in a useful form for reference is an interesting problem and like all technical writers, I struggle with it on each project.  There are three challenges for code in this project in particular:

1. What would you do with directly compilable code on an iOS device?  
2. Compilable code is rather big
3. What language/library to use?

I chose Python-like pseudocode based on my analysis of those challenges.  Read on for the details of why.



Getting Code Samples out of iOS
You can't actually program on an iOS device, except for maybe via VNC or other remote desktop software. I don't expect most readers to be in that situation frequently.  So how can I provide reference data that you might want to copy and paste into a program directly?

My solution is to add a button to e-mail large constants and code samples to yourself.  That should deal with the copy-paste problem both in terms of interface and machine.  I'm developing this for the next release at the end of March 2012.

Compilable Code is Lengthy
Code samples in The Graphics Codex aim to help you get your head around an algorithm. If the code fits on one screen, you have a chance of doing that.  It is even better if it fits on one screen with a diagram next to the code.  When the code gets lengthy, you lose the algorithm in all of the clutter.  At that point, you should pull up a code sample from elsewhere on your dev machine and walk through / single-step through it in your favorite IDE.  

The G3D Innovation Engine code that I link to in The Graphics Codex is open source and provides C++ implementations for most of the interesting code samples. I recommend going there or performing a search on the web for code using:


Graphics uses many Languages
HLSL and GLSL have sufficiently different syntax that they are no longer interchangable.  Most graphics programmers use C++ (I think) for host code, but Cg/GL/DX are radically different on the host side.  For API-independent algorithms, C++ is so dependent on the specific templates and libraries that you're using that it isn't really portable between projects--plus, you might want to implement that algorithm in GLSL, Cg, or HLSL anyway.  For example, my:

  const Vector3& x = Vector3::uniformRandom();

isn't very helpful to you if you're in GLSL, where you probably have to say:

  vec3 x = normalize(texelFetch(randomUniform, ivec2(glFragCoord.xy), 0).xyz);

and even if you're in C++, maybe your library doesn't overload the same operators or provide the same vector methods.  

Which Pseudocode?
The specific style of the pseudocode is something I'm actively experimenting with. I chose Python-like syntax and extended it with common C++ operator overloading, comment operators, and mathematical type annotations.  Choosing a specific scripting language as a model gives me a nice default for conventions rather than inventing everything from whole cloth.  Graphics is usually written in an imperative language, and Python offers both that plus occasional elegant functional structures. It has a very economical syntax without being telegraphic or effectively encrypted like Perl, and is a language that many (although probably not most) graphics programmers are already comfortable.

There are a few topics for which pseudocode is really not appropriate, so I give explicit C++ or shading language code for those. I expect most algorithms will be in pseudocode.

As always, I welcome suggestions for new topics, ones to expand, or new ways of presenting the content of The Graphics Codex.

Wednesday, March 7, 2012

The Graphics Codex 1.3: the "Color" update

The following changes are complete for The Graphics Codex 1.3, and the update has been uploaded to Apple for review.  Expect it around March 24, 2012.

  • App Changes
    • Doubled image resolution for the new third-generation iPad retina display
    • Fast orientation change
    • Fixed slow scrolling on index for some devices
    • Infinite projection matrix topic no longer crashes app
    • Ball-ray intersection topic no longer crashes app
    • Corrected lots of small typos in prose
    • Increased UI contrast
  • New topics
    • Compressed hardware texture formats (S3TC, BC, DXn, PVRTC)
    • RGB <-> sRGB equations
    • Index of all GLSL functions, with links to the man pages
    • Hyperbolic cosine
    • ASCII 128 table
    • XML escape codes
    • Luminance
    • C/C++ integer types and utilities
    • Normalized fixed point equations
    • Reciprocity in light scattering
    • Versons (unit quaternions)
    • Quaternion basis
    • Quaternion inverse
    • Photometric quantities
My feature list for version 1.4 includes:
  • Color wheels
    • Newtonian
    • CIE-CAM
    • Munsell
    • Painter's triangle
    • Printer's triangle
  • Candela
  • Color theory; harmonious color palettes
  • Fresnel effect example photographs
  • Guide to typesetting accents in HTML, Unicode, LaTeX, and ASCII
  • More diagrams
  • Button to e-mail code and constants to yourself

E-mail suggestions, feedback, and corrections to me at morgan@casual-effects.com

Thursday, February 9, 2012

Prevent overscroll on iOS Safari

iOS 5.x Safari supports single-finger scrolling of the contents of a DIV or IFRAME. However, scrolling that DIV too far makes your entire page scroll as well. This behavior is undesirable if the page was specifically designed to fill the mobile screen. I've seen some heavy-handed solutions to this, including disabling all scrolling and using iScroll 4 to simulate it.

Below is my solution.  This leverages the browser's own scrolling mechanisms and adds minimal runtime overhead, so scrolling stays lightweight, portable, and efficient.  The caller includes this script and then says something like:

<script>
  // This must be during the bubble phase (i.e., last argument =
  // false) so that inner objects have an opportunity to override it.
  document.addEventListener('touchmove', function(e) { e.preventDefault(); }, false);
  var scroller = document.getElementById('scroller');
  preventOverScroll(scroller);
</script>

at the bottom of the HTML document.

Thursday, February 2, 2012

The Graphics Codex 1.2 Feature List

The Graphics Codex 1.2 update will be available on the App Store at the end of February. This post describes development work on this update.


I choose features based on community feedback. E-mail feature requests and corrections to me (Morgan) at morgan@casual-effects.com or tweet @CasualEffectsVote on major feature priority on the web page.


Confirmed changes in 1.2:
  • New features
    • Rewrote user interface from scratch for faster loading and scrolling
    • Buttons are easier to press
    • Scrollbar indicators
    • New look (see below)
  • New topics
    • Euler Characteristic
    • Euler Formula
    • The Sun, including spectrum and radiance
    • New diagrams for intersection topics
    • LaTeX includegraphics documentation, space, and font-size tables
    • n-dimensional Convolution
    • n-dimensional Cross-Correlation
    • Table of LaTeX, HTML, Unicode, and ASCII math symbols
    • Axis-angle to unit quaternion
    • Quaternion product
    • Manhattan distance
  • Corrections
    • Sideways scrolling for large tables and figures on iPhone
    • Consistent font sizes on iPhone
    • Rotation from Unit Quaternion topic [quat2mat] now works
    • Corrected definition of psi in [sphry], [sphrz]
    • Restored the missing 1's in [trns3]


New look:

Friday, January 20, 2012

The Graphics Codex 1.1 Update Feature List

The Graphics Codex version 1.1 went live on the App Store Jan. 31, 2012.  This post lists the features.  I prioritize features for each update based on the poll on the web page, so vote there for what you want to see next.


New in version 1.1:
  • Searchable index
  • Fast startup time
    • About 1s for the first load on iPad 2 and iPhone 4; may be slower on iPad 1 and iPhone 3
    • Instantaneous load when switching apps
  • Smooth scrolling
  • Type annotations for all equations and new button for showing and hiding them
  • Reorganized all matrix topics under a single heading
  • New diagrams
    • Refraction/Snell's law
    • Ray-Triangle intersection
  • New topics
    • Unprojecting from a depth buffer
    • Arithmetic mean
    • Geometric mean
    • Expected value
    • Variance
    • Area of a 3D triangle
    • 4 matrix determinant
    • n matrix determinant
    • C++ method pointer syntax
    • Greek alphabet (+XML, HTML, Unicode, LaTeX, ASCII codes)
    • Shadow map pseudocode, with PCF
  • Mathematical corrections
    • Fixed minus signs and added supersampling offsets to projection matrices
    • Fixed the vector diagram for triangle solid angle
  • Many small refinements to existing topics






Thursday, January 19, 2012

The Graphics Codex is now on Sale




Real-Time Rendering, Third Edition:$64
Physically Based Rendering, Second Edition:$52
Fundamentals of Computer Graphics:$81
Not carrying your graphics books home...Priceless

The Graphics Codex is an essential mobile reference for 3D computer graphics. The value may be priceless, but the cost is only $2.99 in the App Store during January, 2012.



http://itunes.apple.com/us/app/the-graphics-codex/id494971103?mt=8

Saturday, January 7, 2012

New Website Design

It was time to replace my original placeholder design of the Casual Effects website, as the release of The Graphics Codex nears.  The original design is below on the left and the new look is on the right:



The original took 30 minutes when I needed something to reserve space on the newly registered domain. The redesign took me about three hours.  About one hour was figuring out what I wanted, another half an hour was implementing it, and the rest was largely using CSS to hack the style of the embedded Twitter and Blogger feeds, which are produced by third-party JavaScript and CGI scripts, and tune the whitespace and colors.

Tools
I'm trained and primarily skilled as a scientist, programmer, and engineer--not a graphic designer.  I know many principles of graphic design but don't have particular skill there and don't know how to use any web design software.  So I try to stick to simple designs and create my web pages by coding directly in Emacs using HTML5, CSS, JavaScript, and XSL.

To extract the feed from Twitter, I used their embedding widget.  To extract the feed from Blogger, I used code by FeedWind.  Each can be somewhat customized; I then used custom CSS to hack the rest.  The Chrome browser's "Inspect this element" command was essential for debugging during this step.

Layout
I wanted my website to list currently active projects and current twitter and blogger posts.  This site is for my independent ("hobby?") projects, so it should also accurately portray the one-man show and indie aspects.  So, to design the website, I looked at the sites from some (much bigger!) indie game teams that I admire, including:


All mostly follow the "WordPress" look of a fixed-width center column with a side-bar for a twitter feed.  I like the way that Unknown Worlds and Mark ten Bosch list their projects with a big image and short description, so I mimicked that.  Unlike most sites, I didn't want the blog front-and-center, so I pushed it down to the bottom and left it as headlines, not the actual blog (i.e., this page!)

Title
I didn't have any new ideas for the title, so I kept the original Casual Effects stylized text.  The carbon-fiber background was too busy to keep behind all of the new text, so I pushed that to the far background and used plain white.  The drop-shadow on the title was too extreme against white and other sites all have a clear separation of title area and body, so I put a solid gray banner behind the title.

Color
When you're not a master of color, I believe that it is best to limit your palette. In this case I chose to simply vary the value of the already primarily monochrome scheme and add a single accent color.

I kept the yellow/gold from the title as the accent color and used it for hyperlinks.  I then used the gray from the title for headers so that they wouldn't fight for emphasis with the body text.  I likewise made the headers all lower-case to echo the formatting of the title and again de-emphasize them.  I hope all of the lower-case comes off as embodying the "casual" from the title, without being over-stylized.

The gray in the headers is slightly darker than the title bar--the larger expanse makes the title bar seem darker, so I had to compensate.  The link gold is darker than the titlebar yellow to make it more readable.

Note that the Endlyss logo is intentionally gray and monochrome and the image for The Graphics Codex is primarily monochrome because it is just a picture of an iPad and iPhone.  I'd be happy to have more color here if future projects merit it, but it was convenient that these are neutral and will slide into any theme.

Fonts
I find sans-serif fonts hard to read.  They were originally designed for titles and for small text on low-resolution displays.  The latter made them associated with computers and "high-tech", so they are (over) used on the web.  I use serif fonts (preferably Georgia, to not look exactly like everyone else's Times New Roman) for body text and sans serif (the old Helvetica standby) for titles.  I usually justify text, but these paragraphs are short enough that they look better with a ragged right.

I added a lot of white space between elements to keep the design clean without borders and rounded the corners of the center box.  The round corners echo the lower-case titles and stand out a little from the default square that you see on most websites.

Shadows
The title and main box have ambient-occlusion style drop shadows.  They are primarily to separate the objects and create depth and contrast without appearing as a concrete visual element.  I modeled them on the default drop shadow parameters on OS X.




Wednesday, January 4, 2012

Translucency in OBJ / MTL Files

This post describes some reverse engineering work on the handling of translucency in MTL material files used with legacy OBJ 3D model files.

Motivation
Endlyss is a hybrid 3D modeling game inspired by Minecraft's creative mode.  I like architecture and designing buildings.  I really enjoy the building aspect of Minecraft (compared to using something like 3DS Max, or even SketchUp, which I find too hard to use to create buildings).  However, I'm frustrated by the voxel limitations of MC.  So I decided to make my own modeling game targeted at casual users but with power tools that would satisfy a 3D modeling artist.  Endlyss is that game.

In order to bring data in and out of Endlyss I wrote support for both Minecraft and OBJ import and OBJ export.  OBJ files specify the material name for each mesh, but the materials themselves are described separately in MTL files.  Those are documented extensively online, e.g.,

http://www.fileformat.info/format/material/
http://paulbourke.net/dataformats/mtl/

However, the documentation is not all consistent, and in some cases does not match what I observe when importing files into 3DS Max (version 14.0, 2011).  Compatibility with Max is the primary reason to have OBJ support, so that trumps the documentation.

Why use the legacy OBJ format instead of a full-featured file format with clear documentation?  For example, COLLADA or FBX. Like many in the graphics community, I appreciate the features in the newer formats but find them hard to work with in practice.  I prefer to use simpler, more widely-supported formats, and OBJ is something of the lowest common denominator for 3D models.

Transmission vs. Partial Coverage

You can read a discussion of the difference between transmission and partial coverage in the appendix of this paper: http://graphics.cs.williams.edu/papers/CSSM/.  The basic idea is that partial coverage means "this surface has holes in it" and transmission means a combination of "light travels at a different speed through the medium on the other side of this surface" and "as it passes through that material, some, but not all light is absorbed."  You can see some of the differences in the photograph below.

Thin red cloth has 50% partial coverage, so it reflects
50% of "red" light.  A red gel has 50% transmission, so it
 reflects almost no light but transmits 50% of the "red" light.

In general, partial coverage is useful for representing cutouts (1 = solid, 0 = hole), and holes and edges below the resolution of the texture map (with fractional values). For example, the edges of leaves that cross through texels, and a window screen for keeping bugs out.  Transmission creates refraction and "colors" the light that passes through it.

You also should see a diminished specular highlight on a surface with partial coverage (since that surface is partly not covered by the material!), but should see full-strength specular highlights on a transmissive surface--although you should set your constants to ensure energy conservation. 

Do we really need both transmissive and partial coverage constants?  Well, it is possible to represent frequency-invariant (i.e., uncolored), non-refractive transmission using partial coverage.  It is possible to represent partial coverage for materials with no specular reflection (which are themselves impossible, since anything that transmits must reflect due to Fresnel effects) using transmission and no refraction.  But those are pretty severe and confusing limitations for a physically-based renderer, so I prefer to keep the concepts separate.


MTL Files
Wavefront MTL files contain a series of blocks that look something like this for specifying materials:

newmtl default
  Ns 10.0000
  Ni 1.5000
  d 1.0000
  illum 2
  Ka 1 1 1
  Kd 1 1 1
  Ks 0.0 0.0 0.0
  Ke 0 0 0
  map_Kd default.png
  map_d alpha.png

I won't describe those in detail (see http://www.fileformat.info/format/material/), but essentially:

  •  "illum" specifies the kind of BSDF by number
  •  "K" values are RGB parameters
  •  "map" values are texture map parameters that trump the associated "k"
  • "N" values are scalar parameters
There are several parameters in these blocks that affect the transmission of light and partial coverage of a surface.  Based on my experiments with 3DS Max, these are:
  • "d" specifies a scalar transmission value, where 1 = no transmission and 0 = 100% transmission.  This must be transmission and not partial coverage because if d=0, then you can see specular highlights.
  • "map_d" is a grayscale image that specifies a varying "d" value across a surface.
  • "Tf" is an RGB value, but 3DS Max 2012 averages across the three channels to produce a scalar transmission coefficient.  Specifically, 3DS Max transmits (1.0 - Tf) of the light, which is the opposite of what the above reverse-engineered documentation says.  For example, 'Tf=1 1 1" transmits no light and "Tf=0 0 0" transmits all background light.
  • The alpha channel of the "map_Kd" texture is ignored.
Here's a sample of one test that I ran to determine that "d" is transmission and not partial coverage:

The map_Kd texture map is in RGBA8 PNG format.  The white square in the map_Kd has A=0, which you can see is ignored in the render on the far right.  The specular highlight on the d=0 part of the map in the right image shows that this is a transmissive coefficient and not partial coverage.

"d" and "Tf" interact in nonobvious ways, as shown below (there is no map_Kd on these).



Finally, I've heard that some packages recognize map_d textures with an alpha channel and use that instead of the intensity, so that you can use "map_d file / map_Kd file" to get alpha cutouts.  3DS Max does not:




Transmission Holds Out Reflection
In 3DS Max, the reflected light is automatically reduced by the transmissive coefficient (this is analogous to partial coverage with a convention of NOT using premultiplied alpha).  The experiment that I used to determine this is below.  In it, the two cubes are rendered from directly above.



Conclusions: Alpha
Unfortunately, from these experiments, it appears that there is no way to do an "alpha cutout" in OBJ format that will be rendered correctly as partial coverage in 3DS Max.  The lack of this is troubling; the best that one can do to fake it is apparently to:
  1. Ks = 0 0 0 
  2. Specify a grayscale map_d, where 0 = hole and 1 = solid
  3. Do not premultiply coverage by map_Kd
I'll continue to support partial coverage in the alpha channel of map_Kd in my own software.  This is backwards compatible to 3DS Max but won't render the cutout there.

I intend to support colored transmission with "Tf" and "map_Tf", and will accept that 3DS Max and other programs may ignore the color (but will at least maintain the average transmission).


Tuesday, January 3, 2012

The Graphics Codex


The Graphics Codex is an app for 3D graphics students, engineers, teachers, and artists. It provides consistent, correct, and easy-to-understand definitions for technical material. Unlike a book, it is always with you. Unlike a PDF, it conforms to the orientation and screen size of your mobile device uses the full power of iOS.

The Graphics Codex collects my notes from teaching computer graphics at Brown University and Williams College and developing commercial games with Iron Lore Entertainment and the Vicarious Visions studio of Activision | Blizzard.

I will release the app with about 100 entries as soon as it is approved by Apple, and then add more content each month as a free update. I use The Graphics Codex every day while working on computer graphics and hope that it will help others now as well!