Sunday, November 8, 2009

The House Of Stairs

English    Spanish

Today I'm going to show a set of renders that although they are not totally finished I would like to show.
The target is the representation in 3D of the picture "The House Of Stairs" of M.C.Escher. I focused the representation of walls and stairs. The strange animals and the doors are missing.

The results are these, in black and white and in color:


In the color version I have simply used blackbody illuminants with temperatures of 3000, 4000, 5000 and 7000 Kelvin.

In order to make the renders we have to do this. It's necessary to model the scenery in such a way so the dimensions fit using whole units (fitting into a grid). So we make sure that all walls, walkways and stairs have similar widths. With any CAD program it's possible to model the scenery looking the original drawing. The objects at this point have box geometry.



Because the rendering of boxes is too dull we have to add some effects. One of those has to emulate the round shape of a stone. In order to achieve that we can use textures or 3D models. In this case I preferred using 3D models to achieve more quality. Accomplishing this is simple. We cubicate the scene with the same resolution of the design grid. Now we have a set of voxels. Each voxel is replaced by a rounded cube mesh shape. The only problem is the amount of data and so the high processing time.



Later we apply a material to the surface. For that is used a composite material. The material is composed by one control map and two data maps. The control material is used to decide the amount of blending between the data materials. It's similar to an alpha blending. For the control map I have used a binary threshold discretized Perlin noise function. In the high part I have assigned one kind of bumpmap and in the lowest part another kind. So, two bumpmaps of controllable independent characteristics are obtained. Now we simply apply a greater scale factor and noise to one to look like holes in stone, while applying a smoother noise to the other. With only one bumpmap would have achieved a smoothed and polished stone effect with some holes. We don't want it.



Finally to render it's used a cylindrical camera to emulate the curved effect of "The House of Stairs". With a little wise we can place the camera more or less the same position where Escher sat it.

Monday, September 14, 2009

Spatial Labyrinths

English    Spanish

Today I'm going to show a set of renders that I did some time ago. The general idea is to make a spatial maze.

That is, one that allows movements upwards and downwards as well as forward, backward, right and left. The movements that a player can do are in any spatial axis. In this case, Theseus has to know how to climb well.

One simple is this one:



In this one we see a tridimensional labyrinth bounded by the surface of a cube.

The procedure to accomplish this renders is not complex.
  • We start from a tridimensional shape. Then it's discretized in voxels marking as active the ones that are partially or totally included in the volume defined by the surface of the figure.
  • Now we are going to discard the non active voxels and we work with the ones that intersect or are included inside the volume.
  • We start from a random voxel and we move in a random direction, marking as visited the currant voxel.
  • As we move through the voxels we can find a visited voxel in the chosen direction. In this case we chose another direction.
  • In the case that there are not any available directions we move backwards and we chose another direction.
  • The algorithm ends when all the nodes (voxels) have been visited.
This algorithm allows a unique path from one point of the labyrinth to another. Obviously if we set two poins, one as starting and another one as ending, there will be a unique path between both, and then any other bifurcation that moves away from the path will bring us to a dead end.

Other views of the cube:











It's possible to use other figures as a "mould" of the labyrinth.

Here we can see a sphere:





And with a spherical camera:





The Utah teapot:



and a some renderings of a lying woman:




















Sunday, August 2, 2009

Spherical Renders of Labyrinths

English    Spanish

Recently I was thinking about how one of the mazes that I programmed would it seen using a spherical lens. Spherical lens deform parts of the images that are away from center, so the things that are far away looks like further away indeed. So more things "fits" inside the image.
When the deformation is low the result is similar to a wide angle lens. When the deformation is high we get images more dificult to achieve in reality. When the deformation is very high the images are imposible to obtain in reality.
The code that generates a particular ray for a pixel can be coded like this:


Ray RayGenerator::GenerateRay(int pixel_x, int pixel_y)
{
Ray ray;
double u,v;

ConvertPixel_to_Unit(pixel_x,pixel_y,u,v);

ray.orig=From;
ray.dir=-Normalize3d(-i + u*tanFov*aspect*j + v*tanFov*k);

return ray;
}

This code generates rays that advance in the negative direction of the X axis

Slightly modifying the code we can obtain our new spherical camera:

