Planeta Codepixel

20 de March, 2010

Divagaciones sobre game programming

Un 56% tiene Dx10

Leo en esta anotación que según una encuesta de Steam, el 56.5% de los usuarios ya tienen sistemas compatibles con DirectX 10/11. Dicho así, parece mucho, pero si también decimos que un 43.5% de los jugadores no tiene Dx10 aún,  pues también me parece una respetable cantidad de usuarios que no comprarán nuestro juego si solo se vende con un renderer basado en Dx10.
No dudo que esto se solucione a corto plazo, cuando Windows 7 demuestre que es un buen sucesor de XP y más jugadores migren a esta nueva plataforma, justificando el desarrollo de juegos que requieran Dx10/11.

by roger (noreply@blogger.com) at 20 de March, 2010 05:03 PM

19 de March, 2010

Divagaciones sobre game programming

Empezar en la industria del videojuego

En Vidaextra han publicado un breve resumen de una conferencia que duró nada menos que seis horas. Consejos de gente importante de la industria, que no está de más leer y tener como referencia obligada para los que quieren (o mejor dicho, queremos, porque yo también me incluyo) meterse en el negocio de los juegos. La primera parte aquí y la segunda aquí.

by roger (noreply@blogger.com) at 19 de March, 2010 06:15 PM

Normal mapping!

Ya funciona el normal mapping! El shader en cuestión es éste, y lo que me tuvo a punto de asesinar a alguien ayer (para que después no digan que los videjuegos no incitan a la violencia) fue el segundo mapa normal.El primero, que es el que ven en la imagen, es gris y con puntos. El segundo es más rojizo y no tenía el punteado que le da ese efecto de relieve, o tal vez sea el color.  El caso es que a pesar de la resaca que tengo justo ahora, se me ocurrió probar a cambiar de textura y ver qué pasaba.
Es la primera vez que pruebo el método y tengo que reconocer que el cambio es increíble, aún cuando hay algoritmos más avanzados, como el parallax mapping. Que dicho sea de paso, también está soportado por Ogre, la cosa es encontrar el shader adecuado. Los ejemplos incluyen un shader de offset parallax mapping, que es el más primitivo, si no recuerdo mal el más avanzado es occlusion parallax mapping. Por favor que alguien me corrija si ando desencaminado.

by roger (noreply@blogger.com) at 19 de March, 2010 12:48 PM

17 de March, 2010

Divagaciones sobre game programming

Nuevo edificio

Hoy recibí una versión preliminar del edificio, incluyendo texturas. El primer modelo tuvo que ser desechado porque algunas cosas no funcionaban, éste que ven aquí es el segundo intento, que incluye textura y mapa normal. Me parece que no se ve mal, a pesar de que faltan detalles por agregar como las puertas y ventanas.
Aún o he podido probarlo en Ogre, aunque exporta bien, porque el exporter de Blender me genera referencias a shaders que dan error, a pesar de que están incluidos en el proyecto. Realmente esto fue algo que no me esperaba, que el exporter identificara la segunda textura como un mapa y me generara los materiales adecuados para usar bump mapping. Como mencioné anteriormente, el objetivo era usar normal map, pero requiere modificar el material a mano. Si esta vía genera el material apto para el uso, supongo que será mejor dejarla como está, aunque el método no sea tan avanzado.

by roger (noreply@blogger.com) at 17 de March, 2010 02:59 PM

10 de March, 2010

Tutfanzine

IOQuake

Os dejo un video del Quake 3 multiplayer sobre un Nokia 900. Me llegó un email de un compañero para que le echara un vistazo un engine compatible con Quake3 Arena. E investigando encontré este video que quiero compartir con vosotros



Para los que quieran informarse mas,

http://ioquake3.org/
http://wiki.ioquake3.org/

by Toni Rodriguez (noreply@blogger.com) at 10 de March, 2010 03:04 PM

07 de March, 2010

Tutfanzine

Trabajo en grupo en entornos virtuales

Últimament no publico mucho debido a que he comenzado Grado Multimedia en la UOC.

En una de las asignaturas, Trabajo en grupo en red, se debate sobre las herramientas TIC para trabajar en grupo en cualquier proyecto, por ejemplo en la creación de un juego.

Que diferencias hay en trabajar entornos virtuales y entornos presenciales ? Que pasa si uno de los miembros deja el proyecto ? ... y así varias preguntas sobre la diferencia, ventajas y desventajas de trabajo en entornos virtuales o presenciales.

Muchos de mis compañeros, a los que me sumo, defendemos que aunque son diferentes maneras de trabajo, el que el proyecto llegue a buen fin, depende de otras variables ( motivación, responsabilidad, seriedad de los componentes, ... ) que afectan por igual a los dos modos de trabajo.

Yo añadí que es posible la combinación de las dos. Se puede trabajar el día a día en un entorno virtual, y cada X tiempo hacer reuniones presenciales para valorar el estado del proyecto si es posible, por ejemplo. Además añadí una variable que muchos descuidaron, el dinero. Y es que éste puede decantar la balanza hacia una manera de trabajar u otra. También añadí que hay muchas herramientas virtuales que facilitan las reuniones por multi-videoconferencia que se asemejan mucho a las presenciales.

Además en una de las actividades, nos indican que debemos compartir en delicious.com dos enlaces interesantes al respecto, yo dejé dos ( Tecnologíapyme y Noticias TIC en empresas ) que podéis encontrar en la siguiente dirección:

http://delicious.com/tonelorc

Pues nada, seguro que de los que visitáis el bloc tendréis experiencia en el trabajo en grupo y vuestra propia opinión. Espero vuestros comentarios para echarme una mano al respecto y poderlo plasmar en la práctica.

by Toni Rodriguez (noreply@blogger.com) at 07 de March, 2010 10:26 AM

03 de March, 2010

Soledad Penades

Seen, gone.

Seen, gone.” is my first (serious) incursion in Android development. Yeah!

As the description says:

Take a picture, watch it morph into something different – yet related to its true origin. And before you can blink twice, it’s gone, destroyed by the very same hands that created it.

To escape from the usual demoscene non-interactive demonstrations, I decided to do something interactive but that still used a bit of processor power, so that I could see what could the platform do. I had already tried to do some audio stuff, but the results were a bit disastrous. I might come back to that field again; maybe I will be more inspired or I will know how to do things ‘the proper way’ and it will end up being a more satisfying experience.

For this, I began using Canvas and only integer math to speed things up but the results were horrible; using Canvas for this was just too much and there weren’t available cycles for anything else. It was unacceptably jerky. I even showed the app to my favourite betatester and he told me that he would uninstall the application immediately.

Since I was determined to improve things, I watched the mighty session by Chris Pruett at past year’s Google IO and understood why things weren’t quite working the way I expected them to do. After much cursing myself for not having watched the presentation before, I replaced Canvas with OpenGL ES –in which I still miss good old immediate mode, but hey… it’s way faster!– and float calculations (to my surprise, you can even afford a few float operations!), plus reorganized pretty much everything, and rewrote the rest. Core calculations could probably be optimized with native C code but I didn’t want to limit myself to non-portable code yet. Although… are there any Android devices which are not ARM based? Heh!

It’s been a very instructive experience; I’ve learnt a lot doing this –the Garbage Collector and I have become almost close friends, so to say– and obviously it will help me to create more Android applications in the future.

But in the meantime, there’s another demo waiting to be finished!

And yes, this app is what I wanted to finish a couple of days ago, just in case you missed that post.

by sole at 03 de March, 2010 11:29 PM

Rubén Penalva's blog

Test: CUDA Volume Raycasting

Click here to view the embedded video.

Features

  • CUDA based application showing gpu volume raycasting using single pass Stegmaier et al. technique.

Downloads

Report

The cuda raycasting implementation is the same approach as the Stegmaier one but with some minor changes and simplifications:

  • CUDA kernel
  • The volume is a cube: width, height and depth are all the same.
  • Proxy geometry (the six quads or the cube) is normalized and translated so the center its the same as the center of the scene.

The intersection code is really unoptimized. It’s just a straightforward implementation of the intersection ray-aabox function shown in “Real time collision detection” by Christer Ericson. I would suggest you to see the implementation of this function within the nvidia sdk volume render sample .

Controls

  • Left click plus mouse movement to rotate the camera around the volume.
  • Right click to show the context menu.
  • Middle click plus vertical movement to increase/decrease the density window width.
  • Middle click plus horizontal movement to move right/left the density window.

