Planeta Codepixel

25 de January, 2010

Divagaciones sobre game programming

3 en raya

Al parecer estoy a punto de implantar algún nuevo record mundial de bugs consecutivos. Al fin logré descubrir qué sucedía con __setitem__, que resultó ser que estaba asignando un valor a un índice inexistente, debido a un atributo que eliminé. Creo que tendré que implementar alguna forma de validar los valores que los scripts tratan de asignar a ciertas cosas.
Sin emabrgo, apenas arreglé ese apareció otro, el juego se caía más o menos ne el mismo lugar. La cuestió era código sin probar que había añadido mientras el anterior bug no me dejaba ejecutar la aplicación. Me tomó un buen rato descubrir que el problema no estaba en los scripts, sino en un parseo incorrecto del XML de los mapas del juego. Y al fin logré entrar otra vez en el juego, solo para descubrir que ahora no funciona el código de movimiento de los personajes en modo isométrico. El modelo simplemente gira y se queda caminando en el mismo lugar. Nada, que hay veces en que uno maldice la hora en que se le ocurrió programar. Me pregunto si cuando solucione ese aparecerá un cuarto problema.
A propósito, busco hosting para proyectos libres, que sea gratis, tenga SVN y espacio web. Obviamente, ubicado fuera de USA.

by roger (noreply@blogger.com) at 25 de January, 2010 02:57 PM

23 de January, 2010

Divagaciones sobre game programming

Código roto

Esto de la programación tiene sus cosas. Es muy común encontrarse todo tipo de problemas del Orinoco, que tú no sabes ni yo tampoco, como esto que me acaba de ocurrir.
Como he dicho en varias ocasiones, utilizo SWIG para generar el código que permite a los scripts en Lua acceder a las variables de la aplicación en C++. SWIG maneja casi todo tipo de cosas, incluyendo operadores, pero por desgracia, no maneja arreglos. El operador [] se emula mediante unas funciones auxiliares, __setitem__/__getitem__ muy sencillas y que funcionan (valga la redundancia) bastante bien. Hasta hace una semana. Algo he cambiado que provoca un error: Error in __setitem__ (arg 2), expected 'int' got 'nil'. El valor no es asignado, con el consiguiente fallo de toda la aplicación poco después.
Y por supuesto, en la lista de correo de Lua nadie tiene idea de qué puede estar pasando.

by roger (noreply@blogger.com) at 23 de January, 2010 05:54 PM

22 de January, 2010

Divagaciones sobre game programming

Rediseñado las habilidades

Esta era una tarea que había dejado para después, ya que ni siquiera tenía un prototipo jugable del proyecto. Desde el principio la idea fue tener atributos básicos y habilidades, como todo RPG que se precie de serlo. El caso es que ya es hora que me tome esto en serio y defina un conjunto de habilidades raíz, las cuales tendrán otras ramificaciones que serán las habilidades que en verdad podremos ejecutar.
Por ejemplo, Magia. Magia influye en la potencia de los hechizos y su probabilidad de fallo, y es la habilidad que podremos nivelar a medida que usemos hechizos. Cualquier jugador puede tener esta habilidad, aún cuando no sea mago. La diferencia es que no tendrás acceso a todo el arsenal de hechizos si eres Mondongo Oblongo, guerrero de profesión y con el cerebro de un protozoo. Sin embargo esto permite cositas tales como que los Antiguos sean guerreros con excepcionales dotes para trucos mágicos. O viceversa: que puedas desarrollar un mago que sea un gran espadachín.
La lista de habilidades raíz es solo una nebulosa en mi cabeza, por el momento. Me falta definir si las diferentes armas de cuerpo a cuerpo serán regidas por habilidades distintas o por una sola, y un conjunto extra como oratoria o comercio.

by roger (noreply@blogger.com) at 22 de January, 2010 06:59 PM

21 de January, 2010

Tutfanzine

3D Studio Game y Lite-C

Por twitter he averiguado que 3d Studio Game a publicado una versión Free de su editor, junto a un nuevo lenguaje de programación, Lite-C.