Ray SphericalRayGenerator::GenerateRay(int pixel_x, int pixel_y)
{
Ray ray;
double u,v;

ConvertPixel_to_Unit(pixel_x,pixel_y,u,v);

u*=fishEyeFactor*aspect;
v*=fishEyeFactor;

Vector V;
double r=sqrt(u*u+v*v);

double a=atan2(v,u);
V.y=sin(a)*(1-cos(r));
V.z=-cos(a)*(1-cos(r));
V.x=sin(r);
V=Normalize3d(V);

Matrix matrix=Construct4d(i,j,k,VECTOR3D(0,0,0));
V=TransformVector3d(V,matrix);

ray.orig=From;
ray.dir=Normalize3d(V);

return ray;
}

This type of projection generates a pole (or singularity) in the positive direction of the X axis. This generates images wery similar to the ones that Escher made in Circle Limit. As we aproach to the horizon we go to infinity.
With the value 'fishEyeFactor' we replicate the plane several times over the sphere reaching infinity as concentrical circular shapes.

This image is a normal render of an infinite labyrinth:


As we increase the spherical factor we slightly deform the image:


If we increase too much the factor we reach infinity several times:


We can make a render looking "down" obtaining an image that remainds quite well to the ones of M.C.Escher:


Likewise it's possible to increase the spherical factor:

Sunday, April 26, 2009

Top Mod 3D Images

English    Spanish

Today i'm going to upload a set of renders that I did recently with a fantastic topological modelling program. The program's name is TopMod3D. Although the figure may seem complicated, thanks to this program are simple to perform.


Using a white skydome.


Using a blue skydome.


Using a blue skydome and a lightsource.


The figure uses a phong material with a high phong exponent.


Set of two objects: A box defined with a phong material and a totaly lambertian figure.


The figure's material simulates a laquer phong coating.


Material with bumpmapping for the box.


Changing the floor's material so a shadow can be appearing (adding a diffuse component)



A high contrast image with a front lightsource.


A high contrast image with a rear lightsource.

Thursday, February 5, 2009

Infinite Labyrinths

English    Spanish

In a previous article (Truchet Tilings) I showed a way to represent labyrinths in a sphere and at the end, in a plane. In this one I'm going to show a way to represent infinite labyrinths in a plane.

Usually these labyrinths are finite sets of triangles. One of the problems in this type of representations is that you can see boundings.

One way to solve this is replicating the figure. Sooner or later you'll be able to see a periodic shape, noticing an artificial behaviour.

So, if you want to show infinite labyrinths, you'll have to find a method that satisfy these conditions:
  • Covers all the visible domain.
  • Absence of periodicity in the image.
The way that I present here in order to do this task is the next one:
  • Split the plane (in an algorithmic manner) in square regions of unit size (a grid of infinite squares, each one with one unit of side length).
  • Asign to each square region a tridimensional figure (for example, a wall in a side).
When a ray step inside a region, it will intersect with the associated shape in that region. When, by reflexion or traversing, it changes the region, a new intersection will be computed with the new form associated to the new region.

Here I show a sample using always the same shape.



This method presents a set of decissions:
  • How many types of shape should I use.
  • How I assign to each region a concrete shape.

The first point is chosen by the user. For example, my set of shapes will be:
  • A wall of 0.1 units width and 1 unit length arranged in a north face of the region.
  • Another similar wall arranged in the west face.
For the second point we have to think a bit. To each coordinate (integer) of the space I have to assign a random number. The function will be f(i,j)->n. Being i and j integer numbers and n a real number from 0 to 1. This function has to return values highly distinct of 'n' using slight variations of i and j. This is either a hashing function or a pseudorandom generator. Esentially are the same.
The generator will be a LCM (Linear Congruent Method) generator. We run the risk of having the Marsaglia effect. It will appear, and the user might see a certain periodicity but will be very dificutl to distinguish.

Each shape has a certain probability for appearing (for example: 1/number_of_figures). It will choose the figure using the method of the Russian roulette depending on the generated random number. As the number is pseudorandom and depends on the input paramaters, it always return the same value for the same input parameters.

The results are these:


And with a different probability distribution:


As you can see, choosing this kind of figures, as the norwest corner is always occupied, the aspect seems to be a growing figures in the same direction.

It can be resolved by adding another figure that is a double wall south and east. So using this way the distribution of corners is uniform and doesn't seem to grow in any direction. Althoug this adds more holes and makes the maze looks more closed.


This is with a figure with a column in the middle of the region:


Making simplier walls appears problems of double corners and doesn't seems very well.