Technology

  • C++
  • Opengl 2.1
  • CUDA
  • Glut for Win32
  • Glew
  • Microsoft Visual Studio 2008 Professional Edition
  • Subversion
  • Redmine

Develop/Build/Test Machine Specs

  • Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz
  • 3072 Mb RAM
  • Nvidia GeForce GTX 260
  • Nvidia Driver Version: 196.21 WHQL
  • Microsoft Windows 7 Professional x64

Resources

by Ruben Penalva at 03 de March, 2010 12:02 AM

27 de February, 2010

Interface

Perdidos en Cooperalia

Hace tiempo que no doy noticias. La verdad es que este comienzo de año ha sido bastante estresante, llegando a solapar tres proyectos a la vez (además de mi trabajo de 8 horas en Bren). Poco a poco estos proyectos se van finalizando, y empiezo a ver la luz al final del túnel.Uno de estos proyecto (Leer resto de la noticia | read full post)

27 de February, 2010 10:21 PM

20 de February, 2010

Tutfanzine

Importar ficheros 3ds a 3D Game Studio 7

Os muestro un pequeño video, que aunque parece sencillo, os puede facilitar la importación de ficheros .3ds creados con cualquier editor 3d ( en el ejemplo 3d Studio Max ), indicando que opciones hay que marcar cuando creamos el .3ds para que después sea importado correctamente:



Eh aquí el enlace: http://www.youtube.com/watch?v=82NUf1Vr0i8

Son pequeñas cosillas que pueden hacer que no tengamos que estar toda una tarde averiguando porque no se importa bien un fichero.

by Toni Rodriguez (noreply@blogger.com) at 20 de February, 2010 09:27 AM

3D Game Studio - Impresiones (1)

Bien, por donde empiezo ? No es bueno empezar un post con una pregunta, pero es que mi primer contacto con 3D Game Studio ha sido un poco por entregas. No he podido dedicarme 2-3 horas seguidas. Es por eso que dejaré mi opinión para los posteriores post.

Por lo pronto, os diré que visité la web oficial y me descargué la versión gratuita. Cuando la instaléis, podréis ver que se crean varios accesos directos en el menú. Cada uno de ellos ejecuta uno de los programas necesarios para crear el juego, a saber:

WED
Editor de niveles

MED
Editor de modelos y terrenos

SED
Editor de script y compilador

Lite-c
Es el lenguaje de script utilizado

Mi objetivo inicial ha sido muy sencillo. A partir de los ejemplos que facilitan, los cuales he compilado y probado para ver las posibilidades, he creado mi propio script e investigado un poco como funciona todo.

Qué es lo primero que quiero hacer ?
No iremos a por el tejado de un inicio. Por lo pronto, cargar una 'entidad animada' y que se mueva a partir del teclado.

Con MED he abierto uno de los modelos que proporcionan, un guerrero en formato .mdl, y viendo las propiedades del mismo he podido comprobar que está compuesto por varias animaciones "stand" "jump" "run" ...

Una vez he visto como está formado el modelo .mdl, he creado el script con el siguiente código para crear la entidad y asignarle una función que trata los eventos de teclado para que el guerrero actue.

#include
#include
#include
#define PRAGMA_PATH "EXE_DIR//include"

function animation_test()
{
my.pan = -150; // face the player
var walk_speed = 0;
var turn_speed = 0;
while(1)
{
ent_animate(my, NULL, 0, 0); // reset all the animations
walk_speed += 3 * time_step; // increase walk_speed; 3 sets the speed
ent_animate(my, "stand", walk_speed, ANM_CYCLE);
if (key_w) // Si la tecla es w
ent_animate(my, "run", walk_speed, ANM_CYCLE);
if (key_s) // Si la tecla es s
ent_animate(my, "stand", walk_speed, ANM_CYCLE);
if ( key_space ) // Si la tecla es la barra espaciadora
ent_animate(my, "attack", walk_speed, ANM_CYCLE);
if ( key_e ) // Si la tecla es la e
ent_animate(my, "jump", walk_speed, ANM_CYCLE);
wait(1);
}
}

int main()
{
level_load(""); // Carga un nivel vacío
ent_create("terran.mdl", vector(400, 0, -50), animation_test); // Carga la entidad animada y le asigna el manejador de eventos animation_test que definimos arriba
}

Creo que no es necesario que explique mucho el código. Abajo os dejo los enlaces de los tutoriales y manuales.

Cosillas
Como es la versión de prueba, el resultado contiene logos en la parte superior derecha. A mi no me molesta porque mi objetivo es echarle un vistazo.

Como todo lenguaje de script, no se puede esperar el mismo rendimiento que si se programa en C++. Pero lógicamente es mas rápido de aprender y ver resultados.

Referencia
Tutoriales Lite-C
Manual 3d Game Studio

by Toni Rodriguez (noreply@blogger.com) at 20 de February, 2010 09:21 AM

19 de February, 2010

Soledad Penades

Breakpoint demolog, day 17: building for windows (from linux)

Windows and Linux executables, rotating a triangle and generating a sine wave audio stream

Today I decided to do something different. And I thought: Okay, I’ll try and sort out this compiling for windows issue, so that I can focus on the rest of more important things without having to worry about it any more.

And guess what…? I think I managed to do it :-)

Roughly, these are the steps I followed, just in case someone else wants to compile for windows with opengl and sdl support, using [ubuntu] linux:

  • install mingw (I did it with Synaptic Package Manager so that I didn’t have to go through the ./configure and ./make hell)
  • get the dev libraries from sdl for windows/mingw –this file– or check their downloads page
  • uncompress the file and locate the bin, include and lib folders within, and…
    • copy bin/SDL.dll to the folder where your win32 .exe will go — so that the exe can pick and load the dll when executing
    • copy the include and lib folders to a folder in your project’s src folder — or anywhere you’ve got access to! For example: project/src/libs/sdl/
  • now in your main.cpp, include SDL’s header files like this:
    #include <SDL/SDL.h>
    #include <SDL/SDL_opengl.h>
  • And the makefile could be something like this too:
    WINDOWS_SDL = ./libs/sdl/windows

    windows:
            i586-mingw32msvc-g++ -I$(WINDOWS_SDL)/include -L$(WINDOWS_SDL) \
    main.cpp $(WINDOWS_SDL)/libSDL.dll.a -o ../test.exe\
     -lmingw32 -lSDLmain -lSDL -mwindows -lopengl32 -Wl,-R.

(ugly hard line returns added by me so that you can see all parameters in one go).

This assumes you are invoking make from the src folder. The output will go to the parent folder. But well, the most important things that need to be highlighted are the bunch of switches you need to include in order to get the program to link:

-I$(WINDOWS_SDL)/include — this tells the compiler where to look for additional header files. This way it can find <SDL/SDL.h> and you do not need to modify the file or add #define’s when building for linux.

-L$(WINDOWS_SDL) — pretty much the same but tells the compiler to look for static libraries in the WINDOWS_SDL folder too

$(WINDOWS_SDL)/libSDL.dll.a — links the library into our binary!

-lmingw32 -lSDLmain -lSDL -mwindows -lopengl32 -Wl,-R. — these are magic – remove any of them and the linker will complain about missing symbols ;)

I still have to test this in a real windows machine; so far I have just tried with Wine. The output is a little jerky and a bit slower than the native (64 bit) counterpart, but I guess this will do much better than compiling in Virtual Box and testing with Wine :D

I’ll try to upload a test .exe when I test it on a real windows box myself, so that you can test it and see if it works in your computer (if you want, of course!). It’s ages since I compiled anything for win, and I truly wonder whether it will work with Vista/7… my last demo for Windows was done in 2005 and XP was in full glory back then :P

by sole at 19 de February, 2010 12:38 AM

09 de February, 2010

Rubén Penalva's blog

Test: GPU Volume Raycasting

Click here to view the embedded video.

Features

  • Opengl based application showing gpu volume raycasting using single pass Stegmaier et al. technique.

Downloads

Report

The gpu raycasting implementation is the same approach as the Stegmaier one but with some minor changes and simplifications:

  • GLSL shaders
  • The volume is a cube: width, height and depth are all the same.
  • Proxy geometry (the six quads or the cube) is normalized and translated so the center its the same as the center of the scene.

Controls

  • Left click plus mouse movement to rotate the camera around the volume.
  • Right click to show the context menu.
  • Middle click plus vertical movement to increase/decrease the density window width.
  • Middle click plus horizontal movement to move right/left the density window.