Podéis informaros en

http://www.3dgamestudio.com/

Está la versión Free, la Trial, Extra y la Pro. Yo voy a probar la primera de ellas para ver de que va el tema. Si queréis ver que contiene cada una de sus versiones:

http://www.conitec.net/english/gstudio/order7.php

3D Game Studio
Por lo pronto me descargué el 3D Studio Game A7 versión Free y la instalé sin problemas
Me ha el Script Editor, el Ingame editor, el Model Editor, Level editor. Todavía no se que limitaciones tiene, os iré informando.

El Lite-C
Un lenguage de script para trabajar con 3D Game Studio cuya sintaxi es muy parecida a C ( de ahí el nombre ).

Me descargué el instalador y para ejecutarlo ( y esto va para los que tengáis Win7 o Vista y no se os ejecute correctamente ) tuve que poner que lo ejecutara con compatibilidad XP Service Pack 3 ( Botón derecho sobre el instalador, pestaña compatibilidad y seleccionar XP Service Pack 3 ).

Me lo instaló correctamente. Del icono que me crea en el escritorio le volví a asignar compatibilidad con XP y se puso en marcha sin problemas. Todavía no he probado de compilar nada.

Pequeño ejemplo de 3D Game Studio


Referencias:
www.3dgamestudio.com
La página de Lite-C

by Toni Rodriguez (noreply@blogger.com) at 21 de January, 2010 07:04 AM

20 de January, 2010

Divagaciones sobre game programming

SVN actualizado

Estoy en proceso de actualizar el repositorio SVN en Sourceforge con los últimos cambios y arreglos. Ya hay una ventana para revisar el inventario (vacío, a menos que cumplas la misión inicial) y otra para comerciar, aún sin implementar pues no he dispuesto de tiempo suficiente para programar.
Así que si alguien quiere tomarse la molestia de bajar el svn (las indicaciones están en algún sitio aquí), el código debería funcionar a menos que yo haya olvidado algo. Antes de compilar es necesario regenerar los wrappers, que esos sí no me preocupo de tenerlos actualizados. Para ello basta con ejecutar pkgs/swig-regen.sh. Para los usuarios de Windows tendré que buscar una variante, pero es que me resulta más cómodo manejar algunas cosas desde bash.

by roger (noreply@blogger.com) at 20 de January, 2010 01:53 PM

19 de January, 2010

Tutfanzine

Kodu - Impresiones (2)

No le voy a dar mas vueltas a Kodu. Lo último que debía saber era como exportar los niveles para que otros pudieran jugar a los niveles que creamos. Pues bien, aquí lo tenéis:

Exportar niveles a otros usuarios

me da la impresión que Kodu no se quedará aquí. Seguro que irá progresando y creciendo. De tanto en tanto le hecharé un vistazo y os iré informando.

Me ha parecido una buena experiencia y un buen 'simple editor de juegos'.

PD: Como no tengo Xbox 360, no me he molestado en buscar como poder jugar a los niveles de Kodu desde la consola. Sorry.

by Toni Rodriguez (noreply@blogger.com) at 19 de January, 2010 01:35 PM

18 de January, 2010

Tutfanzine

Kodu - Impresiones (1)

Ayer por la tarde estuve tanteando este editor-creador de juegos de Microsoft.

La primera impresión ha sido buena, teniendo en cuenta unas limitaciones, que pueden dejar de ser limitaciones si tenemos en cuenta a que 'público' va dedicado: gente que quiere crear juegos sin programar o críos que quieran iniciarse.

Es cierto que lo puede utilizar todo el mundo, y en una tarde puedes tener un pequeño juego con el que reírte un rato. Pero no mas.

Los objetos son limitados y las acciones a realizar también. Hay tres clases de objetos: Kodu, que es el personajes, y dos categorías mas de bots que abarcan un grupo de personajillos u objetos que puedes colocar en tu juegos.

Empiezas creando un mundo vacío. Cuando entras, debes editar tu mundo creando el suelo con diferentes materiales y dándoles mas o menos altitud. Después colocas los objetos, después los enemigos, y por último el personaje jugador.

