Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/multi/SRC/RenataXO.cpp
blob: 9eb3ea68e1c61e86140089ad8dbdcfa13f03eec2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
 * Renata.cpp
 *
 *  Created on: 5/11/2010
 *      Author: smarichal
 */

#ifdef _WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#ifndef __APPLE__
#include <GL/gl.h>
#include <GL/glut.h>
#else
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
#endif
#include <AR/gsub.h>
#include <AR/video.h>
#include <AR/param.h>
#include <AR/ar.h>
#include <AR/arMulti.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include "Utilidades.h"
#include "cvUtilities.h"
#include "UtilidadesSDL.h"
#include "stdio.h"
#include "stdlib.h"
#include <unistd.h>
#include <math.h>
#include <formatopixel.h>

#include "cvUtilities.h"

			/*************************************************************************************************************************
			 * 									CONFIGURACIONES GENERALES DE LA APLICACION
			 *************************************************************************************************************************/


			/*************************************************************************************************************************
			 * 									CONFIGURACION DE RECONOCIMIENTO DE COLORES
			 *************************************************************************************************************************/


			/********************************************************************************************************************************
			 * 								CONFIGURACION DE ARTOOLKIT Y MARCADORES
			 ********************************************************************************************************************************/
int lite = 0;
#define MAX_MARCADORES 30
/* set up the video format globals */

#ifdef _WIN32
char			*vconf = "Data\\WDM_camera_flipV.xml";
#else
char			*vconf = "";
#endif

int             xsize, ysize;
int             thresh = 100;
int             count = 0;

char           *cparam_name    = "Data/camera_para.dat";
ARParam         cparam;

int mostrarVideo=1;

/**************************************************************************************************************************************
 * ************************************************************************************************************************************
 *  										VARIABLES DEL PROTOTIPO
 * ************************************************************************************************************************************
 * ************************************************************************************************************************************/
#define MIN_DETECCIONES 2

/* Representacion de los elementos*/
Elemento elementos[MAX_MARCADORES];	//El indice el elemento coincide con el id del elemento que tambien coincide con el id del marcador artoolkit
//2 Sonidos de error
char error1[255];
char error2[255];

int cantElementosCargados = 0;

int elementoActual = -1; //indice del elemento que esta en pantalla

int xNombreRelacion = 200;
int yNombreRelacion = 15;

int xImagen = 100;
int yImagen = 100;

int anchoPantalla = 600;
int altoPantalla = 600;

int idSDLImagenPantalla =-1;


int estado = 0; //0 indica que se esta esperando un marcador
				//1 indica que se reproduce sonido
				//2 indica que se termino el cuento


Historico historico;

ARUint8         *dataPtr;
ARMarkerInfo    *marker_info;
int             marker_num;
double          err;
int             i;


//Marcadores habilitados para que la aplicacion los reconozca
char* patts[] = { "Data/renata/patterns/tortuga.patt",
                  "Data/renata/patterns/conejo.patt",
                  "Data/renata/patterns/elefante.patt",
                  "Data/renata/patterns/jirafa.patt",
                  "Data/renata/patterns/leon.patt",
                  "Data/renata/patterns/ardilla.patt"};

int* patts_id ;		//El id del marcador es el indice del elemento al que corresponde en el arreglo elementos
int ayuda = 0;
int sdlInicializado = 0;
				/***************************************************************************************************************************************
				 * 												DECALRACIONES DE FUNCIONES AUXILIARES
				 ****************************************************************************************************************************************/
static void   init(void);
static void   keyEvent( unsigned char key, int x, int y);
static void   mainLoop(void);
static int cargarMarcadores();


static int cargarMarcadores()
{
	int i ;
	int idPatt = -1;
	for(i=0;i<cantElementosCargados;i++){
        if(elementos[i].idPatt>=0){
        	idPatt = arLoadPatt(patts[i]);
			if (idPatt < 0) {
				fprintf(stderr, "setupMarker(): pattern load error !!\n");
				return (0);
			}
			if(idPatt!=elementos[i].idPatt){
				fprintf(stderr, "Error en el orden de los elementos. elemento[%d].idPatt=%d , id devuelvo por arLoadPatt=%d!!\n",i,elementos[i].idPatt,idPatt);
				return (0);
			}
			printf("Marcador id= %d cargado!\n",elementos[i].idPatt);
        }
	}

	return (1);
}

//reproduce el audio en elementos[indice]
void reproducirSonidoEtapa(int indice){
	if(elementos[indice].sonido!=NULL){
		PlaySound(elementos[indice].sonido);
	}
}