Technology

  • C++
  • Opengl 2.1
  • GLSL
  • Glut for Win32
  • Glew
  • Microsoft Visual Studio 2008 Professional Edition
  • Subversion
  • Redmine

Develop/Build/Test Machine Specs

  • Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz
  • 3072 Mb RAM
  • Nvidia GeForce GTX 260
  • Nvidia Driver Version: 196.21 WHQL
  • Microsoft Windows 7 Professional x64

Resources

by Ruben Penalva at 09 de February, 2010 09:45 PM

Soledad Penades

Breakpoint demolog, days 1-7

So the quest is set, the aim is clear: create something for Breakpoint 2010. There won’t be another opportunity; not at least under the Breakpoint umbrella.

The organizers have expressed publicly they don’t wish to organize yet another edition of nowadays biggest demoscene event, so it’s now or never! (At least until a new event this good takes off).

I already have had stuff of mine shown in their big screen. But that was before the true Big Screen, with capital letters. The 70 square meters one. I must release something, I said to myself.

Of course, this means that in a way, I’m going to break my own self-imposed rule (I will release things when they are done), but I’m working in a slightly pressurised scenario in order to finish the demo before setting off for the airport.

I have decided to keep a somewhat sporadic short demolog to keep people informed of what I’m doing, trace’s style. Hopefully it will help/force me to do things, daily, so that I don’t slack or procrastinate, and maybe you may help me too when/if I get stuck somewhere ;)

I’ll keep things short –this is probably going to be the longest post in the series– so that writing here doesn’t starve me of time to code.

This is the current status of the project:

  • the theme is approximately set, but I won’t disclose it here
  • I’m working on converting my on-its-own rudimentary OO-C synth (sorollet) to a bit less rudimentary C++ synth that can be embedded and interfaced, VSTi style, so that I can sequence everything from Renoise and play with parameters and settings in real time…
  • … and convert Renoise’s Song.xml (inside the .xrns file) to my own data file — kind of means recreating a simple tracker which follows Renoise conventions (Lines Per Beat for example). I have taken a look at the Song.xml file, extracting and using the relevant data seems easy, specially since Sorollet was already using a tracker style format.
  • So far I have managed to compile a VST plug-in in Linux. I had to solve several issues like having to compile for 32 bit while using a 64 bit OS, because Renoise is 32 bit too, gdb not willing to cooperate most of the times, the VST SDK docs being scarce and incomplete and not ready for Linux and etc, but I’m slowly progressing. Now I have a basic synth that can play sines or triangles, and transpose octaves. Awesomeness!
  • This means I’m not using an mp3 this time. Could this fit into an intro? Maybe, but I don’t want to sacrifice code readability in order to make it fit into an intro… I’ll be more than content with making a demo!
  • I need to find a way of producing a working Windows executable. Sadly, party organisers won’t allow a non-Windows .exe to enter the demo compo. Big BOOOOOOH for them. I have thought of different solutions, the easier is to install mingw in a VirtualBoxed Windows I’ve got, recompile my sources there and run the exe in my main machine, using wine. But I still have to try that, and I hope it works in Windows Vista :-S
  • I still haven’t thought about the visual part, I fear I’ll have to script it as in ye olde times –no time for writing a visual timeline manager–, but I will probably use Lua to alleviate the pain.

Complimentary screenshot:

Sorollet VST

More later.

by sole at 09 de February, 2010 12:11 PM

06 de February, 2010

Jesús de santos

Code Bloat Hunting

I have dedicated the last few days of work to face a problem that is getting bigger and bigger. Although we have a quite modular codebase, use interfaces whenever possible to hide implementation...

by ent at 06 de February, 2010 12:39 AM

04 de February, 2010

El laboratorio del Dr. Txap

Tuber’s Two Step de Chris Wedge

A pesar de haber impartido un par de veces una ponencia sobre la historia de los gráficos por ordenador en el cine, uno debe ser humilde y reconocer que es imposible saberlo todo sobre un tema; siempre se queda algo en el tintero, y cuando menos te lo esperas aparece uno de los blogs amigos a enseñarte algo nuevo.

En este caso, nuestro contrabandista de Moonfleet preferido nos muestra el primer corto animado de Chris Wedge. Se llama Tuber’s Two Step y es de 1985.

Para situarnos en contexto, por aquellos años Pixar se estaba formando como tal y, aunque bajo el ala de George Lucas ya habían sacado André and Wally B. (1984), aún faltaba un año para que sacaran su primer corto como empresa independiente: Luxo Jr.

Chris Wedge se empezó a dar a conocer en el mundo de los gráficos muchos años más tarde, cuando ganó el Oscar al mejor corto animado por Bunny en 1998. Este corto sí lo incluí en la historia de la animación por ordenador por sus avances en el renderizado del pelo de los animales, algo que Pixar no había conseguido ni en Toy Story ni en Bichos. Más tarde Wedge aprovecharía esta técnica en los animales que creó para su primer largo hecho con su propia compañía: Ice Age (2002).

Les dejo con el corto, que no aporta gran cosa más que su valor histórico:

by Txapulín at 04 de February, 2010 02:25 PM

03 de February, 2010

Interface

Run with the Wolves

Hola, cuanto tiempo!Os invito a disfrutar de un video musical que han hecho ex-compañeros de Dygra, para un concurso de The Prodigy. Estupenda realización, estilo y narrativa, va como un guante al video. Y con final sorpresa!  Votad! :) (Leer resto de la noticia | read full post)

03 de February, 2010 02:41 AM

11 de January, 2010

El laboratorio del Dr. Txap

The Third and the Seventh

Alex Roman es un artista que se ha tomado un par de años sabáticos y en este tiempo ha hecho un corto alucinante. Véanlo primero, y luego comento algunas cosas.

The Third & The Seventh from Alex Roman on Vimeo.

Hasta el minuto 6 ó 7, cuando empiezan a aparecer las esferas de agua y los pétalos al viento, estuve convencido que estaba filmado (real-life footage le llaman en english). Incluso después pensé que estos trucos estaban hechos con una excelente composición. Eso me pasa por mirar el video antes de leer sobre él (lo cual no es malo, por cierto). Fue luego que leí la entrevista que le hacen al artista en dimensión 2.5. Lo más impresionante es que ¡es todo cg! Lo ha hecho con 3D Studio Max y VRay (y otros programas para la postproducción).

Dice en la entrevista que todavía está en paro. No creo que sea por mucho tiempo, porque ya he visto este video correr por varios foros en inglés.

by Txapulín at 11 de January, 2010 02:43 PM

08 de January, 2010

Interface

Nieve en Santiago!

El dolor del madrugón para ir a trabajar se ha visto agradablemente recompensado:No me refiero a mi transformación a Power Ranger -esto es habitual- sino a que ha caido una intensa nevada por la noche, algo totalmente inusual por estos lares. Más foticos: Puede verse un video en youtube montado p (Leer resto de la noticia | read full post)

08 de January, 2010 08:27 PM

03 de January, 2010

Strawberry Iq

31 de December, 2009

Interface

Raytracing en Python

En noviembre, en esos huecos y tiempos muertos de 5-10 minutos que surgen en el dia a día, me entretuve programando un raytracer en Python. Motivos: 1. Reaprender python 2. No se necesita un motivo para hacer un raytracer! El código es muy chapucero. Hice lo mínimo para conseguir lo que quería, (Leer resto de la noticia | read full post)

31 de December, 2009 07:31 PM

30 de December, 2009

Strawberry Iq

26 de December, 2009

El hombre alto

On C++ performance: The Evil Mr. Branch

Here's a simple problem . For some reason, you've got to select between two types or values: smaller (or equal) than 50, and bigger than 50. And you need to do that fast using one core (no multithreading). ¿How do you do it?

For our example, we'll have an array called data where all values are stored, and an array called results, where an integer value is stored, indicating if the input was bigger or smaller than 50.

So, this is the straighfoward way to do it.
for(int i=0;i<NUM_DATA;++i)
{
    if(data[i] <= 50)
        results[i] = SMALLERTHAN_50;
    else
        results[i] = BIGGERTHAN_50;
}
And most of us (and myself 2 days ago) would say: "you won't get much faster than that!". Well, in fact you can. How?

By not branching!

In school they show you that branching can make the processor flush the data it has in the pipeline and start over. They also tell you that today's general-purpose processors do not generally take a big hit when branching, but that hit still exists (I'm talking x86 PCs, here. Consoles DO have serious problems with branching).

So, how do you do this without branching? With a small trick ;-)

result = x + (y-x) & condition

