Inigo Quilez   ::     ::  
1402 blog posts, written between 2008 and 2016. These are mostly short observations, funny thoughts and word playing. Some are embarrasingly corny, some more deep. I keep it here mostly a little time capsule for myself, organized by month:



<
June 2011
>
rays love polygons
2011-06-29
this is very old news, but since i was explaining this in an email to somebody, but it doesn't quite qualify for an article in my website, i thought of dropping it here. that's what boxrooms are for, after all.

so, say you are raymarching or raytracing some objects in a fragment shader, and you want to composite them with some other geometry that you rendered or will render through regular rasterizarion. the only thing you need to do is to output a depth value in your raytracing/marching shader, and let the depth buffer do the rest. the first to do, then, is to understand what "depth" means here.

in a raytracer/marcher, you probably have access to the distance from the ray origin (you camera position) to the closest geometry/intersection point. that distance is NOT what you want to write to the depth buffer, as hardware rasterizers (opengl or directx) don't store distances to the camera, but the z of the geometry/intersection point. the reason is that this z value is still monotonically increasing with the distance, but has the property of being linear (linear like in "interpolatable across the surface of a play 3D triangle). so, in your raymarcher, compute the intersection point, and use it's z component for writing to the depth buffer.

well, that will not work just like that. your api of preference will remap your z values to a -1 to 1 range based on the near and far clipping planes you decided to set up. furthermore, the remapping will probably also transform your z values to some other sort of scale that exploits the properties of perspective (like with a curve that compresses values in the far distance). so you will have to implement the same remapping in your shader before you can merge your raytraced/marched objects with the rest of the polygons.

the mapping is simple, though, and is normally configured by the projection matrix. grab your opengl redbook, and have a look to the content of a standard projection matrix. the third and forth row are what we need, since those are the ones that affect the z and w components of your points when transformed from eye to clip space. so, if ze is the z of your intersection point in camera (eye) space, then you can compute the clip space z and w as

zc = -ze*(far+near)/(far-near) - 2*far*near/(far-near)
wc = -ze

the hardware will then do the perspective division and compute the z value in normalized device coordinates before converting it to a 24 bit depth value:

zn = zc/zw = (far+near)/(far-near) + 2*far*near/(far-near)/ze

which you can see it is a formula of the form zn = a + b/ze which produces the desired depth compression. you can check that the boundary conditions are met, by doing

ze = -near -> zn = -1.0;
ze = -far -> zn = 1.0;

yeah, remember that your depths in camera space are negative inwards the screen. so, our raytracing/marching shader should end with something like

float a = (far+near)/(far-near);
float b = 2.0*far*near/(far-near);
gl_FragDepth = a + b/z;

you probably want to upload a and b as uniforms to your shader.

alternatively, if you don't want mess with all this, you can directly grab the projection parameters from the projection matrix, and do something like

float zc = ( (ModelView)ProjectionMatrix * vec4( intersectionPoint, 1.0 ) ).z;
float wc = ( (ModelView)ProjectionMatrix * vec4( intersectionPoint, 1.0 ) ).w;
gl_FragDepth = zc/wc;

which is a little bit more expensive, but gives the same results...
...why would i change
2011-06-27
i'm still on windows xp, listening to my music in winamp, and using my hotmail account for email. it all works perfectly, and gives me more than what i need. so...
siliconE valley
2011-06-25
going to a pool party in silicon valley - check

(and it was pretty awesome, if you ask me)
iñicleta segunda
2011-06-23
llevo un mes y medio caminando, caminando mucho. desde que abandoné a mi iñicleta, voy al trabajo a pie. hoy, tuve que ir a oakland para un tema de papeles, allí en matalasparras, y mientras volvía al currelo a pata pasé por delante de una tienda de bicicletas y me abordadó el sentimiento aquél de ya está bien, a tomar por culo, el patear se va a acabar.