//muestra la imagen de elementos[indice]
void mostrarImagenEtapa(int indice){
	if(idSDLImagenPantalla!=-1){
		OcultarImage(idSDLImagenPantalla,1);
	}
	if(elementos[indice].idImagenSDL<0){
		elementos[indice].idImagenSDL = PlayImageConTitulo( elementos[indice].imagen, elementos[indice].nombre,xImagen,yImagen,0);
	}else{
		mostrarImagen(elementos[indice].idImagenSDL,0);
	}
	idSDLImagenPantalla = elementos[indice].idImagenSDL; //Actualizo el id de la imagen mostrada actualmente
	flip();
}

int main(int argc, char **argv)
{
	glutInit(&argc, argv);
    init();
    arVideoCapStart();
    argMainLoop( NULL, keyEvent, mainLoop );
	return (0);
}

void avanzar(){
	printf("Avanzar\n");
	printf("elementoActual=%d, cantElementosCargados-1=%d\n",elementoActual,cantElementosCargados-1);
	if(estado==1){ //termino de reproducir parte del cuento.
		estado =0;
	}else{
		if(elementoActual == cantElementosCargados -1){//TODO Vuelve a comenzar o mensaje de exito y finaliza??
			printf("FIN DEL CUENTOOOOOOOOOOOOOOOOO!\n");
			estado=2;
		}else{
			estado=1;
			elementoActual++;
		}
	}

}

/* main loop */
static int procesarFrame()
{
        ARUint8         *dataPtr;
	    ARMarkerInfo    *marker_info;
	    int             marker_num;
	    double          err;
	    int             i;

	    //arVideoCapStart();
	    if( (dataPtr = (ARUint8 *)arVideoGetImage()) == NULL ) {
		printf("sleep\n");
		arUtilSleep(2);
	        return -1;
	    }
	    if( count == 0 ) arUtilTimerReset();
	    count++;

	    /*      ATENCION, DETECTMARKERLITE ES MAS RAPIDA PERO TIENE MAS ERROR QUE DETECTMARKER      */
	    if(lite){
	        /* detect the markers in the video frame */
	        if( arDetectMarkerLite(dataPtr, thresh, &marker_info, &marker_num) < 0 ) {
	            cleanupAll();
	            exit(0);
	        }
	    }else{
	        if( arDetectMarker(dataPtr, thresh, &marker_info, &marker_num) < 0 ) {
	            cleanupAll();
	            exit(0);
	        }
	    }

	    if(mostrarVideo){
			argDrawMode2D();
			if( !arDebug ) {
				argDispImage( dataPtr, 0,0 );
			}
			else {
				argDispImage( dataPtr, 1, 1 );
				if( arImageProcMode == AR_IMAGE_PROC_IN_HALF )
					argDispHalfImage( arImage, 0, 0 );
				else
					argDispImage( arImage, 0, 0);

				glColor3f( 1.0, 0.0, 0.0 );
				glLineWidth(6.0);
				for( i = 0; i < marker_num; i++ ) {
					argDrawSquare( marker_info[i].vertex, 0, 0 );
				}
				glLineWidth( 1.0 );
			}
		}

		argSwapBuffers();

	    int j;
	    int indice = -1;
	    if(marker_num>0){
	        printf(" *marcadores detectados = %d \n",marker_num);
	    }


	    //Busco algun marcador que se haya cargado en elementos[]
	    for(j = 0;(j<marker_num);j++){
	    	printf("marker_info[%d]=%d\n",j,marker_info[j].id);
	    	printf("marker_info[%d].cf=%f\n",j,marker_info[j].cf);
	        int k;
	        if(marker_info[j].cf > 0.60){
	            for(k=0;k<cantElementosCargados;k++){
	                if(elementos[k].idPatt>=0 && marker_info[j].id==elementos[k].idPatt){ //Elije el primer marcador con el mismo id, no el que mas se parezca usando el cf
	                    printf("patt %d detectado!\n",marker_info[j].id);
	                	return elementos[k].idPatt;
	                }
	            }
	        }
	    }


	    return -1;
}

void reproducirAyuda(Elemento elemento){
	ayuda =!ayuda;
	if(ayuda==0 && error1!=NULL){
		PlaySound(error1);
	}else if(ayuda==1 && error1!=NULL){
		PlaySound(error2);
	}
}