If condition has all bits to 0, the second half of the computation will be 0, so result ends up being x. On the other side, if condition has all bits to 1, the x cancels out, and we get result=y.

So we get a function like this (code shamelessly taken from here):
int isel( int a, int x, int y )
{
    int mask = a >> 31; // arithmetic shift right, splat out the sign bit
    return x + ((y - x) & mask); // mask is 0xFFFFFFFF if (a < 0) and 0x00 otherwise.
}
If a is positive, it returns x, if negative, returns y.

So using this function, we can get our array sorted out just like this:
for(int i=0;i<NUM_DATA;++i)
    results[i] = isel(50 - data[i], SMALLERTHAN_50, BIGGERTHAN_50); 
It works just as well... the only question is performance. What will run faster?

Well, in my machine (a Core 2 Duo at 2.4GHz), for NUM_DATA=10,000, and 200,000 iterations of those loops, I get:

- Using GCC with no optimizations:
Elapsed time BRANCHING:       19.156000000  sec
Elapsed time NOT BRANCHING:   17.566000000  sec
- Using GCC with -O3:
Elapsed time BRANCHING:       2.605000000  sec
Elapsed time NOT BRANCHING:   1.981000000  sec
The difference is not that big without optimizations, but with them, it's clear as day: not branching gets you further. More than a 20%, in this case!!

And this goes to show you what some people might already have told you: compilers inline the hell out of your code if set to high optimization values, even if you don't explicitly ask them to. This code is faster using a function call inside the main loop than without it!

By the way, GCC is NOT generating MMX, SSE, or any instructions like that. This is the disassembly for the main loop in the branchless version (the text on the right is my interpretation for the asm):

.text:00401170 loc_401170:
.text:00401170             mov     eax, ecx                  ## eax=50
.text:00401172             sub     eax, [ebx+edx*4]          ## eax-=data[i]
.text:00401175             shr     eax, 1Fh                  ## eax>>=31
.text:00401178             mov     [edi+edx*4], eax          ## result[i] = eax
.text:0040117B             inc     edx                       ## ++i
.text:0040117C             cmp     edx, 270Fh                ## if(i<NUM_DATA)
.text:00401182             jle     short loc_401170          ##    repeat loop

The process is heavily optimized by GCC, but it's all there in normal, honest-to-fsm, everyday-life instructions.

I do still have some doubts about this, however, as the GCC optimization for the branching loop doesn't use a j(n)le or jz instruction, but setnle. And I can't find out if this instruction does in fact flush the pipeline or not. Anyway, it still results in a faster processing when using the isel version.

For comparison, here's the optimized branching loop:
.text:004010F0 loc_4010F0:
.text:004010F0             xor     eax, eax
.text:004010F2             cmp     dword ptr [ebx+edx*4], 32h
.text:004010F6             setnle  al
.text:004010F9             mov     [esi+edx*4], eax
.text:004010FC             inc     edx
.text:004010FD             cmp     edx, 270Fh
.text:00401103             jle     short loc_4010F0
And, well, here's the whole testing code if anyone is curious about it:
#include <cstdlib>
#include <cstdio>
#include <ctime>

enum{ SMALLERTHAN_50, BIGGERTHAN_50};

int isel( int a, int x, int y )
{
    int mask = a >> 31; // arithmetic shift right, splat out the sign bit
    return x + ((y - x) & mask); // mask is 0xFFFFFFFF if (a < 0) and 0x00 otherwise.
}

int main ()
{
    const int NUM_DATA = 10000;
    const size_t NUM_ITERS = 200000;

    clock_t startTime, endTime;

    int * data     = new int[NUM_DATA];
    int * results  = new int[NUM_DATA];
    int * results2 = new int[NUM_DATA];
    
    // Initialize test data
    for(int i=0;i<NUM_DATA;++i)
        data[i]= rand()%100; 

    startTime = clock();
    // ------------------------------ 
    // Branch test
    for (int j=0;j<NUM_ITERS;++j)
        for(int i=0;i<NUM_DATA;++i)
        {
            if(data[i] <= 50)
                results[i] = SMALLERTHAN_50;
            else
                results[i] = BIGGERTHAN_50;
        }
    // ------------------------------ 
    endTime = clock();

    printf ("\tElapsed time BRANCHING:       %.9f  sec\n", 
        (float)(endTime-startTime) / CLOCKS_PER_SEC);
    
    startTime = clock();
    // ------------------------------ 
    // Branchless test
    for (int j=0;j<NUM_ITERS;++j)
        for(int i=0;i<NUM_DATA;++i)
            results2[i] = isel(
                50 - data[i], 
                SMALLERTHAN_50, 
                BIGGERTHAN_50);                                                                                   
    // ------------------------------ 
    endTime = clock();
 
    printf ("\tElapsed time NOT BRANCHING:   %.9f  sec\n",
        (float)(endTime-startTime) / CLOCKS_PER_SEC);

    // Check we didn't mess things up 
    for(int i=0;i<NUM_DATA;++i)
        if( results[i] != results2[i])
            printf ("ERROR in elem %i=%i, first value: %i, second value: %i\n",
                i, data[i], results[i], results2[i]);
}                                          

by Jon Valdés Furriel at 26 de December, 2009 08:54 AM

Strawberry Iq

21 de December, 2009

El hombre alto

C++: Could you please code cleanly? Pretty please?

One of my little things when coding is that I always feel ashamed when my code is not clean. This means I try very hard to make my code simple and easy to understand. I don't always succeed (not even close), but I try.

I wasn't always like that, mind you. As a teenager, my code was just a horrible mess of spaghetti code. But Pablo Orduña showed me long ago the value of easily understandable code, and since then I always try my best to code in a clear and non-hackish way.

Anyway, these days I've found myself working with code from other people. And, at that, people that didn't try to create readable code. I'm sure they did know how to do it. They just weren't in the mood. You can just read it in the code: "if it works, ship it!"

As a small example (there are much much worse things than this), here's a slightly modified version of a function I found the other day:
bool RetrieveProperty(object_t * object, string propName, VARIANT* pPropertyValue)
{
	PropertyReader * pPropertyReader = NULL;
	object->FromInterface(IID_IPropertyReader, (void**)&pPropertyReader);
	if (pPropertyReader)
	{
		Properties * pProperties = NULL;
		pPropertyReader->get_Properties(&pProperties);
		if (pProperties)
		{
			long propCount = 0;
			if (pProperties->get_Count(&propCount) == OK)
			{
				for (long i = 0; i < propCount; i++)
				{
					Property * pProperty = NULL;
					pProperties->get_Item(i, &pProperty);
					if (pProperty)
					{
						PropertyDictionary * pPropertyDictionary = NULL;
						pProperty->FromInterface(IID_PropertyDictionary, (void**)&pPropertyDictionary);
						if (pPropertyDictionary)
						{
							string bDictionaryName;
							pPropertyDictionary->get_Name(&bDictionaryName);
							
							if (!strcmp((char*)bDictionaryName.c_str(), "MY_DICTIONARY"))
							{
								HRESULT hr;
								if ((hr = pPropertyDictionary->get_Item(PropertyName, pPropertyValue)) == OK)
									return true;					
							}
						}
					}
				}
			}
		}
	}

	return false;
}
Now, did anyone notice something odd? The nested ifs and loops? They make it unnecessarily hard to follow the program flow and they don't buy us anything in return!

In fact,the whole structure of the function allows us to remove most of the 9 (yes, 9) indentation levels in that code. We just have to reverse the ifs and return early. Like this:
bool RetrieveProperty(object_t * object, string propName, VARIANT* pPropertyValue)
{
	PropertyReader * pPropertyReader = NULL;
	object->FromInterface( IID_IPropertyReader, (void**)&pPropertyReader);
	if (!pPropertyReader)
		return false;

	Properties * pProperties = NULL;
	pPropertyReader->get_Properties(&pProperties);
	if (!pProperties)
		return false;

	long propCount = 0;
	if (pProperties->get_Count(&propCount) != OK)
		return false;
		
	for (long i = 0; i < propCount; i++)
	{
		Property * pProperty = NULL;
		pProperties->get_Item(i, &pProperty);
		if (!pProperty)
			continue;
		
		PropertyDictionary * pPropertyDictionary = NULL;
		pProperty->FromInterface(IID_PropertyDictionary, (void**)&pPropertyDictionary);
		if (!pPropertyDictionary)
			continue;
	
		string bDictionaryName;
		pPropertyDictionary->get_Name(&bDictionaryName);
	
		if (strcmp((char*)bDictionaryName.c_str(), "MY_DICTIONARY"))
			continue;

 		HRESULT hr; // why do we need this, I say?
		if (hr = pPropertyDictionary->get_Item(PropertyName, pPropertyValue) == OK)
			return true;					
	}

	return false;
}
Max indentation: 3 levels.