Una vez colocado todo ( hay varias formas, permite el copy-paste de objetos, por ejemplo ), debes asignarles a cada uno de ellos el comportamiento que deben tener a cada evento que se realice en el juego. sí pues:

Seleccionas al personaje jugador ( kodu ), botón derecho, programar. Le asignas que cuando se pulse la tecla 'Up' se mueva ràpido. Cuando se pulse la tecla 'Down' se pare, .... cuano choque con una manzana se la coma, cuano choque con una manzana se incremente los puntos, ...

Vamos, que de una manera limitada y sencilla tienes tu jueguecillo.

Me queda pendiente como se publica. No se como crear el ejecutable o como se exporta el juego para poderlo jugar... os iré informando.

by Toni Rodriguez (noreply@blogger.com) at 18 de January, 2010 01:55 PM

Kodu - crea sencillos juegos para PC o la 360

Tengo que decir que todavía no lo he probado. Kodu, producto de ... Microsoft ( el lado oscuro ) ..., pretende ser un 'sencillo' editor de juegos con los que crear juegos de una manera sencilla.

Como habitualmente trabajo con Ubuntu, voy atrasando la prueba del mismo, pero prometo probarlo e intentar explicar mis impresiones sobre Kodu.



Por lo que he podido observar, puedes crear tus niveles, ir colocando personajillos e ir asignándoles eventos. Desconozco si puedes ir añadiendo personajes creados por ti mismo o niveles propios ... es algo que debo mirar.



Estando por el medio Microsoft, seguro que algo de pago hay. No me extrañaría que te dejen hacer el juego, pero si lo quieres publicar debas pagar, o debas pagar $ por apuntarte a algún grupo de programación, o vete a saber tu con que motivo te hacen pagar ... otra cosa a investigar.

Si queréis mas información al respecto:

Web oficial de Kodu en Microsoft

Blog oficial de Kodu con ejemplos, noticias, ...

Pues ale, a crear jueguecillos. Será cuestión de probarlo para saber donde te hacen pagar.

by Toni Rodriguez (noreply@blogger.com) at 18 de January, 2010 11:17 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

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

Un año menos

Vaya año más movido...  viajé a Canarias, Granada, Menorca, Madrid, Guimaraes, París, y dentro de casa, conocí las estupendas playas de Ézaro y Carnota.Me mudé a las afueras de Santiago, a una urbanización donde pude disfrutar de unas fresas exquisitas, extraidas de la minihuerta de la (Leer resto de la noticia | read full post)

31 de December, 2009 06:26 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

15 de December, 2009

Strawberry Iq

04 de December, 2009

Interface

No a la censura y el retraso social y tecnológico.

http://www.enriquedans.com/2009/12/manifiesto-en-defensa-de-los-derechos-fundamentales-en-internet.html (Leer resto de la noticia | read full post)

04 de December, 2009 07:02 AM

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

28 de August, 2009

El laboratorio del Dr. Txap

Tezcalipoca de Robin George

Tezcatlipoca, es señor del cielo y de la tierra, fuente de vida, tutela y amparo del hombre, origen del poder y la felicidad, dueño de las batallas, omnipresente, fuerte e invisible.

El lado norte del universo se identificaba con el Mictlán, región del reposo, y se llama Mictlampa, rumbo de los muertos. Se asocia con el color negro, con la imagen del Técpatl o cuchillo de pedernal, lo preside Yayauhqui Tezcatlipoca (Oscuro espejo su esplender). El norte es una región árida por donde soplan los vientos fríos. Tezcatlipoca es señor de los guerreros y gobernantes; guardian del frío que representa el cielo nocturno. Es un protector que tiene el don de la ubicuidad. Su atributo principal es el espejo que humea; su disfraz es el jaguar, el que va al corazón de la montaña (Tepeyolohtli) y su emblema un cuchillo de obsidiana, que representa el viento negro y cortante, como las palabras que desarmonizan el entorno y la comunicación cuando no se emplean adecuadamente [...]