static void mainLoop(void){
	if(!sdlInicializado){
		if(!initSDL(anchoPantalla,altoPantalla)){
				cleanupAll();
				exit(0);
		}
		CargarFondo("Data/renata/imagenes/fondoRenata.bmp",1);
		sdlInicializado = 1;
	}
	switch (estado) {
		case 0:
			arVideoCapStart();
			if(elementos[elementoActual].idPatt>=0){
				int idMarcadorEncontrado = procesarFrame();
				if(idMarcadorEncontrado>=0){
					int cant =registrarColision(idMarcadorEncontrado,&historico);
					if(cant>=MIN_DETECCIONES){	// Ya detecto el marcador suficientes veces y se da por valido.
						if(idMarcadorEncontrado==elementoActual){
							mostrarImagenEtapa(elementoActual); //Se despliega la imagen correspondiente a esta etapa del cuento y se cambia el
							avanzar();							//estado para que continue reproduciendo el sonido del cuento.
						}else{
							reproducirAyuda(elementos[elementoActual]);
						}
						initHistorico(&historico,MIN_DETECCIONES,-1);
					}

				}
				arVideoCapNext();
			}else{									//En esta etapa no se espera ningun marcador
				mostrarImagenEtapa(elementoActual); //Se despliega la imagen correspondiente a esta etapa del cuento y se cambia el
				avanzar();							//estado para que continue reproduciendo el sonido del cuento.
			}
		break;
		case 1:	//reproducir sonido de la etapa
			arVideoCapStop();
			reproducirSonidoEtapa(elementoActual);
			avanzar();
		break;
		case 2:
			//TODO alguna accion cuando termina el cuento?
			sleep(2);
			cleanupAll();
			exit(0);
		break;
		default:
			fprintf(stderr, "Estado de aplicacion invalido\n");
			exit(1);
		break;
	}


}

static void init( void )
{
    ARParam  wparam;
    //Cargo archivo de configuracion de los elementos a detectar
    cantElementosCargados = leerConfiguracionElementos("renata.config",elementos,MAX_MARCADORES,error1,error2);
    printf("Se cargaron %d elementos\n",cantElementosCargados);
    imprimirPropiedadesElementos(elementos,cantElementosCargados);
    /* open the video path */
    if( arVideoOpen( vconf ) < 0 ) exit(0);
    /* find the size of the window */
    if( arVideoInqSize(&xsize, &ysize) < 0 ) exit(0);
    printf("Image size (x,y) = (%d,%d)\n", xsize, ysize);

    /* set the initial camera parameters */
    if( arParamLoad(cparam_name, 1, &wparam) < 0 ) {
        printf("Camera parameter load error !!\n");
        exit(0);
    }
    arParamChangeSize( &wparam, xsize, ysize, &cparam );
    arInitCparam( &cparam );
    printf("*** Camera Parameter ***\n");
    arParamDisp( &cparam );

    //Mostramos la imagen de debug desde el principio
    arDebug = 1;


    /* open the graphics window */
    argInit( &cparam, 1.0, 0, 2, 1, 0 );
    arFittingMode   = AR_FITTING_TO_IDEAL;
    arImageProcMode = AR_IMAGE_PROC_IN_FULL;
    argDrawMode     = AR_DRAW_BY_TEXTURE_MAPPING;
    argTexmapMode   = AR_DRAW_TEXTURE_HALF_IMAGE;

    //Inicializacion de sdl
	/*if(!initSDL(anchoPantalla,altoPantalla)){
		cleanupAll();
		exit(0);
	}*/

	//Cargo patterns
	if(!cargarMarcadores()){
		cleanupAll();
		fprintf(stderr, "Error cargando patterns\n");
		exit(0);
	}
	//Inicializo historial
	initHistorico(&historico,MIN_DETECCIONES,-1);
	elementoActual = 0;
	estado = 1;
	//La imagen del elemento 0 es el fondo de la pantalla :)
//	CargarFondo("Data/renata/imagenes/fondoRenata.bmp",1);
}



static void   keyEvent( unsigned char key, int x, int y)
{
    /* quit if the ESC key is pressed */
    if( key == 0x1b ) {
        printf("*** %f (frame/sec)\n", (double)count/arUtilTimer());
        cleanupAll();
        exit(0);
    }

    if( key == 'v' ) {
		mostrarVideo = 1 - mostrarVideo;
		if(!mostrarVideo){
			argCleanWindow(0,0);
		}
	}

    if( key == SDLK_RETURN ) { //Avanza sin que haya reconocido el marcador
		if(estado==0){ //Si se esta esperando un marcador y se toca enter, entonces salta automaticamente y cambia el estado para seguir
			mostrarImagenEtapa(elementoActual);
			avanzar(); //reproduciendo el sonido de la proxima etapa.
		}

	}

    if( key == 't' ) {
        printf("count = %d\n",count);
        printf("timer = %f\n",arUtilTimer());
        printf("*** %f (frame/sec)\n", (double)count/arUtilTimer());
        printf("Enter new threshold value (current = %d): ", thresh);
        scanf("%d",&thresh); while( getchar()!='\n' );
        printf("\n");
        count = 0;
    }

    /* turn on and off the debug mode with right mouse */
    if( key == 'd' ) {
        printf("*** %f (frame/sec)\n", (double)count/arUtilTimer());
        arDebug = 1 - arDebug;
        if( arDebug == 0 ) {
            glClearColor( 0.0, 0.0, 0.0, 0.0 );
            glClear(GL_COLOR_BUFFER_BIT);
            argSwapBuffers();
            glClear(GL_COLOR_BUFFER_BIT);
            argSwapBuffers();
        }
        count = 0;
    }

}