It takes less than a minute, it's safe to do, the meaning of the program is exactly the same... and it's much cleaner and easy to understand! And as a bonus, it isn't even longer than the previous version!!

There are even clever people that have said this before me several times!

So please, do try. I know it seems easier and faster not to, but it's only in the short run. Some day (when you have to go back to try to understand your own code) you'll regret it.

Still unconvinced? Now try imagining this with 700 loc functions (and yes, I have a few like that one here...)

by Jon Valdés Furriel at 21 de December, 2009 01:50 PM

19 de December, 2009

Orangemachine

PFM – Burning and Crumpling Paper – Difusión del Calor


Hola planet!

HeatSolver2D Demo

HeatSolver2D Demo

Después de un periodo de vacaciones y trabajos varios he retomado el proyecto.

He terminado unas tareas que tenía pendientes referentes a la difusión del calor en 2D.

La representación del papel es un sistema masa-muelle. Este proceso irá quemando los nodos y los muelles conectados se irán contrayendo para simular las arrugas del papel.

De momento solo tengo el proceso de difusión y una deformación simple, reduciendo los muelles un epsilon. Aunque está lejos del resultado final, tiene pinta de que vamos por el buen camino :) y motiva a seguir trabajando y compartiendo ideas.

También he creado una sección para ir colgando material relacionado con el proyecto.

Seguimos en contacto!

by Pablo Quesada Barriuso at 19 de December, 2009 03:24 PM

18 de December, 2009

El laboratorio del Dr. Txap

Alma de Rodrigo Blaas

Otra de las maravillas que pude ver en el festival de animación del SIGGRAPH.

Alma from Rodrigo Blaas on Vimeo.

Vía cg-node.

by Txapulín at 18 de December, 2009 11:38 AM

17 de December, 2009

Strawberry Iq

22 de November, 2009

El hombre alto

New job!

Tomorrow monday is officially my first day working for RandomControl as the fryrender plugins subsystem developer and maintainer.

By the way, I'll be telecommuting from home, so I'll avoid cubicle-work once again (yay!)

And, well, I hope this job leaves me some time (and it doesn't eliminate my coding-mood) so I can keep on posting some weird stuff here!

And now, I'm going to bed. Gotta get up early to go to the office tomorrow in the morning :-P

by Jon Valdés Furriel at 22 de November, 2009 10:53 PM

18 de November, 2009

El hombre alto

Voronoi video-filling

After showing the last test to a colleague, he guessed that this method would look really bad if seen in motion, using a random sampling method for the image. He thought that a constant sampling pattern would be needed... and so I had to test it out.

This is the result, using a video sample from a Fringe episode. I think it's not half-bad when you get past 1000-2000 samples in the image. And it's completely real-time! :-)

by Jon Valdés Furriel at 18 de November, 2009 10:51 AM

12 de November, 2009

El laboratorio del Dr. Txap

Pigeon: Impossible

Éste lo vi en el festival de animación del SIGGRAPH. Es bueno que vayan apareciendo…

Gràcies, Ignasi.

by Txapulín at 12 de November, 2009 03:23 PM

20 de October, 2009

Gyakoo

Something about security

Exploiting of systems is a subject of which I'd like to know more about. I think it's good to understand how avoid future hacking, but really you neither find much information on web nor books related. I've found a book which maybe could help us to improve these skills. Topics in book include:
  • Program computers using C, assembly language, and shell scripts
  • Corrupt system memory to run arbitrary code using buffer overflows and format strings
  • Inspect processor registers and system memory with a debugger to gain a real understanding of what is happening
  • Outsmart common security measures like nonexecutable stacks and intrusion detection systems
  • Gain access to a remote server using port-binding or connect-back shellcode, and alter a server's logging behavior to hide your presence
  • Redirect network traffic, conceal open ports, and hijack TCP connections
  • Crack encrypted wireless traffic using the FMS attack, and speed up brute-force attacks using a password probability matrix


And related to that, in the video below, speakers Michael Stail and Felix Domke talk about The XBox 360 Security System and its Weaknesses. They first talk about all weaknesses in old Xbox I, and one by one they're going giving technical information about how they fixed them.

by gyakoo (noreply@blogger.com) at 20 de October, 2009 03:34 PM

17 de October, 2009

Gyakoo

Please, no more discussion about C vs C++

I'm really thinking that C vs C++ discussion will never end. I just read a Peter Seibel post about interviews he has written in his book Coders at Work, asking to fifteen top programmers and computer scientist around the world about what are their opinions in using C++ language.

Well, maybe you're going to be surprised since most of them think that C++ is a bad, too complex, useless language, and they prefer C when they need performance. That's what a couple of well considered programmers said.

Reading the post, I can see that they had that opinion mainly focusing in how the complex the C++ is. They said that sometimes programmers use only a subset of the language. They think that what you mostly need to do with an OO language, you best do it with some other like Java or Python, because they're better structured languages and things can be done in the same way by different programmers. They insist in the complexity of language and the different compiler implementations, which is a pain in compatibility issues.

Anyway, although I'm not by far as good programmer as they are (years of experience are talking here), I think they're old-school programmers, I mean, C++ has been changing along these years and already there exist another standard revision, as well as compilers do. In reference to the language complexity, all is about using it. If you're a Java experienced programmer and you want to program in C++ after a lot of years, it is obvious that C++ is very complex for you in the beginning. You'll get confused with OO artifacts (which is half-implemented in C++, it is true), or by the using of pointers and references.

C++ is a great language, as well as C and Java and others, depending on what you need to do. The google jam code contest is a good example about it. I've a good colleague that tried to resolve its exercises by using C++, but he said me that more rounds he passed more difficult the questions were, but difficult in the sense of he hadn't enough time to program the result algorithm, not by the algorithm's complexity itself. He was spending a lot of time with language (C++) to do simple tasks like word parsing, splitting a string ... I wonder if he had used python, I'm pretty sure he had obtained a better results.

A place where you can find a lot of C++ code is in the videogames industry, but anyway there is a common evolution there, the using of more high level scripting language, loosing a bit of performance but gaining flexibility and avoiding bugs. That evolution is focused also in tries to make an better script parallel language. And talking about parallelism, it is true that C++ might be a bit painful. That's because the lack of a memory model like Java has. But next language standard has done efforts in that field.

To summarize, my honest opinion about using C++ is that if you've got a couple of good programmers that understand well the language, and they're pragmatic, you could program a very good product (in the performance sense) by using C++, but even so there are parts of a system that is better program in another not-so-risky language. To make good use of the C++ you need good and experienced C++ programmers.

C++ is a dangerous language, like a knife is. But that has not made it so bad. All depend on who is using it and how he/she uses it. You don't let a child that plays with a knife, don't you?

by gyakoo (noreply@blogger.com) at 17 de October, 2009 06:15 PM

15 de October, 2009

Gyakoo

C++ or C (in this era?)

A post from The Endeavour blog about a Linus Torval's response in a forum, makes me remember the ethernal dilemma about OO and Procedural methodologies flamewar, C++ vs C, STL vs C, Java vs C, well whatever vs C...

Linus:
C++ is a horrible language. It's made more horrible by the fact that a lot
of substandard programmers use it, to the point where it's much much
easier to generate total and utter crap with it. Quite frankly, even if
the choice of C were to do *nothing* but keep the C++ programmers out,
that in itself would be a huge reason to use C.
...
John:
...
Well, I’m nowhere near as talented a programmer as Linus Torvalds, but I totally disagree with him. If it’s easy to generate crap in a relatively high-level and type-safe language like C++, then it must be child’s play to generate crap in C. It’s not fair to compare world-class C programmers like Torvalds and his peers to average C++ programmers. Either compare the best with the best or compare the average with the average.
...


John's impressions are clever and looks like more polite, against Linus's outspoken attitude but completely honest, but anyway after read a lot of controversial comments and what Stroustup said about his C++, finally I think that why do we have to chose one of them? Are always things black or white? I neither agree nor disagree with extreme positions ... people like discussions!

by gyakoo (noreply@blogger.com) at 15 de October, 2009 02:53 PM

Hacker's Delight