Finaly there is a more complex method than the previous one. Consists on chosing figures randomly only in pair coordinates (i,j) which sum i+j are even (from this point, even regions). That yields a checker pattern. In the even regions we assign one shape selected by the pseudorandom generator. In the other hand, in the odd regions the shape is assigned by a shape that matchs with the shapes that are sharing each face. That is, if the north face of the figure that I have in the south has a wall, my south face should have a wall. So, both walls match together.

Choosing correctly the shapes and with a little extra programming we can achieve these images:




Using non linear cameras:


Using some procedural textures and phong materials:


If we use the first proposed method the labyrinth looks like this:

That's wrong but nice to test global illumination.

Obviously changing slightly the hashing function (adding a sum operation, in example) we can make labyrinths totaly indistinguishable ones with each others. We have graphically represented the hashing function.

Wednesday, January 28, 2009

White Sky

English    Spanish

I put here some renders that I did some time ago and I have re-rendered recently. Simply they are simple geometric figures to test oclussions. The skydome is totaly white, as well as the reflectors and the luminarie. The result so it is gray. Originally these designs were backgrounds of a lost blog that I did long time ago. It can be work quite well as wallpapers.



Sunday, January 18, 2009

Truchet Tilings

English    Spanish

Today I'm going to show a set of renders that are related to Truchet Tesellations. In 1704 Sebastien Truchet thought about a system of teselate a plane using oriented triangles. A modification of this one allow us to generate labyrinthic motifs using curved lines. In 1989 Pickover shown that it was an elegant method to see patterns in pseudorandom numbers secuences.

Seeing the Pickover's motifs I thought that it should be a way to tesselate a sphere without producing singularities at the poles.

So, here they are the ingredients:
  • Take a geodesic sphere discretized in triangles more or less regular with similar size.
  • Define 5 triangular tiles.
  • For each triangle replace it with one of the 5 tiles in a random fashion or with a certain probability distribution.
Here I show the results:

It can be shown only a certain kind of tiles:
Type 1

Type 2

Type 3

Type 4

Type 5

Only two types:




Uniform proability distributions:


Distributions of non uniform probability for each type:






Finaly all the types:


Images without the inner sphere:

and with a inner point of light:

With other materials:




Planar projections with non-linear cameras:


Finally, with all those projections depends on a triangular mesh it's possible to make denser motifs or even with a certain meshes. Like in this case, the Stanford Bunny:

Saturday, January 17, 2009

Textos bilingües

English Spanish

This post is not related to computer graphics. I present a way to show posts in two languages. The mechanism is very simple and can be used in blogspot as I'm going to show. I haven't wasted too much time in finding over internet similar mechanisms. Due to the simplicity of this method I had prefered doing it by myself.

In order to achieve this javascript will be used. I expose the steps:

  • Modifying the template

  • Creation of the language links in the post

  • Definition of the language blocks in the post


Modifying the template
The template can be modified in Design options of blogger. It's possible to add this:

<script language='javascript' type='text/javascript'>
function showBlk_1 ()
{
var nodeObj = document.getElementById('blk_1')
nodeObj.style.display = 'inline';
var nodeObj = document.getElementById('blk_2')
nodeObj.style.display = 'none';
}
function showBlk_2 ()
{
var nodeObj = document.getElementById('blk_2')
nodeObj.style.display = 'inline';
var nodeObj = document.getElementById('blk_1')
nodeObj.style.display = 'none';
}
</script>

The code is simple. If showBlk_1 is invoked, the style of the block identified by blk_1 is changed to visible, and the one identified with blk_2 is set to invisible.
The other function does the oposite operation.

Creation of the language links in the post
Simply we define the tags 'span' o 'a' with a href targeting '#' and this is the important thing: An onclick function:
For example:

<a href='#'><span onclick="showBlk_1()">Spanish</span></a>
<a href='#'><span onclick="showBlk_2()">English</span></a>


Definition of the language blocks in the post
Finaly now the texts in the two languages are written. The text in the language associated to the block 1 (blk_1) will be inside in a div block identified with blk_1.
The texts in the other language will be inside the other block.
For example:

<div id="blk_1" style="display: inline;">Esto es un texto en idioma Español.</div>
<div id="blk_2" style="display: none;">This is an English text.</div>


One of the blocks has to be visible and the other ones invisibles so by default only one language will be shown.