la nueva iñicleta es más ligera, más cosmopolita, y más sexy. no tiene marchas, ni falta que le hace, hoy hemos superado todas las colinas sin ningún problema. ¡esto promete!
no confundir
2011-06-21
nota, "silicon valley" es el valle del silicio (microchips), no de la silicona (macrotits). aunque sea más común ver de lo segundo que de lo primero.
no es lo mismo
2011-06-19
hay una pequeño conjunto de palabras con culo que no son esdrújulas... pero tampoco son sustantivos, sino verbos (primera persona singular del presente indicativo, como yo circulo, yo especulo, yo calculo, yo reculo, yo articulo o yo musculo). nah, me siguen gustando las esdrújulas
smoothstep in a napkin
2011-06-17

pillabilidades
2011-06-15
las pillabilidades son la probabilidad de pillar
¿reconquista? creo que va a ser que no
2011-06-13
y hablando de la lengua española, quiero compartir una revelación.

había leído yo innumerables veces que el español estaba de moda, y no sólo estaba de moda, sino que además de ser la lengua más hablada en estados unidos después del inglé, pronto se convertiría en una lengua necesaria y relevante en la vida del nortemaricano.

mi percepción no puede ser más alejada de eso. creo que confundieron el número de personas que conocen el español con el número de personas que lo hablan, y sobre todo, lo hablarán.

los hijos de los immigrantes latinos en estados unidos hablan el español porque lo usancon sus padres, pero lo hablan mal. se sienten más cómodos hablando en inglés, y orgullosos de hacerlo, pues éste es el idioma con el que se escolarizaron, que hablan son sus amigos, con el que leen, escuchan la música, ven las películas, miran la tele, con el que primero estudian y después trabajan. estas generaciones de latinos tienen al inglés como lengua materna, muy apesar de sus madres, y si bien aún son capaces de hablarlo, eso sí, relativamente fluido pero con su acentito americano y sus errores y torpeces y tropiezos y simplezas, nunca lo usarán con sus hijos. ni falta que les hace. sus vidas se desarrollan en inglés.

así que aquello de que el español conquistaría los estados unidos... desengañémosnos: me parece que va a ser que no. creo que lo del spanglish quedó también en anecdota. me temo que en estados unidos se habla inglés y poco más, señores. ¿qué nos pensábamos?
movimientos
2011-06-11
hace dos años y medio me alarmé con la carencia relativa de artículos en lengua española comparando con otros lenguages en principio menos populares como el japonés, el polaco o el holandés, que gozaban de un número mayor de artículos en la wikipedia.

desde aquél día, he muestreando cuatro veces el número de artículos en estos mismos idiomas, siendo la última hoy. lo que he visto es que el español ha va ganando posiciones poco a poco: ha pasado de ser el noveno lenguage a ser el quinto. si acaba sobrepasando al alemán o el francés, concluiré que el peso demográfico tiene una mayor influencia que la relevancia (¿económica?) de los países que hablan la lengua, como aventuré a proponer. veremos.





nadar
2011-06-09
me encanta nadar. pero no lo de dar brazadas en el agua, sino nadar de no hacer nada.
metamorfosis
2011-06-07
¿tiempo de cambios? posiblemente, creo que ya me vale de hacer el capullo
apples to oranges
2011-06-05
this laptop PC that I own is 4 years old now. even for me, that i do pretty heavy work on computer graphics and algorithms, it's still a good machine. i lovely call it (him) "orangy". and since it was not designed to be good looking and cool and trendy at all time, i don't feel that urge to replace it with a better looking (but not necessarily faster) one. yes, different business models i know, but still, i cannot resist the temptation to compare apples to oranges.
dedos y tildes
2011-06-03
casi todos los idiomas tiene palabras diferentes para los dedos del pie y los dedos de la mano. pero en castellano no. ¿las tuvimos alguna vez y las perdimos por el camino, o nunca nos hicieron falta?

la reflexión más larga jamás hecha sin tildes
unicode? yet?
2011-06-01
speaking of things that were supposed to have been sorted out by now, Unicode.

shouldn't unicode be functional since, dunno, 10 years ago? i already resigned from writing my name properly quite some years ago. cause, yep, still today, ñ displays and prints as a tiny square in most systems. i don't mind about my name, but c'mon, why do I still get some friend's text messages broken with white spaces in between characters (specially from those using iphones in romaing network)?

unicode? where are you!