Since I read an article from EntBlog about this book, I pushed it in my pending books queue. And ... finally a good colleague at Optenet give it to me like a present. I'm really excited. Thank you dude.

Sure I'll learn a lot of interesting things.

by gyakoo (noreply@blogger.com) at 15 de October, 2009 02:16 PM

12 de October, 2009

Rubén Penalva's blog

New adventure in Cambridge

Well, after some time without updating the blog I’m giving some life signals. Sorry for the lack of updates but I’ve been super busy moving to Cambridge. Yes, I moved to Cambridge to work for ArtVPS as a software developer. I’m working with real time ray tracing renderers, which is really cool. The people here are great professionals and I’m very pleased to have the opportunity to work with them.  As you could imagine I have no time to do anything aside searching a flat and getting used to listen English the whole day. I left my machine in Madrid, so no tech demos in a couple of months. I have to figure out how the hell I’m going to bring all that (2 monitors, a big case, 7.1 speakers,…..) to Cambridge.

by Ruben Penalva at 12 de October, 2009 12:24 PM

06 de October, 2009

Shash Final Project Diary

Technical details of implementation

After the general ideas, I want to talk about the technical details of the project implementation. First of all, I'm mainly an OpenGL coder, I've been using the API for almost a decade now, so I'm quite used to it. Also I'm quite used to coding all the stuff that is rationally doable myself: 3D mesh exporters/importers, file formats, parsers, etc. As I see the final project as a learning exercise, I wanted to try something different.

First, I'll be using Direct3D 9 or 10: I'm not sure of the capabilities that Direct3D 9 offers, so maybe I'll have to use some stuff that is Direct3D 10 level. Whenever I can check of the full Direct3D 9 capabilities I'll know, I'm too used of working with OpenGL, where higher requirements don't mean changing the version of the API, just another extension.

For the 3D mesh/scene file format, I'll be using Collada. The reason is quite simple, it's got exporters already written from 3dsmax and Maya (the two applications I know best), it's plain XML (so I can write a parser, and in the process learn about the schema) and it's meant to be a industry standard (that's the least important reason, but seems plenty of people/companies are using it as exchange format between the 3D package, tools and final format).

As for the math and base code, I'll use modified (mainly simplified) versions of those that I use for my personal projects, as I won't be needing all the stuff I've coded over the years (or I hope so!).

Also, it's worth noting that I already started the project, in fact it was started 3 weeks ago! As of now, I've the first draft of the Collada loader, an a very simple Direct3D encapsulation. In the upcoming days, I'll be uploading screenshots if I do something worth posting, and will start detailing the four shading techniques that I'll implement.

by shash (noreply@blogger.com) at 06 de October, 2009 06:27 PM

01 de October, 2009

Neurogence

An AI's application in my daily work?

Well, last months we've here a big problem about our daily technical work. As you possibly already know (if you read my another blog), I'm working in a big system which automatizes all our Software Quality Assurance (SQA) procedures and test cases for our (complex, have to say) products.We always have a issue related with interface's dependent test cases. Basically, they're scripts that perform

by gyakoo (noreply@blogger.com) at 01 de October, 2009 06:00 PM

23 de September, 2009

Shash Final Project Diary

Initial ideas

Well, as part of my final project at the university, I wanted to make a diary with plenty of screenshots and as a mean to see how much the finished project changed from the initial ideas. Let's get to explain what I'll be doing in the next months.

Over the past years I've devoting both my personal and professional time to 3D related coding, including, but not limited to, software/hardware rasterizers, raytracers or related tools. I've also toyed with non PC hardware quite a lot, as I've coded for the Playstation 1, GBA, DS and PSP (the latter two to a large extent). As such, it was a natural choice doing my final project on something related to 3D.

Over the past year, I've seen a lot of times comparisons between the different game rendering techniques: I mean how the problem of illuminating surfaces with several different lights is accomplished. First, the discussion is between forward and deferred rendering, not between several less memory heavy deferred rendering approaches. As of now, I've done an implementation of both forward lighting and deferred lighting, but both engines had a very different target (and test scenes). What I want to do now, is to test several different approaches on the same test scenes and be able to compare them in the same environment.

So, let's sum it up, I want to implement the following 4 techniques:
  • Forward rendering (probably multi-pass, and not multi-light übershaders)
  • Deferred rendering (the old big GBuffer approach)
  • Pre-light pass (also know as deferred lighting)
  • Light indexed rendering
I'll mainly focus my work on getting all renderers to show all scenes to a certain degree of fidelity, even if at the cost of performance: if the scene is not meant to perform well on one of the techniques, I won't be doing any quality downgrades on the renderer (for example, dropping lights or transparency).

This is really important, as I want to focus on accurately benchmarking all of them and getting a fair comparison of them on a wide range of scenes. The main problem of my tests will be that I'll probably only be using a PC (not a PS3 or a Xbox360), which won't give a industry level comparison, but I don't have access to that hardware now, and even if I had, access to the PS3 GPU is not possible without a devkit, which is way out of my budget :P

To sum it up, I'll be doing a benchmark of different rendering techniques, let's start the ride :)

by shash (noreply@blogger.com) at 23 de September, 2009 08:51 PM

Neurogence

Welcome

Neurogence is an attempt to compile a collection of articles, techniques, methods and ideas about Artificial Intelligence. In this website we'll post some of advances and news in AI, interesting books, useful links, and areas where AI is currently in use, as well as a few descriptions, myths and definitions.Also, here we'll challenge to anyone who wants to share AI algorithms for specific

by gyakoo (noreply@blogger.com) at 23 de September, 2009 04:56 AM

Computer vision, pattern recognition and hot dogs

Is impressive how the flex-pickers recognize and classify the hot dogs.There are a lot of variables to take into account as well as recognition of forms, robotics, IK, the conveyor belt, optimization to select the best place where to put the hot dogs ... all in realtime. You can see how some pieces can't be processed, but surely they're used to feed back the pipeline.

by gyakoo (noreply@blogger.com) at 23 de September, 2009 04:55 AM

Fantastic AI

In the middle of 2005 I started to work in a company called Gextech where we were developing for 3 years, a non-interactive, bet-oriented soccer game: Fantastic League. I was the AI senior programmer there, and I'll try to explain how we did it.It was interesting and motivating for us. One of the challenges was to create a sort of "artificial intelligence" for football players. I say "sort of"

by gyakoo (noreply@blogger.com) at 23 de September, 2009 04:55 AM

09 de August, 2009

Historías de un coder

Puños fuera!

Hace unos días estuve en casa de un amigo que acaba de tener un hijo (técnicamente su pareja, pero ya se entiende). Hacía casi dos años que no nos veíamos, aunque hace mucho que nos conocemos: al irme de Barcelona, habíamos perdido el contacto. Fui a su piso, conocí a su hijo (que entonces hacía 7 días exactos que había nacido) y me invitaron a comer. Su madre preparó unas de las paellas mas espectaculares que puedo recordar. Compartieron lo que tenían conmigo, de forma generosa.

Cuando era pequeño, solíamos ir, con mis padres y los compañeros del club excursionista, bastante de camping. Allí, casi siempre que comíamos se hacia en comunidad, se compartía la comida con todos, y nadie abusaba comiéndoselo todo ni nada parecido.

Y porque cuento todo este rollo personal, cuando os importa un pepino? Pues porque al final de este post hay el código de la ultima prod que hemos hecho slack y yo. He limpiado un poco el código, y ahora debería requerir menos GPU, pudiendo funcionar en aquellas tarjetas que no soporten GLSL 1.2 (o OpenGL 2.1 completo, si lo preferís). Ademas, he reducido el tamaño de la prod a la vez que he añadido soporte decente para resoluciones diferentes y para esconder el ratón.

No he añadido contenido ni he corregido el que había, prefiero trabajar en nuevas prods que no invertir tiempo en esta: únicamente sacamos versión final porque ha sido un trabajo derivado de limpiar el código para publicarlo. De hecho, al poco de publicar este post estaré empezando la nueva prod. Ademas he publicado versión final de la 4k:

- otopoto / Collapse & Gatitos (versión final)
- otopoto / Collapse & Gatitos (código fuente)

Preguntas, insultos y correcciones serán bienvenidas.

by shash (noreply@blogger.com) at 09 de August, 2009 09:45 PM

Nueva 4k

Pues eso, hemos terminado una nueva 4k. Las criticas no han sido buenas, y quedamos segundos. Ademas, para añadirle insulto, es la 4k a la que posiblemente he dedicado mas tiempo. Vaya, un fiasco, no? No creáis. Voy a contar porqué.