De la wikipedia

Aquí en alta calidad.

Vía CGDigg.

by Txapulín at 28 de August, 2009 12:40 PM

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

15 de July, 2009

Soledad Penades

“re:fritos” sources released

ppg06: refritos

Since the code for re:fritos is pretty much the same than the one from tube, porting it to Linux has been pretty much easy. So here’s another batch of demoscene sources! This demo is totally different from tube. While tube is highly aggressive and reflects perfectly the daily fight to get to your final destination on time, re:fritos is a cheeky, for-fun only, demo.

While porting this demo to Linux, I found something strange. Once I finally got everything compiled again, and executed the demo, I got a super segfault when initializing one of the resources in the demo. The SEGFAULT more exactly happened when calling std_vector::push_back. The fun begins when I tell you that this very source had also been compiled in mac and in windows, always using gcc, and never got any problem when executing it, and the machine was way less powerful than this one (just compare a Quad Core vs a humble Powerbook G4 or Mac Mini).

Trying to find out why was that happening, I suspected it could be something to do with the heap size or the stack size, although I didn’t quite know why should I have that problem. I did a test in which the effect used less interpolation points (and therefore used less memory), and the SEGFAULT didn’t happen, so that confirmed my suspicions in some way. But why? Some forums suggested to have a look at ulimits and see if that would shed any light but it didn’t really help me (or I don’t quite know how to read those results). Looking somewhere else, they suggested to add the #include <new> line. I tried it, quite skeptically to be honest, and to my surprise, the demo worked! I’m still puzzled by this. I guess that maybe Xcode included that header or linked to it when building, but I still don’t now what’s the purpose of that header. Must investigate.

Anyway, enjoy the demo, have a peek at the code, or if you know anything about this mysterious new and segfault issue, do let me know!

PS: And the count down goes on! 2…

by sole at 15 de July, 2009 02:50 PM

14 de July, 2009

Soledad Penades

“tube” sources released

Tube by xplsv

I began working on my new, shiny notengine (full name: thisisnotanengine) a few months after vslpx was released. It took some ideas and knowledge from that code base but it also introduced some new concepts and changed others. The result, now that I see it from the distance, is a horrible amalgamation of misunderstood C++ concepts and unoptimized code. Not all is due to my inexperience in C/C++ but also because of the (you guess it) lack of time. Too many things to do, so little time.

Because there are so many amazing demos out there already, one strives to improve and get better with each release, and while there’s no harm in that, there is a problem if you force yourself to release something just because there’s a party, and not because the production is mature enough. So you adjust your schedules to something artificial like the demoparties and end up half finishing things, spending too much time tracking stupid bugs which wouldn’t happen in a normal, less stressful, situation. Or they would happen, but you would be able to recognize them because you would be awake and alert.

Going through the source code for this demo, after a couple of years of not touching it, has been an incredible eye opener. I have found several fundamental design errors, lots of direct attacks to the DRY principle and tons of unfinished, half baked stuff. All because there was an imminent party and a demo had to be delivered. And while the main concept of this demosystem is quite good, the implementation is too cumbersome and am not particularly proud of it. I wouldn’t recommend to anyone learning how to code a demo to try and learn from those sources. But I guess if you’re curious at to how it is done, then they should be fine :)

The demo itself doesn’t look that bad, and it decidedly moved some people at Breakpoint’06. It was also funny to record the videos and stuff, and I even toy with the idea of making a sequel, probably using this song of mine inspired by Valencia’s underground rail.

PS: I’m not being very original lately, am I? But once you start something, it must be finished! Oh, and let’s start a count down too: 3…

by sole at 14 de July, 2009 06:51 PM

13 de July, 2009

Soledad Penades

“vslpx” sources released

vslpx by xplsv

vslpx is an strange hybrid between the code of “Blue Tuesday” and “Tube” (to be added shortly ;)). It was all done in a hurry (sadly, as usual) and it shows at some points. Some others are really cool, but it could also be a result of randomness ;)