Here, for clarity it has been added a return carriage to separate the divs but in the post the 'divs' shouldn't be separated. If not, the second language will appear with an extra line.


Conclusion
It has been shown a very easy way to generate posts in two langages. This model it's also easily scalable to manage schemes with multiple languages.

Prueba bilingüe

English Spanish

This is an English text.

Saturday, January 10, 2009

Gravity Paths

Dejo aquí unos renders que hice hace poco. Representan las trayectorias de partículas con masa dentro de un campo gravitatorio arbitrario. Para realizarlo he partido de un objeto tridimensional. He calculado su campo gravitatorio. Luego he dejado dentro del campo un conjunto de partículas. Avanzando la simulación las partículas se mueven dentro del campo. Se pueden registrar sus trayectorias a medida que se mueven. Una vez que se obtienen las trayectorias se pueden convertir a objetos sólidos tubulares. Con el objeto sólido se puede realizar un render de pathtracing y obtener estos resultados:





Thursday, January 8, 2009

Lattice Object

El otro día estuve mirando un libro de Escher que tengo desde hace tiempo. Hojeándolo llegué hasta uno de los dibujos que siempre me había sorprendido por su regularidad: "Cubic Space Division" . Este dibujo se puede representar a mano con un poco de paciencia, cosa que les sobra a las computadoras. Así, que decidí realizar un pequeño programa que representara escenarios parecidos a ese dibujo.

Cómo mostrar el espacio sin más es aburrido, decidí representar un enrejado acotado por la superficie de un objeto. Para ello utilicé una herramienta que codifiqué hace más o menos un año. La herramienta (una clase en C++) determina si un punto está dentro o fuera de un objeto cerrado. Esta herramienta se pensó para determinar el volumen de un objeto amén de utilizarse para obtener otras interesantes características como el tensor de inercia del sólido rígido que representaría. Para determinar el volumen, normalmente se eligen puntos aleatorios acotados dentro de una superfice que engloba el objeto y se haya una relación entre los que están dentro y los totales. Si esta relación se multiplica por el volumen acotado de la superficie englobante tenemos una aproximación del volumen. Estas técnicas de integración numérica son muy útiles cuando es muy complicado o imposible obtener una función analítica que represente la función de superficie que se desea integrar.

Para realizar este modelo simplemente hay seleccionar puntos equiespaciados en los tres ejes espaciales y almacenar los que están dentro del objeto a analizar. Analizando la vecindad de los nodos (ver si tiene vecinos en los tres ejes y sus dos direcciones) se pueden añadir empalmes que parejas de éstos. Es necesario elegir cautelosamente los tamaños de los nodos y de los empalmes para que el armazón no englobe todo el espacio.

Dejo por aquí algunos renders. Una vista interior:

Otras exteriores...



Y una exterior más de cerca:

Sunday, January 4, 2009

Brócoli con suelo liso

Dejo por aquí otros dos renders del brócoli de Romanesco. He quitado el fondo de ajedrez como comentó Mamen.

En este render el suelo es simplemente gris. El color azulado se debe a la radiancia que emite la cúpula celeste (si nos fijamos cuidadosamente veremos que en el mundo real pasa algo similar, las sombras diurnas son ligeramente azuladas).


En este otro render he cambiado la BRDF del suelo de difusa a una de phong (con un exponente de 1024). El efecto conseguido es un suelo reflectante que dispersa parcialmente los rayos de luz que llegan. Los reflejos más distantes se vuelven más difusos. Obviamente el color azulado es debido al color del cielo.


Sunday, December 28, 2008

El brócoli de Romanesco

Recursividad y autosimilaridad, dos características propias de los fractales. La autosimilaridad es propia de la naturaleza y la recursividad de las computadoras. Está por lo tanto la naturaleza, ¿computada?. No lo creo, es más probable que simplemente sea el resultado de una compresión de datos a nivel genético y una optimización de los recursos desde un punto de vista evolutivo. En cualquier caso es fascinante.

Las plantas son los seres vivos que mas relacionados están con la geometría fractal. El ejemplo clásico es el helecho (Fern) representado en otro 'post' mediante una técnica de IFS. Una técnica sorprendente dado que une el caos, la autosimilaridad y el orden en un único elemento. Representando puntos aleatorios y transformandolos usando una función iterada nace la autosimilaridad. Entrada aleatoria, mundo real; iteraciones, evolución. Personalmente no sé si la naturaleza funciona así, pero sus resultados son sorprendentes.