Hace 2 años exactos, decidí dejar de producir. Acababa de volver de la Euskal, habíamos ganado la competición de 4k, y yo solo podía sentir frustración por la producción con la que habíamos ganado: mucho material reutilizado y hecha con desgana. El hecho que ganara solo añadió insulto al asunto. Ya entonces consideraba seriamente que no producía al nivel que podía hacerlo, al menos en lo que respecta a técnica. Hacer cosas abstractas esta bien una temporada, pero después de unos años...

Decidí dejar de producir hasta que no pusiera todo mi empeño en una producción. Hace algo menos de un año empecé con la versión final de la Let yourself go, ya que creía que merecía un poco de amor antes de olvidarla para siempre. La idea era pillar carrerilla en algo orientado a la demoscene, y luego empezar algo nuevo. Siempre con la idea de volver a producir con ganas, y dar lo que pudiera, al menos a nivel técnico.

Y aunque el resultado de la otopoto no sea el que tenía en la cabeza, y siendo consciente que había muchísimas cosas por pulir, puedo levantar la cabeza alto y sentirme orgulloso de haber trabajado en ella a consciencia. Obviamente, el resultado artístico deja que desear, pero técnicamente tiene detalles interesantes. En la próxima tengo que recordar centrarme mas en la parte artística, como hacía con las producciones mas abstractas.

Solo para notar como las prisas finales hicieron recortar en calidad, comparad los 2 shots siguientes. El primero es el de la prod a una semana de la party, el segundo de la versión presentada en la party:


No mucho mas que comentar al respecto, si alguien quiere mas detalles, que comente y le responderé lo mejor que sepa.

A parte, en esta euskal también di una charla sobre 4k. Hubo cosas que funcionaron muy bien y otras que no. A parte, estaba algo nervioso, pues la sala estaba MUY llena (50-70 personas) y no había ensayado la charla tan a fondo como hubiera querido. Tenéis, de momento, el audio y las diapositivas usadas aquí. A final de verano saldrá el vídeo de la charla, cuando esté disponible ya lo comentaré por aquí.

by shash (noreply@blogger.com) at 09 de August, 2009 09:45 PM

28 de July, 2009

Jesús de santos

The Documentation Challenge

Documentation is the part of the development process where usually less time and money is invested. Few resources implies a poor infrastructure for something that, as the project gets bigger and...

by ent at 28 de July, 2009 07:58 PM

23 de July, 2009

Rubén Penalva's blog

Summer blog break

I’m going to take a break from updating the blog. I will post again in September. Have a happy summer!

by Ruben Penalva at 23 de July, 2009 08:00 AM

16 de July, 2009

Soledad Penades

“escena.org dentro v2″ sources released

Escena.org dentro v2

So here’s the last installment of my demoscene sources: escena.org dentro version 2. It was done for past year’s Inspire democompo and it won (incidentally, there weren’t any other entries in the compo but hey, it’s not my fault! :P).

This demo used a different approach; instead of building a whole scaffolding of C++ classes I just wrote some glue code with C++ in order to be able to draw something with OpenGL, and scripted everything else using Lua. It was also a bit of a benchmark. The result isn’t bad, given my lack of experience with Lua :)

Here’s the HD video (and here’s on vimeo, if you prefer it to youtube), and finally, here are the sources.

PS: The count down goes on to 1, and…

by sole at 16 de July, 2009 10:13 AM

03 de July, 2009

Historías de un coder

Hoy, snippets cortos de código

Viendo como OpenGL va a deprecar parte del API (cosa que me parece bien, a ver si conseguimos mejores drivers!), y la costumbre de programar cosas de mas que tenemos algunos, he creído que alguien le seria útil. Funcionan 100% igual que las funciones de la API (misma matriz, etc). Empezaré por el mas trivial (la implementación es directa respecto a la documentación), crear una matriz de proyección ortográfica, con los mismos parámetros que gluOrtho:

   1:  CMatrix4x4 CreateOrtographicProj (float left,   float right, 
   2:                                    float bottom, float top, 
   3:                                    float Near,   float zFar)
   4:  {
   5:   CMatrix4x4 result;
   6:
   7:   float  tx = -(right+left)/(right-left),
   8:          ty = -(top+bottom)/(top-bottom),
   9:          tz = -(zFar+zNear)/(zFar-zNear);
  10:
  11:   result.Set (2.f/(right-left), 0.f,              0.f,               tx,
  12:               0.f,              2.f/(top-bottom), 0.f,               ty,
  13:               0.f,              0.f,             -2.f/(zFar-zNear),  tz,
  14:               0.f,              0.f,              0.f,               1.f);
  15:
  16:   return result;
  17:  }

Como apunte, en todos los snippets de codigo usan ciertas clases matemáticas sencillas que uso, en esta la clase matriz cuadrada de 4 elementos. Si hay alguna duda sobre esto, comentadlo y expando los detalles sobre ellas. A efectos prácticos, podéis suponer que CMatrix4x4::Set (...) es equivalente a ir asignando a un array de floats de 16 elementos: el primer parámetro seria el primer elemento del array, el segundo parámetro el segundo elemento, etc.

En segundo lugar, proyección en perspectiva, equivalente a gluPerspective:

   1:  CMatrix4x4 CreatePerspectiveProj (float fovy,  float aspect, 
   2:                                    float zNear, float zFar)
   3:  {
   4:   float f    = tanf (((fovy/180.f)*(float)M_PI) / 2.0f);
   5:   float div  = (zNear-zFar);
   6:
   7:   f   = IsFloatEqual(f, 0.f) ? FLT_MAX : 1.f / f;
   8:   div = IsFloatEqual(div, 0.f) ? FLT_MAX : 1.f / div;
9:
  10:   CMatrix4x4 result;
  11:
  12:   result.Set (f / aspect, 0.f,   0.f,              0.f,
  13:               0.f,          f,   0.f,              0.f,
  14:               0.f,        0.f,   (zFar+zNear)*div, (2.f*zFar*zNear)*div,
  15:               0.f,        0.f,  -1.f,              0.f);
  16:
  17:   return result;
  18:  }

A comentar, la macro IsFloatEqual solo compara dos números en coma flotante: el método normalmente mas recomendado (pero menos rápido, obviamente), es restarlos, coger el valor absoluto, y comparar si es menor que cierto epsilon. Esto se hace así debido a que por precisión de los numeros en coma flotante, comparar con numeros exactos (por ejemplo, haciendo float == 0.0) es desaconsejable.

Finalmente, el que tiene mas curro, el gluLookAt (sobretodo, porque la documentación obvia ciertos detalles):

   1:  CMatrix4x4 CreateLookAt (const CVector3 &eye,
   2:                           const CVector3 &center, 
   3:                           const CVector3 &up)
   4:  {
   5:   CVector3 f      (center-eye);
   6:   CVector3 upLocal(up);
   7:
   8:   f.Normalize();
   9:   upLocal.Normalize();
  10:
  11:   CVector3 s = f ^ upLocal;
  12:   CVector3 u = s ^ f;
  13:
  14:   s.Normalize();
  15:   u.Normalize();
  16:
  17:   CMatrix4x4 result, translate;
  18:
  19:   result.Set ( s.x,  s.y,  s.z, 0.f,
  20:                u.x,  u.y,  u.z, 0.f,
  21:               -f.x, -f.y, -f.z, 0.f,
  22:                0.f,  0.f,  0.f, 1.f);
  23:
  24:   translate.SetTranslation (eye*-1.f);
  25:
  26:   return result*translate;
  27:  }

A ver, destacar de este snippet, que el operador^ de la clase CVector3 equivale a hacer un producto vectorial (cross product), que el método Normalize hace lo inferible del nombre (es decir, normaliza el vector usando su modulo), y que el método SetTranslation de la clase CMatrix4x4, simplemente asigna a una traslación a la matriz (en este caso, al ser una matriz identidad, simplemente creamos una matriz de traslación).

No he explicado a fondo que hace cada parte, para eso tenéis los links a la documentación de OpenGL, y si hay mas preguntas mejor dejad comentarios.

La licencia de este código es la obvia y clásica haced lo que os dé la gana con él. Si encontrais algun bug, comentarlo y aprendemos todos de ello :)

by shash (noreply@blogger.com) at 03 de July, 2009 09:55 PM

15 de May, 2009

Historías de un coder

Volviendo a empezar, poco a poco