Here’s a short anecdote for those interested: a few weeks after releasing this demo I bought my first Mac, but for some strange reason this was my only demo that I never tried to make work in a non Windows operating system. So porting this to Linux has been a bit the portability nightmare. It was full of proprietary functions like _stricmp, references to windows.h and whatnot. I still am not sure why I never attempted to port this one before. Maybe because it was still too fresh and I didn’t want to remember the sleepless night to finish it in time for the compo? We’ll never know!

Anyway, enjoy or improve it!

by sole at 13 de July, 2009 04:39 PM

04 de July, 2009

Rubén Penalva's blog

ITC2009: Line Segment Intersection

The problem of this contest’s round was to find the intersections within a set of 3d line segments. I found tons of information in google about algorithms solving this problem in 2d. It seems that finding the intersections in a set of 2d line segments is a well known problem of computational geometry. Unfortunately, I didn’t find any algorithm in 3d and I wasn’t sure that converting the 2d algorithms to 3d could give better results than a brute force approach. Taking this into account, I decided to implement a brute force algorithm using a simple line segment intersection test. This approach gave ~800secs in a set of 100.000 line segments. I realized that the tests that were already tested could be skipped, after the modification the algorithm gave ~300secs. At this moment, I removed every instruction of the if intersection test statement (don’t ask why) resulting in a running time of ~6secs. This time was wrong. I was compiling with the optimizations active, so the compiler just removed the call to the intersection test function, giving a double nested loop doing pointer dereferencing. Well, after this little mistake I was ready to think in how to parallelize the algorithm.

As with the previous problem I used Threading Building Blocks as the tool to parallelize the algorithm. I chose to use the parallel_reduce algorithm, after trying to make it with parallel_for. The problem is gathering the results across all the tasks. Parallel_reduce is an easy way of collect results after the tasks completion. The algorithm includes a synchronization method: join. After a task ends the join method is called to merge the results. The parallel approach gave me a time of ~60secs.

I think the speed I got wasn’t that fast to win this round but that’s not my objective. I’m having a lot of fun, I’m learning from other people and I’m learning how to use TBB. Those are my objectives.

by Ruben Penalva at 04 de July, 2009 10:00 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

20 de June, 2009

Rubén Penalva's blog

ITC2009: Knapsack

The 5th problem of the Intel Threading Challenge 2009 Contest is a bounded knapsack  problem with real numbers instead of integers. You can get more information about knapsack problems in “Knapsack Problems: Algorithms and Computer Implementations”, Silvano Martello and Paolo Tooth, which is a free book.  I implemented a classical dynamic programming algorithm using Intel Threading Build Blocks to parallelize it. More information on dynamic programming in “Introduction to Algorithms, Second Edition” .

The approach I took to solve the problem is really naive due time constraints. The problems I found were:

  • Convert a bounded knapsack problem to a 0-1 knapsack problem.
  • Convert real number weights and benefits to integers.
  • Parallelization of the serial algorithm.
  • Memory efficiency.

The serial algorithm is really naive:

  1. Convert the weights and values to integer numbers.
  2. Convert the problem to a 0-1 knapsack problem repeating bounded limit times the items.
  3. Solve 0-1 knapsack problems with a dynamic programming algorithm.
  4. Trace back the items.

As you see this approach is the classical example of dynamic programming you can find in textbooks. Although it has big problems when you try to solve big data.  Repeating the items bounded limit times its a really easy way to convert the problem but needs tons of memory. Multiplying by 100 makes the deal, but it can lead to rounding precision problems. The parallel algorithm is the same but using a “parallel_for” to replace the second for loop of the algorithm.

Well, the solution proposed is very naive, so I don’t expect good results in the contest. Anyway, I enjoyed the problem and I’m already thinking about the next one: “Segment intersection”.

by Ruben Penalva at 20 de June, 2009 10:00 AM

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

16 de January, 2009

Jesús de santos

Planet 51 Trailer

Since the first day I saw content from Planet51 I knew it was going to rock. I am emotionally attached to this movie because I worked in the Videogame for a few months and because I have worked in...

by ent at 16 de January, 2009 10:26 AM

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