Uno de los ejemplos que más me ha impresionado del mundo vegetal es el brocoli de Romanesco. Conos organizados en espiral con otros conos dentro de los primeros y así sucesivamente, de tal suerte que se organizan de forma esferoide maximizando el volumen, minimizando los huecos, siendo una figura óptima.

Para representar por computadora este brócoli he utilizado simplemente un mecanismo recursivo. Siguiendo el concepto básico de función iterativa he partido de una matriz de transformación (identidad) que he ido rotando y escalando en cada iteración. Siendo el resultado de una iteración la fuente de la siguiente. Representando una esfera (o cualquier otro elemento) en el punto que determina la transformación de cualquier punto del espacio (constante en todo el proceso, por ejemplo (1,0,0) ) con dicha matriz se puede representar una forma. En este caso una espiral. Si se toma, para cada uno de esos puntos medidos en la primera pasada, su matriz de transformación asociada y se usa como matriz original de una nueva serie de transformaciones obtenemos el fenómeno de la autosimilaridad.

Esta técnica no se puede llevar hasta niveles elevados (más de 3) porque el número de elementos crece rápidamente. En el ejemplo hay dos niveles de recursividad. Nótese, a modo de comparación con la naturaleza, el detalle que tiene la forma real y cómo la computación (¡tan solo visual!) de su homólogo virtual puede llegar a ser impracticable.

Thursday, December 25, 2008

Un cojín

Dejo por aquí una primera prueba de un cojín. El cojín está modelado a mano. Sinceramente hubiera estado bien haber tenido algún programa de simulación física para realizar este tipo de modelos, pero por ahora a mano.

Para el efecto de iluminación he usado una BRDF de Minnaert. Esta BRDF se caracteriza por aumentar la reflectancia en ángulos alejados a la normal, justo al contrario de la Lambertiana.

Se pueden conseguir efectos similares al terciopelo. Os paso un pequeño render.

Tuesday, December 23, 2008

Fractal Flame

Hoy he decidido revisar un módulo de fractales en C++ que empecé hace tiempo y lo he dejado bastante olvidado. Modificando ligeramente una función que calcula un fractal de tipo IFS se pueden conseguir curiosos efectos. Si se realizan principalmente dos transformaciones: Una espacial y otra de ajuste de tono, se pueden conseguir un tipo de fractales denominados Fractal Flames (creados originalmente por Scott Draves).
Este es el resultado de un programa que se puede desarrollar fácilmente (de media a una hora) para representar Fractal Flames.


Obviamente, mejorando la paleta de colores (el ejemplo tiene dos colores) se pueden llegar a obtener mejores resultados.
Si realmente os interesa explorar el mundo fractal de los IFS os recomiendo el software Apophysis. Para finalizar, os dejo un IFS bastante clásico, el del helecho.

Monday, December 22, 2008

Simulación de PinArt

El otro día me acordé de aquellos juguetes con los que podías hacer una réplica de un objeto con agujas. Podéis echarle un vistazo a lo que me refiero aquí. Después de verlo me dije, por qué no hacer algo similar en 3D. Y aquí está.


Para realizar esta imagen tuve que hacer lo siguiente. Se parte de un modelo 3D. Este se puede hacer desde cero o se puede utilizar un modelo ya prehecho de Daz3D y darle una pose utilizando Poser.

Una vez que se tiene el modelo 3D, como una malla tridimensional es necesario transformarla a un objeto del estilo PinArt. Para ello es necesario crear en 3D las agujas. Esto se puede realizar con casi cualquier programa de modelado 3D.

Ahora hay que dar una cierta altura a las agujas con respecto la información de altura del modelo. Aquí hay dos maneras de atacar el problema, a mano y a máquina. Se puede tomar un programa de modelado 3D e ir ajustando las alturas de los pines uno a uno. O como elegí yo, se puede codificar un pequeño programa que determina la altura del modelo para una posición dada. Esta elección es la correcta si se desean realizar renders de otros modelos 3D. Aparte, teniendo en cuenta el número de agujas, te puedes pegar un buen rato moviéndolas de arriba a abajo. Hay que tener en cuenta que el programa que calcula las alturas de las agujas debe componer un nuevo objeto para exportarlo.

Para realizar el render he utilizado un programa de iluminación global codificado en C++. Se pueden usar programas comerciales o gratuitos como Indigo, o en mi caso, uno de fabricación propia.