Hacia mucho que no escribía por aquí. El ultimo post quería decir que vuelvo a verme motivado para producir demos. Aunque muchos ya lo saben, me tomé un descanso porque noté que no producía lo mejor que podía, y no quería seguir creando productos sub-par. No creo que todas mis producciones sean mierda, ni de lejos, pero la ultima 4k, la forma de hacerla (la casi nula intención por crear algo de calidad), fue la razón que decidiera parar.

Durante el parón (y antes de él) me he visto envuelto en bastantes proyectos, algunos de ellos públicos, muchos de ellos privados, que solo han visto las pocas personas en las que confío para mostrar mis trabajos en progreso. Por eso, hoy quiero hacer un poco de resumen, con mas pantallazos que texto. Al fin y al cabo, nadie lee los blogs, para que escribir :P

Me gustaría, pero no sé si conseguiré, que hubiera preguntas respecto a los proyectos. Estoy muy abierto a dar toda la información posible y ayuda. No soy muy partidario de dar código a espuertas, pues creo que coger el vicio de copiar código por sistema es malo. Aprender a hacer algo basado en una explicación concisa me parece mucho mas didáctico. Así pues, preguntad, y intentaré dar todo mi (limitado) conocimiento.

Nada más, empezaré con los visores de formatos de geometría de juegos. Basicamente son cargadores del formato que usan ciertos juegos, tanto sea en sus modelos como en los mapas en si. Luego hay unas cuantas pantallas de mis colaboraciones en emuladores. Por cierto, los shots no están en orden cronológico, sino quedaba algo desestructurado, si alguien quiere saberlo lo comento.


Quake 1 / Quake 2




Quake 3




Portal / Half life 2
(mismo engine porque es el mismo formato)




Visor de modelos del Half Life 2
(lo programé a parte y luego lo integré en el engine de arriba)




Visor de modelos del Doom 3
(también tengo hecho un cargador de mapas, pero no tengo shots a mano)



Visor de modelos del Crysis




Port del mi motor de Quake 3 a DS
(corriendo sobre emulador, también corre en el hardware real)




Port del mi motor de Quake 3 a PSP




Desmume (emulador de DS)
(Colaboración, principalmente, trabajo en el core 3D, pero también en la CPU/2D/optimización)





jpcsp (emulador de PSP)
(Colaboración, principalmente trabajo en el core 3D)



Y esto es todo lo "importante" a mencionar. Contando que estuve activo en la demoscene hasta Julio del 2007, tampoco está tan mal. Por supuesto, podría haber hecho más, pero mucho tiempo se dedicó al emulador de DS, cuyo desarrollo fue muy complejo.

A parte, a ratos voy trabajando, como todo coder gráfico, en un engine 3D, del cual me guardaré shots para otra ocasión.

Nada más que contar ni mostrar por hoy!

by shash (noreply@blogger.com) at 15 de May, 2009 10:59 AM

11 de May, 2009

Luanatic

Welcome to Codepixel’s planet

Just to start a new tag “codepixel” :)

The whole planet here

by PpluX at 11 de May, 2009 07:02 AM

28 de April, 2009

Jesús de santos

Compile-Time Strings

It would be nice if we had such a feature in the C language, wouldn’t it? The term ‘compile-time string’ is referred here as strings that are converted to unique integer identifiers...

by ent at 28 de April, 2009 10:19 PM

09 de March, 2009

Jesús de santos

Andrew Glassner’s Notebook

Andrew Glassner’s Notebook Author: Andrew Glassner Pages: 304 Published: 1999 During periods in which I need to stay focused in hard technical problems I try to avoid reading dense books...

by ent at 09 de March, 2009 12:52 AM

02 de February, 2009

Orangemachine

Modelado de Personajes – Character Setup


En este proyecto hemos seguido el pipeline para la creación y animación de personajes. El objetivo era crear un modelo, con esqueleto, músculos, pelo, ropa y animación facial. Como resultado hemos creado una animación de 20 segundos.

Play the video

Play the video (external link)

Estoy bastante contento con el resultado. He aprendido muchas técnicas y trucos, y lo más importante, el trabajo que lleva hacer un personaje :D .

Uno de los pasos más costosos fue ajustar los pesos que influyen en los vértices cuando el esqueleto se mueve. Leyendo en el foro de CG Society, los profesionales dan de 4 a 6 pasadas para obtener un buen resultado.

Agradecimientos
Caroline Larboulette and Olivier.

Algunos screenshot durante el desarrollo y producción:

by Pablo Quesada Barriuso at 02 de February, 2009 03:40 PM

09 de January, 2009

Viento fuerte

Simulación de olas


En este proyecto se resuelve la ecuación de transporte convectivo con difusión en 2 dimensiones, reproduciendo una onda que se propaga a través de un dominio rectangular a la vez que se va amortiguando,haciendo uso de un malla bidimensional generada mediante diferencias finitas.
Se han parametrizado todos los valores de configuración, como la velocidad de refresco, el factor senoidal, las condiciones de contorno o la longitud del dominio, con el fin de facilitar su uso en tiempo de ejecución y que de esa manera sea más sencillo evaluar las condiciones de estabilidad (atendiendo sobre todo a los términos de Courant y D*).


by vientofuerte at 09 de January, 2009 02:20 AM

APO HomeWork 3


Aquí tocaba jugar un poco con animación Skelética (bones, smooth deformation, rigging …) y para endulzar un poco el video, he utilizado un plugin de generación de fuego en el que estaba trabajando.

by vientofuerte at 09 de January, 2009 02:15 AM

APO HomeWork 2


Mediante este trabajo se aplican los algoritmos vistos en clase sobre deformaciones, se han aplicado entre otros volumens de revolución, twist, taper y free form deformation. Además he jugado un poquito con sistemas de partículas y naturalmente keyframes para fabricar la animación.
Influencias:Clipper de fresa (refresco riquísimo de mi tierra) Dead Note, serie anime altamente recomendable, de donde se ha extraido parte de la BSO.-> (Clipper de fresa + Dead Note) = Clipper Note :) .

by vientofuerte at 09 de January, 2009 02:09 AM

Trazador de rayos


Este proyecto es una toma de contacto con los métodos de iluminación global, para la que se ha desarrollado un trazador de rayos muy simplificado, en lenguaje Java, partiendo de un pequeño framework con las funcionalidades básicas que no son de trazado de rayos (importación de ficheros, generación de imágens …), con el fin de centrar los esfuerzos en lo que es en si desarrollar un raytracer.
Estas son algunas de las “features” que posee nuestro trazador de rayos:

  1. Algoritmicas
    • Trazador de rayos básico
    • SuperSampling
    • Sombras
    • Reflexiones
  2. Geométricas
    • Esferas
    • Triángulos
    • Toroides
    • Cubos alineados a los ejes
  3. Materiales
    • Lambertiano (mate)
    • Phong
    • ShinyPhong
    • Transparente
    • Refractario
  4. Luces
    • Luces puntuales: Permitiendo atenuación con la distancia
  5. Optimizaciones
    • Uso de bounding-boxes alineados a los ejes

El team para este proyecto hemos sido: Pablo Quesada Barriuso, Ricardo Suárez Mesa y un servidor.

Agradecimentos a JJ: “Cuando todo falla, lo mejor es volver al origen”.

by vientofuerte at 09 de January, 2009 01:53 AM

22 de November, 2008

Orangemachine

Animación Avanzada – Simulación de Olas


Siguiendo con la serie de trabajos realizados en el Máster de Informática Gráfica, el siguiente ejemplo consiste en resolver la ecuación de transporte convectivo con difusión en dos dimensiones. De esta manera intentaremos reproducir una onda que se propaga a través de un dominio rectangular y que a su vez se va amortiguando

En general el esquema es estable para la parte de convección cuando 0 < Courant <= 1, y para la parte de difusión cuando 0 <= D* <= 0.5. Hay que recordar que cualquier método introduce una difusión “artificial” debido al propio método, y que no tiene explicación física.

En este estudio, los valores apropiados para que el sistema sea estable han sido C = 0.50 y D* = 0.25.

Downloads

- AA – Simulación Olas (rar).

Entorno de desarrollo

Framework: Eclipse CDT & Qt Integration
Code: C++, Qt 4.4.3, LibQGLViewer 2.3.1

by Pablo Quesada Barriuso at 22 de November, 2008 08:19 PM

05 de October, 2008

Vanilla Iq

Leizex

4k graphics for fun

05 de October, 2008 06:00 AM

25 de September, 2008

Vanilla Iq

Organix

4k graphics for Function

25 de September, 2008 06:00 AM