示例#1
0
void gamescreen()
{
  // set the mode for 2 text layers and two extended background layers
  videoSetMode(MODE_5_2D |
               //DISPLAY_BG1_ACTIVE |
               DISPLAY_BG3_ACTIVE |
               DISPLAY_SPR_ACTIVE | DISPLAY_SPR_1D_LAYOUT
               );

  // set the first bank as background memory and the third as sub background memory
  // B and D are not used (if you want a bitmap greater than 256x256 you will need more
  // memory so another vram bank must be used and mapped consecutivly
  vramSetMainBanks(VRAM_A_MAIN_BG_0x6000000, VRAM_B_MAIN_SPRITE, //VRAM_B_MAIN_BG_0x6020000,
                   VRAM_C_SUB_BG, VRAM_D_MAIN_BG_0x6020000);
  
  // set up our bitmap background
  BG3_CR     = BG_BMP8_512x256 | BG_WRAP_ON| BG_BMP_BASE(0);
  //BG2_CR     = BG_BMP8_256x256 | BG_BMP_BASE(8);
  
  BG1_CR = BG_32x32 | BG_TILE_BASE(0) | BG_MAP_BASE(8) | BG_256_COLOR;


  // these are rotation backgrounds so you must set the rotation attributes:
  // these are fixed point numbers with the low 8 bits the fractional part
  // this basicaly gives it a 1:1 translation in x and y so you get a nice flat bitmap
  BG3_XDX = 1 << 8;
  BG3_XDY = 0;
  BG3_YDX = 0;
  BG3_YDY = 1 << 8;

  BG2_XDX = 1 << 8;
  BG2_XDY = 0;
  BG2_YDX = 0;
  BG2_YDY = 1 << 8;


  //our bitmap looks a bit better if we center it so scroll down (256 - 192) / 2
  BG3_CX = 0;
  BG3_CY = 0;

  BG2_CX = 0;
  BG2_CY = 0;

  for(int i = 0; i < 512*256; i++)
    BG_GFX[i] = ((u16*)topscreen_img_bin)[i];

  for(int i = 0; i < 256; ++i)
    BG_PALETTE[i] = ((u16*)topscreen_pal_bin)[i];
  //for(int i = 0; i < 256; ++i)
  //BG_PALETTE[i] = ((u16*)numbers_pal_bin)[i];

        
  x = 0;
  y = 0;
  px = 128-32;
  py = 103;
  oldx = x;
  oldy = y;
  drag = false;
  touch_down = touchReadXY();

  initSprites();
  
  for(int i=0;i<256*256;i++)
    {
      SPRITE_GFX[i] = i % 256 | ((i % 256) << 8);
    }

  //for(int i = 0; i < 8*8*256/2; ++i)
  //    ((u16*)BG_TILE_RAM(0))[i] = ((u16*)numbers_img_bin)[i];

  //for(int i = 0; i < 32*32; ++i)
  //((u16*)BG_MAP_RAM(8))[i] = i%256;

  /*    for(int y=0;y<64; ++y)
        for(int x=0;x<32; ++x)
        {
        SPRITE_GFX[y*64+x] = ((u16*)sprite_img_bin)[y*32+x];
        }*/

  const u8* frames[16];
  frames[0]  = walk_frame00_img_bin;
  frames[1]  = walk_frame01_img_bin;
  frames[2]  = walk_frame02_img_bin;
  frames[3]  = walk_frame03_img_bin;
  frames[4]  = walk_frame04_img_bin;
  frames[5]  = walk_frame05_img_bin;
  frames[6]  = walk_frame06_img_bin;
  frames[7]  = walk_frame07_img_bin;
  frames[8]  = walk_frame08_img_bin;
  frames[9]  = walk_frame09_img_bin;
  frames[10] = walk_frame10_img_bin;
  frames[11] = walk_frame11_img_bin;
  frames[12] = walk_frame12_img_bin;
  frames[13] = walk_frame13_img_bin;
  frames[14] = walk_frame14_img_bin;
  frames[15] = walk_frame15_img_bin;

  const u8* pal_frames[16];
  pal_frames[0]  = walk_frame00_pal_bin;
  pal_frames[1]  = walk_frame01_pal_bin;
  pal_frames[2]  = walk_frame02_pal_bin;
  pal_frames[3]  = walk_frame03_pal_bin;
  pal_frames[4]  = walk_frame04_pal_bin;
  pal_frames[5]  = walk_frame05_pal_bin;
  pal_frames[6]  = walk_frame06_pal_bin;
  pal_frames[7]  = walk_frame07_pal_bin;
  pal_frames[8]  = walk_frame08_pal_bin;
  pal_frames[9]  = walk_frame09_pal_bin;
  pal_frames[10] = walk_frame10_pal_bin;
  pal_frames[11] = walk_frame11_pal_bin;
  pal_frames[12] = walk_frame12_pal_bin;
  pal_frames[13] = walk_frame13_pal_bin;
  pal_frames[14] = walk_frame14_pal_bin;
  pal_frames[15] = walk_frame15_pal_bin;

  for(int i=0;i<64*32; ++i)
    SPRITE_GFX[i] = ((u16*)sprite_img_bin)[i];

  for(int i=0;i<32*32/2; ++i)
    SPRITE_GFX[i+64*32] = ((u16*)use_icon_img_bin)[i];

  for(int i=0;i<64*32; ++i)
    SPRITE_GFX[i+ (64*32) + (32*16)] = ((u16*)smalldoor_img_bin)[i];

  for(int i=0;i<64*32; ++i)
    SPRITE_GFX[i] = ((u16*)walk_frame00_img_bin)[i];

  for(int i = 0; i < 256; ++i)
    SPRITE_PALETTE[i] = ((u16*)walk_frame00_pal_bin)[i];


  sprites[0].attribute[0] = ATTR0_SQUARE | ATTR0_TYPE_BLENDED | ATTR0_BMP | px;
  sprites[0].attribute[1] = ATTR1_SIZE_64 | py  | ATTR1_FLIP_Y;
  sprites[0].attribute[2] = ATTR2_ALPHA(3);

  sprites[1].attribute[0] = ATTR0_SQUARE | ATTR0_COLOR_256 | (192-32-8) | ATTR0_DISABLED;
  sprites[1].attribute[1] = ATTR1_SIZE_32 | (256-32-8);
  sprites[1].attribute[2] = 64*2;//64*64;//64*32;

  sprites[2].attribute[0] = ATTR0_SQUARE | ATTR0_COLOR_256 | 90-6;
  sprites[2].attribute[1] = ATTR1_SIZE_64 | 200+16+2;
  sprites[2].attribute[2] = 64*2+32;

  int frame_index = 0;
  int sx = 0;
  //int sy = 0;
  bool left = true;;

  if (subscreen_mode == PDA)
    init_pda();
  else
    init_doorminigame();

  while(1) 
    {
      swiWaitForVBlank();

      frame_index += 1;
      frame_index = frame_index % 80;

      //SPRITE_GFX[i] = ((u16*)numbers_img_bin)[i];


      // read the button states
      scanKeys();
      touch = touchReadXY();

      pressed = keysDown();	// buttons pressed this loop
      held = keysHeld();		// buttons currently held
      
      if (subscreen_mode != DIALOG)
        {
          sprites[0].attribute[0] = ATTR0_SQUARE | ATTR0_TYPE_BLENDED | ATTR0_COLOR_256 | mod(103,512);
          sprites[0].attribute[1] = ATTR1_SIZE_64 | mod(128-32,512) | (left ? 0: ATTR1_FLIP_X);
          sprites[0].attribute[2] = ATTR2_ALPHA(3);

          sprites[2].attribute[0] = ATTR0_SQUARE | ATTR0_TYPE_BLENDED | ATTR0_COLOR_256 | mod(90-6, 512);
          sprites[2].attribute[1] = ATTR1_SIZE_64 | mod((200+16+2 - px + 128-32 + door_pos/4),512);
          sprites[2].attribute[2] = ATTR2_ALPHA(1) | 64*2+32;
        }
      else
        {
          sprites[0].attribute[0] |=  ATTR0_DISABLED;
          sprites[1].attribute[0] |=  ATTR0_DISABLED;
          sprites[2].attribute[0] |=  ATTR0_DISABLED;
        }

      if ((held & KEY_L) && (held & KEY_R))
        swiSoftReset();

      if ((pressed & KEY_LEFT) || (pressed & KEY_RIGHT))
        {
          frame_index = 0;
        }

      if (held & KEY_LEFT)
        {
          left = true;
          px -= 1;
          sprites[0].attribute[1] = sprites[0].attribute[1] & ~ATTR1_FLIP_X;

          for(int i=0;i<64*32; ++i)
            SPRITE_GFX[i] = ((u16*)frames[frame_index/5])[i];
      
          for(int i = 0; i < 256; ++i)
            SPRITE_PALETTE[i] = ((u16*)pal_frames[frame_index/5])[i];
        }
      else if (held & KEY_RIGHT)
        {
          left = false;
          px += 1;
          sprites[0].attribute[1] = sprites[0].attribute[1] | ATTR1_FLIP_X;

          for(int i=0;i<64*32; ++i)
            SPRITE_GFX[i] = ((u16*)frames[frame_index/5])[i];
      
          for(int i = 0; i < 256; ++i)
            SPRITE_PALETTE[i] = ((u16*)pal_frames[frame_index/5])[i];
        }
      else
        {
          for(int i=0;i<64*32; ++i)
            SPRITE_GFX[i] = ((u16*)frames[0])[i];
      
          for(int i = 0; i < 256; ++i)
            SPRITE_PALETTE[i] = ((u16*)pal_frames[0])[i];
        }

      if (held & KEY_DOWN)
        py += 1;
      else if (held & KEY_UP)
        py -= 1;


      if ((px + 128) > 328-16 && 
          (px + 128) < (328+35+16))
        {
          sprites[1].attribute[0] &=  ~ATTR0_DISABLED;
          //if (pressed & KEY_X)
          //            {
          if (subscreen_mode == PDA)
            {
              init_doorminigame();
              subscreen_mode = DOOR_MINIGAME;
            }
          else if (subscreen_mode == DOOR_MINIGAME)
            {
              init_pda();
              subscreen_mode = PDA;
            }
          //}
        }
      else if ((px + 128) > 133-16 &&
               (px + 128) < 133-16+32)
        {
          init_dialog();
          subscreen_mode = DIALOG;
        }
      else
        {
          sprites[1].attribute[0] |= ATTR0_DISABLED;
          if (subscreen_mode == DOOR_MINIGAME)
            {
              init_pda();
              subscreen_mode = PDA;
            }
        }


      sx = px;
      //sx += 1;
      
      if ((held & KEY_TOUCH)  && drag)
        {
          x = oldx + (touch_down.px - touch.px);
          y = oldy + (touch_down.py - touch.py);
        }

      if (!(held & KEY_TOUCH))
        drag = false;
      
      if (subscreen_mode != DIALOG)
        {
          BG3_CX  = x*500 + sx<<8 ;
          BG3_CY  = y*500 + (32<<8);
        }
      //2_CX  = -x;
      //2_CY  = -y;
      
      update_subscreen();

      updateOAM();
    }
}
示例#2
0
int main()
{	
    struct touchPosition pos;
	float rotateX = 0.0;
	float rotateY = 0.0;

	powerON(POWER_ALL);
    consoleDemoInit();

	//set mode 0, enable BG0 and set it to 3D
	videoSetMode(MODE_0_3D);

	//irqs are nice
	irqInit();
	irqEnable(IRQ_VBLANK);
    
	// initialize gl
	glInit();
    
	// enable antialiasing
	glEnable(GL_ANTIALIAS);
	
	// setup the rear plane
	glClearColor(0,0,0,31); // BG must be opaque for AA to work
	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
	glClearDepth(0x7FFF);

	//this should work the same as the normal gl call
	glViewPort(0,0,255,191);
    
	//any floating point gl call is being converted to fixed prior to being implemented
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(35, 256.0 / 192.0, 0.1, 100);
	
	gluLookAt(	0.0, 0.0, 1.0,		//camera possition 
				0.0, 0.0, 0.0,		//look at
				0.0, 1.0, 0.0);		//up

	while(1)		
	{
        float px, py;
        
    	pos = touchReadXY();
        px = pos.px;
        py = pos.py;

        px = (px * 5) / 256;
        py = (py * 3) / 192;

        px -= 2.5;
        py -= 1.5;

		glPushMatrix();

		//move it away from the camera
		glTranslate3f32(0, 0, floattof32(-1));

		glRotateX(rotateX);
		glRotateY(rotateY);

		glMatrixMode(GL_MODELVIEW);

		//not a real gl function and will likely change
		glPolyFmt(POLY_ALPHA(31) | POLY_CULL_NONE);
        
		scanKeys();
		
		u16 keys = keysHeld();
		
		if((keys & KEY_UP)) rotateX += 3;
		if((keys & KEY_DOWN)) rotateX -= 3;
		if((keys & KEY_LEFT)) rotateY += 3;
		if((keys & KEY_RIGHT)) rotateY -= 3;
        
		//draw the obj
		glBegin(GL_TRIANGLE);
			
			glColor3b(255,0,0);
			glVertex3v16(inttov16(-1),inttov16(-1),0);

			glColor3b(0,255,0);
			glVertex3v16(inttov16(1), inttov16(-1), 0);

			glColor3b(0,0,255);
			glVertex3v16(inttov16(0), inttov16(1), 0);
			
		glEnd();

        glLoadIdentity();
        glTranslatef(px,-py,-3.0);
        glBegin(GL_TRIANGLE);
            glVertex3f( 0.0, 1.0, 0.0);
            glVertex3f(-1.0,-1.0, 0.0);
            glVertex3f( 1.0,-1.0, 0.0);
        glEnd();

		glPopMatrix(1);

		glFlush(0);
		swiWaitForVBlank();
	}

	return 0;
}//end main 
示例#3
0
inline void sleep(u32 vblanks){for(u32 i = 0; i < vblanks; i++){swiWaitForVBlank();}};
示例#4
0
文件: main.c 项目: fincs/Maxmod-FeOS
// Program entrypoint
int main()
{	
	if (!mmIsARM7Loaded())
	{
		printf("Couldn't load Maxmod!\n");
		return 1;
	}

	// Init Maxmod with default settings (loading from FAR)
	mmInitDefaultFAR(hFar, "/soundbank.bin");
	
	FeOS_DirectMode();

	videoSetMode(MODE_0_2D);
	videoSetModeSub(0);
	vramSetBankA(VRAM_A_MAIN_SPRITE);

	// Initialize the sprite engine with 1D mapping 128 byte boundary
	// aand no external palette support
	oamInit(&oamMain, SpriteMapping_1D_32, false);

	int i;
	for (i = 0; i < 5; i ++)
	{
		// Allocate some space for the sprite graphics
		sprites[i].gfx = oamAllocateGfx(&oamMain, sprites[i].size, sprites[i].format);

		// Fill each sprite with a different index (2 pixels at a time)
		dmaFillHalfWords(((i+1) << 8) | (i+1), sprites[i].gfx, 32*32);
	}

	// Set indexes to different colours
	SPRITE_PALETTE[1] = RGB15(31,0,0);
	SPRITE_PALETTE[2] = RGB15(0,31,0);
	SPRITE_PALETTE[3] = RGB15(0,0,31);
	SPRITE_PALETTE[4] = RGB15(31,0,31);
	SPRITE_PALETTE[5] = RGB15(0,31,31);

	mmSetEventHandler(myEventHandler);
	mmLoad(MOD_EXAMPLE2);
	mmStart(MOD_EXAMPLE2, MM_PLAY_LOOP);

	for(;;)
	{
		swiWaitForVBlank();
		if (keysDown() & KEY_START)
			break;

		for (i = 0; i < 5; i ++)
		{
			// Constantly increase the sprite's y velocity
			sprites[i].dy += 1;
		
			// Update the sprite's y position with its y velocity
			sprites[i].y += sprites[i].dy;
		
			// Clamp the sprite's y position
			if (sprites[i].y<72) sprites[i].y = 72;
			if (sprites[i].y>96) sprites[i].y = 96;
		
			oamSet(&oamMain,                 // Main graphics engine context
			       i,                        // OAM index (0 to 127)  
			       sprites[i].x,             // X and Y pixel location of the sprite
			       sprites[i].y, 			
			       0,                        // Priority, lower renders last (on top)
			       sprites[i].paletteAlpha,  // Palette index 
			       sprites[i].size,
			       sprites[i].format,
			       sprites[i].gfx,           // Pointer to the loaded graphics
			       sprites[i].rotationIndex, // Sprite rotation data  
			       false,                    // Double the size when rotating?
			       false,                    // Hide the sprite?
			       false, false,             // VFlip, HFlip
			       false);                   // Apply mosaic
		}
	}

	mmStop();
	mmUnload(MOD_EXAMPLE2);
	mmUnloadSoundbank();

	FeOS_ConsoleMode();

	return 0;
}
示例#5
0
int main(int argc, char **argv) {

	// Pantalla de espera inicializando NitroFS
	NF_Set2D(0, 0);
	NF_Set2D(1, 0);	
	consoleDemoInit();
	iprintf("\n NitroFS init. Please wait.\n\n");
	iprintf(" Iniciando NitroFS,\n por favor, espere.\n\n");
	swiWaitForVBlank();

	// Define el ROOT e inicializa el sistema de archivos
	NF_SetRootFolder("NITROFS");	// Define la carpeta ROOT para usar NITROFS

	// Inicializa el motor 2D
	NF_Set2D(0, 0);				// Modo 2D_0 en la pantalla superior

	// Inicializa los fondos tileados
	NF_InitTiledBgBuffers();	// Inicializa los buffers para almacenar fondos
	NF_InitTiledBgSys(0);		// Inicializa los fondos Tileados para la pantalla superior

	// Inicializa los Sprites
	NF_InitSpriteBuffers();		// Inicializa los buffers para almacenar sprites y paletas
	NF_InitSpriteSys(0);		// Inicializa los sprites para la pantalla superior

	// Inicializa los buffers de mapas de colisiones
	NF_InitCmapBuffers();

	// Carga los archivos de fondo
	NF_LoadTiledBg("bg/pdemo_bg", "bg3", 256, 256);		// Carga el fondo para la capa 3, pantalla superior

	// Carga los archivos de sprites
	NF_LoadSpriteGfx("sprite/whiteball", 0, 16, 16);	// Pelota
	NF_LoadSpritePal("sprite/whitepal", 0);

	// Carga el fondo de colisiones
	NF_LoadColisionBg("maps/pdemo_colmap", 0, 256, 256);

	// Crea los fondos de la pantalla superior
	NF_CreateTiledBg(0, 3, "bg3");

	// Transfiere a la VRAM los sprites necesarios
	NF_VramSpriteGfx(0, 0, 0, true);	// Puntero
	NF_VramSpritePal(0, 0, 0);

	// Variables de uso genereal
	u8 b = 0;
	u8 n = 0;

	// Crea el Sprite del puntero en la pantalla inferior
	for (b = 0; b < 3; b ++) {
		NF_CreateSprite(0, b, 0, 0, -16, -16);	// Crea el puntero en la pantalla inferior
		NF_SpriteLayer(0, b, 3);				// Y la capa sobre la que se dibujara
	}

	// Variables para el control de movimiento
	s16 x[3];
	s16 y[3];
	x[0] = 32;
	y[0] = -16;
	x[1] = 228;
	y[1] = 32;
	x[2] = 10;
	y[2] = 100;


	// Variables de control de colisiones, define todos los puntos de colision del sprite por debajo
	s16 py[16];
	py[0] = 11;
	py[1] = 13;
	py[2] = 14;
	py[3] = 15;
	py[4] = 15;
	py[5] = 16;
	py[6] = 16;
	py[7] = 16;
	py[8] = 16;
	py[9] = 16;
	py[10] = 16;
	py[11] = 15;
	py[12] = 15;
	py[13] = 14;
	py[14] = 13;
	py[15] = 11;

	// Control de movimiento
	bool down = false;
	bool left = false;
	bool right = false;

	// Bucle (repite para siempre)
	while(1) {

		// Borra la pantalal de texto
		consoleClear();

		// Bola a bola
		for (b = 0; b < 3; b ++) {

			// Control de colisiones, caida
			down = true;	// Flag de descenso arriba
			// Busca pixel por pixel, si hay colisiones (pixel azul, nº4)
			for (n = 0; n < 16; n ++) {
				if (NF_GetPoint(0, (x[b] + n), (y[b] + py[n])) == 4) down = false;
			}

			// Control de colisiones, decide derecha o izquierda
			right = true;	// Flag de movimiento lateral arriba
			left = true;
			// Caida a izquierda
			if (NF_GetPoint(0, (x[b] - 1), (y[b] + 16)) == 4) left = false;
			// Caida a derecha
			if (NF_GetPoint(0, (x[b] + 16), (y[b] + 16)) == 4) right = false;
			// Si hay caida libre, no te muevas en horizontal
			if (left && right) {
				right = false;
				left = false;
			}

			// Si es necesario, caida libre
			if (down) y[b] ++;
			// Muevete a la derecha
			if (right) x[b] ++;
			// Muevete a la izquierda
			if (left) x[b] --;

			// Recoloca la pelota si sale de los limites de pantalla
			if (y[b] > 192) {
				x[b] = 32;
				y[b] = -16;
			}

			// Posicion del Sprite
			NF_MoveSprite(0, b, x[b], y[b]);

			// Imprime la posicion de la pelota
			printf("x:%03d  y:%03d\n", x[b], y[b]);

		}

		NF_SpriteOamSet(0);				// Actualiza el Array del OAM

		swiWaitForVBlank();				// Espera al sincronismo vertical

		oamUpdate(&oamMain);			// Actualiza a VRAM el OAM Secundario
	
	}

	return 0; 

}
示例#6
0
int BndsArticlesView::exec()
{
      /// Muestra la pantalla.
      show();
  
      while(1) {

	  swiWaitForVBlank();

	  scanKeys();
	  
	  if (keysDown() & KEY_LEFT) {
	      previousPage();
	  } else if (keysDown() & KEY_RIGHT) {
	      nextPage();
	  } else if (keysDown() & KEY_L) {
	      break;
	  } // end if

	  /// Procesa los eventos de la pantalla tactil.
	  int itemSelected = g_video->eventTemplateListA(true, true);

	  if (itemSelected == -1) {
      	      m_modifierActive = false;
	      /// Necesita repintarse.
	      show();
	  } // end if

	  if (itemSelected == -2) {
	      previousPage();
	  } // end if

	  if (itemSelected == -3) {
	      nextPage();
	  } // end if

	  if (itemSelected == -4) {
	      break;
	  } // end if
	  
	  if (itemSelected == -10) {
	      modifierChangeState();
	  } // end if
	  
	  /// itemSelected = 0 => No se ha pulsado ningun recuadro. No se hace nada.
	  if (itemSelected > 0) {
	      /// Devuelve la posicion de la categoria dentro de la lista de categorias.
	      /// El primer elemento es el 1.
	      /// Inserta el articulo en el ticket.

	      int contador = 0;
	      for (list<BndsArticle*>::iterator itArtic = m_listaArtic.begin(); itArtic != m_listaArtic.end(); itArtic++) {

		if (contador == (itemSelected - 1 + ((m_currentPage - 1) * m_maxItemsPerPage)) ) {
		  
		    if ( m_modifierActive ) {
			/// Se captura la informacion de los modificadores.
			/// 1) Captura info extra.
			/// 2) Guarda info si no se ha cancelado la accion.
			BndsModifier *mod = new BndsModifier();
			int result = mod->exec();
			if (result == 1) {
			    /// Se pulso el boton 'aceptar'. Se guarda la informacion.
			    g_db->currentTicket()->addArticle( *itArtic, mod );
			} else {
			    /// TODO: se pulso otro boton.
			    g_db->currentTicket()->addArticle( *itArtic, 0 );
			} // end if
			m_modifierActive = false;
		    } else {
			g_db->currentTicket()->addArticle( *itArtic, 0 );
		    } // end if
		    
		    /// Refresca la informacion en pantalla.
		    show();
		    /// Sale del for.
		    break;
		    
		} // end if
		
		contador++;

	      } // end for

	  } // end if

      } // end while

    return 0;
}
示例#7
0
void nds_config_key()
{
  int prev_held = 0;
  int held = 0;
  nds_cmd_t cmd;
  char buf[BUFSZ];

  u16 key;
  char command[INPUT_BUFFER_SIZE];

  nds_flush(0);

  nds_draw_prompt("Press the key to modify.");

  while (1) {
    swiWaitForVBlank();

    scanKeys();

    prev_held = held;
    held = nds_keysHeld();

    /* We don't let the user configure these */

    if ((prev_held & chord_keys) && (held == 0) && (nds_count_bits(prev_held) == 1)) {
      key = prev_held;
      break;
    } else if ((held & cmd_key) ||
               ((held & ~chord_keys) == 0)) {
      continue;
    } else if (held) {
      key = held;
      break;
    }
  }

  nds_clear_prompt();

  cmd = nds_get_config_cmd(key);

  if (cmd.f_char < 0) {
    return;
  }

  command[0] = cmd.f_char;
  command[1] = '\0';

  if (! nds_input_buffer_is_empty()) {
    strcat(command, nds_input_buffer_shiftall());

    DEBUG_PRINT("cmd: %s\n", command);
    sprintf(buf, "Mapped %s to %s x%s.", nds_key_to_string(key), cmd.name, command);
  } else {
    sprintf(buf, "Mapped %s to %s.", nds_key_to_string(key), cmd.name);
  }

  nds_add_keymap_entry(key, command);

  clear_nhwindow(WIN_MESSAGE);
  putstr(WIN_MESSAGE, ATR_NONE, buf);

  nds_save_key_config();

  nds_flush(0);
}
示例#8
0
int main()
{	
	
	int textureID;
	int i;
	float rotateX = 0.0;
	float rotateY = 0.0;

	//set mode 0, enable BG0 and set it to 3D
	videoSetMode(MODE_0_3D);

	// initialize gl
	glInit();
	
	//enable textures
	glEnable(GL_TEXTURE_2D);
	
	//this should work the same as the normal gl call
	glViewport(0,0,255,191);
	
	// enable antialiasing
	glEnable(GL_ANTIALIAS);
	
	// setup the rear plane
	glClearColor(0,0,0,31); // BG must be opaque for AA to work
	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
	glClearDepth(0x7FFF);

	vramSetBankB(VRAM_B_LCD);
	REG_DISPCAPCNT = 
			DCAP_MODE(DCAP_MODE_BLEND) //blend source A and source B
		//|	DCAP_SRC_ADDR //this is not used since we are setting the display to render from VRAM
		|	DCAP_SRC_B(DCAP_SRC_B_VRAM)
		|	DCAP_SRC_A(DCAP_SRC_A_3DONLY)
		|	DCAP_SIZE(DCAP_SIZE_256x192)
		|	DCAP_OFFSET(0) //where to write the captured data within our chosen VRAM bank
		|	DCAP_BANK(DCAP_BANK_VRAM_B)
		|	DCAP_B(12) //blend mostly from B to make a very dramatic effect
		|	DCAP_A(4) //and blend only a little bit from the new scene
		;
	//but, dramatic effects tend to leave some garbage on the screen since the precision of the math is low,
	//and we're not putting a lot of dampening on the effect.
	//a more realistic value might be 8 and 8, but perhaps in a more complex 3d scene the garbage isn't such a bad thing
	//since the scene is changing constantly

	DisplayEnableMotionBlur();
	bool displayBlurred = true;


	vramSetBankA(VRAM_A_TEXTURE);

	glGenTextures(1, &textureID);
	glBindTexture(0, textureID);
	glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, (u8*)texture_bin);
	
	
	//any floating point gl call is being converted to fixed prior to being implemented
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(70, 256.0 / 192.0, 0.1, 40);
	
	gluLookAt(	0.0, 0.0, 1.0,		//camera possition 
				0.0, 0.0, 0.0,		//look at
				0.0, 1.0, 0.0);		//up
	
	while(1) {
		
		glLight(0, RGB15(31,31,31) , 0,				  floattov10(-1.0),		 0);
		glLight(1, RGB15(31,0,31),   0,				  floattov10(1) - 1,			 0);
		glLight(2, RGB15(0,31,0) ,   floattov10(-1.0), 0,					 0);
		glLight(3, RGB15(0,0,31) ,   floattov10(1.0) - 1,  0,					 0);

		glPushMatrix();

		//move it away from the camera
		glTranslatef32(0, 0, floattof32(-1));
				
		glRotateX(rotateX);
		glRotateY(rotateY);
		
		glMatrixMode(GL_TEXTURE);
		glLoadIdentity();
		
		glMatrixMode(GL_MODELVIEW);

		glMaterialf(GL_AMBIENT, RGB15(8,8,8));
		glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
		glMaterialf(GL_SPECULAR, BIT(15) | RGB15(8,8,8));
		glMaterialf(GL_EMISSION, RGB15(5,5,5));

		//ds uses a table for shinyness..this generates a half-ass one
		glMaterialShinyness();

		//not a real gl function and will likely change
		glPolyFmt(POLY_ALPHA(31) | POLY_CULL_BACK | POLY_FORMAT_LIGHT0 | POLY_FORMAT_LIGHT1 | 
													POLY_FORMAT_LIGHT2 | POLY_FORMAT_LIGHT3 ) ;
		
		scanKeys();
		
		u16 keys = keysHeld();
		
		if((keys & KEY_UP)) rotateX += 3;
		if((keys & KEY_DOWN)) rotateX -= 3;
		if((keys & KEY_LEFT)) rotateY += 3;
		if((keys & KEY_RIGHT)) rotateY -= 3;

		if(keysDown() & KEY_A)
		{
			displayBlurred = !displayBlurred;
			if(displayBlurred)
				DisplayEnableMotionBlur();
			else 
				DisplayEnableNormal();
		}
		
		glBindTexture(0, textureID);

		//draw the obj
		glBegin(GL_QUAD);
			for(i = 0; i < 6; i++)
				drawQuad(i);
		
		glEnd();
		
		glPopMatrix(1);
			
		glFlush(0);

		swiWaitForVBlank();

		if(keys & KEY_START) break;

		//the display capture enable bit must be set again each frame if you want to continue capturing.
		REG_DISPCAPCNT |= DCAP_ENABLE;
	}

	return 0;
}//end main 
示例#9
0
int main(void)  {

	struct in_addr ip, gateway, mask, dns1, dns2;
	
	// set the mode for 2 text layers and two extended background layers
	videoSetMode(MODE_5_2D);
    vramSetBankA(VRAM_A_MAIN_BG_0x06000000);

	consoleDemoInit();
   
	PrintConsole topScreen;
	PrintConsole bottomScreen;
	
	videoSetMode(MODE_0_2D);
	videoSetModeSub(MODE_0_2D);

	vramSetBankA(VRAM_A_MAIN_BG);
	vramSetBankC(VRAM_C_SUB_BG);

	consoleInit(&topScreen, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
	consoleInit(&bottomScreen, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, false, true);
   
   consoleSelect(&bottomScreen);
   
   Keyboard *kbd = keyboardDemoInit();
   
   kbd->OnKeyPressed = OnKeyPressed;
   
   consoleSelect(&topScreen);
   
   iprintf("Connecting to WiFi...");
	
	if(!Wifi_InitDefault(WFC_CONNECT)){
		iprintf("Failed to connect!");
		exit(1);
	}
		
		iprintf("Connected\n\n");
		
		uint16 keysPressed = ~(REG_KEYINPUT);
			if(keysPressed & KEY_A){
				debug = true;
			}
		
		ip = Wifi_GetIPInfo(&gateway, &mask, &dns1, &dns2);

		while(Connected == false && debug == false) {
			char wiiIP[256];

			iprintf("Your ip: %s\n",inet_ntoa(ip));
			iprintf("Type in your Wii's IP(or /cmd for the console):\n");
			scanf("%s", wiiIP);

			if(!strcmp(wiiIP, "/cmd")){
				CMD();
				continue;
			}	

			iprintf("\nConnecting To %s\nfrom %s...", wiiIP,inet_ntoa(ip));
			
			int server = 0; server = TCP_ClientConnect(wiiIP, 8593);//TCP_ClientConnect(ip address, port)

			if(server == true){
				Connected = true;
				iprintf("Connected\n");
			}

			while(Connected == true){
				
			}
			
			iprintf("Press start to exit or click any other button to try again:\n");

			scanKeys();
			while(!keysDown()){
				scanKeys();
				if(keysPressed & KEY_START)
					exit(0);
			}

			swiWaitForVBlank();
			consoleClear();
	}
	
	int host = 0;
	int client = 0;
	if(debug == true){
		
		consoleClear();
		iprintf("Welcome To Server Screen\n");
		iprintf("Your ip: %s\n",inet_ntoa(ip));
		host = TCP_Server(PORT, PLAYERS);//TCP_Server(port, number of players)
	}
	
	while(debug == true){
		
		client = PLAYERS; client = TCP_GetClient(host);//TCP_GetClient(host socket)
		if(!clientForServer == 4){
			clientForServer++;
			iprintf("Client connected(%d of %d)\n", clientForServer,PLAYERS);
			iprintf("Client id: %d\n", client);
		}
		
	}

   return 0;
}
示例#10
0
文件: main.c 项目: fagensden/dslink
//---------------------------------------------------------------------------------
int main(void) {
//---------------------------------------------------------------------------------

	initDisplay();

	kprintf("dslink ... connecting ...\n");

	if(!Wifi_InitDefault(WFC_CONNECT)) {
		kprintf(" Failed to connect!\n");
		waitButtonA();
		return 0;
	}

	struct in_addr ip, gateway, mask, dns1, dns2;

	ip = Wifi_GetIPInfo(&gateway, &mask, &dns1, &dns2);
	kprintf("Connected: %s\n",inet_ntoa(ip));
	
	int sock_udp = socket(PF_INET, SOCK_DGRAM, 0);
	struct sockaddr_in sa_udp, sa_udp_remote;

	sa_udp.sin_family = AF_INET;
	sa_udp.sin_addr.s_addr = INADDR_ANY;
	sa_udp.sin_port = htons(17491);

	if(bind(sock_udp, (struct sockaddr*) &sa_udp, sizeof(sa_udp)) < 0) {
		kprintf(" UDP socket error\n");
		waitButtonA();
		return 0;
	}

	struct sockaddr_in sa_tcp;
	sa_tcp.sin_addr.s_addr=INADDR_ANY;
	sa_tcp.sin_family=AF_INET;
	sa_tcp.sin_port=htons(17491);
	int sock_tcp=socket(AF_INET,SOCK_STREAM,0);
	bind(sock_tcp,(struct sockaddr *)&sa_tcp,sizeof(sa_tcp));
	int i=1;
	ioctl(sock_tcp,FIONBIO,&i);
	ioctl(sock_udp,FIONBIO,&i);
	listen(sock_tcp,2);

	int dummy, sock_tcp_remote;
	char recvbuf[256];

	while(1) {
		int len = recvfrom(sock_udp, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*) &sa_udp_remote, &dummy);

		if (len!=-1) {
			if (strncmp(recvbuf,"dsboot",strlen("dsboot")) == 0) {
				int respSock = socket(PF_INET, SOCK_DGRAM, 0);
				sa_udp_remote.sin_family=AF_INET;
				sa_udp_remote.sin_port=htons(17491);
				sendto(respSock, "bootds", strlen("bootds"), 0, (struct sockaddr*) &sa_udp_remote,sizeof(sa_udp_remote));
			}
		}

		sock_tcp_remote = accept(sock_tcp,(struct sockaddr *)&sa_tcp,&dummy);
		if (sock_tcp_remote != -1) {
			loadNDS(sock_tcp_remote,sa_tcp.sin_addr.s_addr);
			closesocket(sock_tcp_remote);
		}
		swiWaitForVBlank();
		scanKeys();
		if (keysDown() & KEY_START) break;
	}
	return 0;
}
示例#11
0
int main(int argc, char *argv[]) {
    /* Quickly enable the ANSI console */
    consoleDemoInit();

    int nb_a = 0;
    int nb_b = 0;
    int nb_x = 0;
    int nb_y = 0;

    int nb_l = 0;
    int nb_r = 0;

    int nb_up = 0;
    int nb_down = 0;
    int nb_left = 0;
    int nb_right = 0;
    volatile int frame = 0;
    while(1) {
        frame++;
        scanKeys();

        // Clear screen
        iprintf("\x1b[2J");
        printf("Frame:%d\n", frame);

        {
            printf("Pressed:\n");
            int keys = keysHeld();
            printf("A:%d B:%d X:%d Y:%d L:%d R:%d \n",
                   bool(keys & KEY_A),
                   bool(keys & KEY_B),
                   bool(keys & KEY_X),
                   bool(keys & KEY_Y),
                   bool(keys & KEY_L),
                   bool(keys & KEY_R)
                  );
            printf("^:%d v:%d <:%d >:%d \n",
                   bool(keys & KEY_UP),
                   bool(keys & KEY_DOWN),
                   bool(keys & KEY_LEFT),
                   bool(keys & KEY_RIGHT)
                  );
        }

        {
            printf("Counter:\n");
            int keys = keysDown();
            nb_a += bool(keys & KEY_A);
            nb_b += bool(keys & KEY_B);
            nb_x += bool(keys & KEY_X);
            nb_y += bool(keys & KEY_Y);
            nb_r += bool(keys & KEY_R);
            nb_l += bool(keys & KEY_L);
            printf("A:%d B:%d X:%d Y:%d L:%d R:%d\n",
                   nb_a,
                   nb_b,
                   nb_x,
                   nb_y,
                   nb_l,
                   nb_r
                  );
            nb_up += bool(keys & KEY_UP);
            nb_down += bool(keys & KEY_DOWN);
            nb_left += bool(keys & KEY_LEFT);
            nb_right += bool(keys & KEY_RIGHT);
            printf("^:%d v:%d <:%d >:%d \n",
                   nb_up,
                   nb_down,
                   nb_left,
                   nb_right
                  );
        }

        PA_CheckLid();
        swiWaitForVBlank();
    }

    return 0;
}
示例#12
0
void help(void *fonts) {
	FontSet *fontset = (FontSet *)fonts;
	u8 page = 0;
	touchPosition stylus;

	Canvas buffer_top(SCREEN_WIDTH, SCREEN_HEIGHT);
	Canvas buffer_bottom(SCREEN_WIDTH, SCREEN_HEIGHT);

	Button button_prev(&screen_bottom, fontset->large_font, "<<");
	Button button_next(&screen_bottom, fontset->large_font, ">>");
	Button button_back(&screen_bottom, fontset->large_font, "Back");

	button_prev.set_colors(BUTTON_COLORS, BUTTON_PRESSED_COLORS);
	button_next.set_colors(BUTTON_COLORS, BUTTON_PRESSED_COLORS);
	button_back.set_colors(BUTTON_COLORS, BUTTON_PRESSED_COLORS);

	button_prev.set_width(32);
	button_next.set_width(32);
	button_back.set_width(SCREEN_WIDTH - 84);

	button_prev.set_height(32);
	button_next.set_height(32);
	button_back.set_height(32);

	button_prev.set_position(5, SCREEN_HEIGHT - 37);
	button_next.set_position(SCREEN_WIDTH - 37, SCREEN_HEIGHT - 37);
	button_back.set_position(42, SCREEN_HEIGHT - 37);

	print_help_page((FontSet *)fonts, page, &buffer_top, &buffer_bottom);
	buffer_top.copy(&screen_top);
	buffer_bottom.copy(&screen_bottom);

	button_prev.disable();

	button_prev.draw();
	button_next.draw();
	button_back.draw();

	while (1) {
		scanKeys();
		touchRead(&stylus);

		if (button_prev.update(stylus) == BUTTON_CLICKED) {
			if (page > 0) {
				page--;

				print_help_page((FontSet *)fonts, page, &buffer_top, &buffer_bottom);
				buffer_top.copy(&screen_top);
				buffer_bottom.copy(&screen_bottom);

				if (page == 0) {
					button_prev.disable();
				}

				button_next.enable();

				button_prev.draw();
				button_next.draw();
				button_back.draw();
			}
		}

		if (button_next.update(stylus) == BUTTON_CLICKED) {
			if (page < NUM_PAGES - 1) {
				page++;

				print_help_page((FontSet *)fonts, page, &buffer_top, &buffer_bottom);
				buffer_top.copy(&screen_top);
				buffer_bottom.copy(&screen_bottom);

				if (page == NUM_PAGES - 1) {
					button_next.disable();
				}

				button_prev.enable();

				button_prev.draw();
				button_next.draw();
				button_back.draw();
			}
		}

		if (button_back.update(stylus) == BUTTON_CLICKED) {
			break;
		}

		swiWaitForVBlank();
	}

	// Load title screen
	Image image_title(&screen_top, options.full_path("images/title.img"));
	image_title.draw(0, 0);
}
示例#13
0
int main() {

	// initialize the geometry engine
	glInit();	

	// Setup the Main screen for 3D 
	videoSetMode(MODE_0_3D);
	
	//map some vram to background for printing
	vramSetBankC(VRAM_C_MAIN_BG_0x06000000);
 
	consoleInit(0,1, BgType_Text4bpp, BgSize_T_256x256, 31,0, true, true);

	//put bg 0 at a lower priority than the text background
	bgSetPriority(0, 1);
  

 
	// enable antialiasing
	glEnable(GL_ANTIALIAS);
 
	// setup the rear plane
	glClearColor(0,0,0,31); // BG must be opaque for AA to work
	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
	glClearDepth(0x7FFF);
 
	// Set our viewport to be the same size as the screen
	glViewport(0,0,255,191);
 
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(70, 256.0 / 192.0, 0.1, 100);
 
	//ds specific, several attributes can be set here	
	glPolyFmt(POLY_ALPHA(31) | POLY_CULL_NONE);
 
	// Set the current matrix to be the model matrix
	glMatrixMode(GL_MODELVIEW);
 
	iprintf("      Hello DS World\n");
	iprintf("     www.devkitpro.org\n");
	iprintf("   www.drunkencoders.com\n");

	while (1) {
 
		DrawGLScene();
 
		// flush to screen	
		glFlush(0);
 
		// wait for the screen to refresh
		swiWaitForVBlank();

		printf("\x1b[15;5H rtri  = %f     \n", rtri);
		printf("\x1b[16;5H rquad = %f     \n", rquad);
		rtri+=0.9f;										// Increase The Rotation Variable For The Triangle ( NEW )
		rquad-=0.75f;									// Decrease The Rotation Variable For The Quad ( NEW )

		rtri  = fmodf( rtri , 360 );
		rquad = fmodf( rquad, 360 );

	}
 
	return 0;
}
示例#14
0
文件: main.c 项目: Nikolaj64/lolSnes
int main(void)
{
	int i;
	
	defaultExceptionHandler();
	
	irqEnable(IRQ_VBLANK);
	irqEnable(IRQ_HBLANK);
	
	irqSet(IRQ_VBLANK, vblank_idle);
	
	fifoSetValue32Handler(FIFO_USER_02, arm7print, NULL);
	fifoSetValue32Handler(FIFO_USER_03, sleepMode, NULL);
	
	//vramSetBankA(VRAM_A_LCD);
	videoSetMode(MODE_0_2D);

	// map some VRAM
	// bank C to ARM7, bank H for subscreen graphics
	*(vu8*)0x04000242 = 0x82;
	*(vu8*)0x04000248 = 0x81;
	
	videoSetModeSub(MODE_0_2D);
	consoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 2, 0, false, true);
	
	*(vu16*)0x0400100A = 0x0300;
	
	setBackdropColorSub(0x7C00);
	
	// configure BLDCNT so that backdrop becomes black
	*(vu16*)0x04001050 = 0x00E0;
	*(vu8*)0x04001054 = 16;
	
	// enable window 0 and disable color effects inside it
	*(vu16*)0x04001000 |= 0x2000;
	*(vu16*)0x04001048 = 0x001F;
	*(vu16*)0x0400104A = 0x003F;
	
	toggleConsole(false);
	
#ifdef NITROFS_ROM
	if (!nitroFSInit())
#else
	if (!fatInitDefault())
#endif
	{
		toggleConsole(true);
		iprintf("FAT init failed\n");
		return -1;
	}
	
	makeROMList();
	
	makeMenu();

	iprintf("lolSnes " VERSION " -- by Mega-Mario\n");
	
	for (;;)
	{
		if (keypress != 0x03FF)
		{
			if (!(keypress & 0x0040)) // up
			{
				menusel--;
				if (menusel < 0) menusel = 0;
				if (menusel < menuscroll) menuscroll = menusel;
				makeMenu();
			}
			else if (!(keypress & 0x0080)) // down
			{
				menusel++;
				if (menusel > nfiles-1) menusel = nfiles-1;
				if (menusel-21 > menuscroll) menuscroll = menusel-21;
				makeMenu();
			}
			else if ((keypress & 0x0003) != 0x0003) // A/B
			{
				strncpy(fullpath, "snes/", 5);
				strncpy(fullpath + 5, &filelist[menusel << 8], 256);
				
				if (!Mem_LoadROM(fullpath))
				{
					iprintf("ROM loading failed\n");
					continue;
				}
				
				*(vu16*)0x04001000 &= 0xDFFF;
				toggleConsole(true);
				iprintf("ROM loaded, running\n");

				CPU_Reset();
				fifoSendValue32(FIFO_USER_01, 1);
				
				swiWaitForVBlank();
				fifoSendValue32(FIFO_USER_01, 2);
				
				irqSet(IRQ_VBLANK, vblank);
				irqSet(IRQ_HBLANK, PPU_HBlank);

				swiWaitForVBlank();
				CPU_Run();
			}
			
			keypress = 0x03FF;
		}
		
		swiWaitForVBlank();
	}

	return 0;
}
示例#15
0
void Menu::Configuration()
{
    CONFIG config;
    if(!Config::Load(&config)) {
        config.port = 0;
        memset(config.ip, 0, 4);
    }

    while(1) {
        consoleClear();
        iprintf("\n CONFIGURATION\n _____________\n\n"
                " PORT: %d\n"
                " IP ADDRESS: %03d.%03d.%03d.%03d\n"
                " HOLD         A   B   X   Y\n\n"
                " <       - PORT-\n"
                " >       - PORT+\n"
                " L       - IP-\n"
                " R       - IP+\n"
                " UP/DOWN - +10/+100 (HOLD)\n"
                " _____________\n\n"
                " START   - SAVE & RETURN\n"
                " SELECT  - DON'T SAVE & RETURN", config.port, (u8)
                config.ip[0], (u8) config.ip[1], (u8) config.ip[2], (u8)
                config.ip[3]);

        while(1) {
            swiWaitForVBlank();

            scanKeys();

            int pressed = keysDown();
            int held = keysHeld();

            if(held & KEY_LEFT || pressed & KEY_LEFT) {
                if(held & KEY_UP)
                    config.port -= 10;
                else if(held & KEY_DOWN)
                    config.port -= 100;
                else
                    config.port--;

                break;
            }

            if(held & KEY_RIGHT || pressed & KEY_RIGHT) {
                if(held & KEY_UP)
                    config.port += 10;
                else if(held & KEY_DOWN)
                    config.port += 100;
                else
                    config.port++;

                break;
            }

            if(held & KEY_L || pressed & KEY_L) {
                u8 inc;
                if(held & KEY_UP)
                    inc = 10;
                else if(held & KEY_DOWN)
                    inc = 100;
                else
                    inc = 1;

                if(held & KEY_A) config.ip[0] -= inc;
                if(held & KEY_B) config.ip[1] -= inc;
                if(held & KEY_X) config.ip[2] -= inc;
                if(held & KEY_Y) config.ip[3] -= inc;

                break;
            }

            if(held & KEY_R || pressed & KEY_R) {
                int inc;
                if(held & KEY_UP)
                    inc = 10;
                else if(held & KEY_DOWN)
                    inc = 100;
                else
                    inc = 1;

                if(held & KEY_A) config.ip[0] += inc;
                if(held & KEY_B) config.ip[1] += inc;
                if(held & KEY_X) config.ip[2] += inc;
                if(held & KEY_Y) config.ip[3] += inc;

                break;
            }

            if(pressed & KEY_START) {
                Config::Write(&config);
                return;
            }

            if(pressed & KEY_SELECT) {
                return;
            }

            if(pressed & KEY_LID) {
                int s = REG_POWERCNT;
                REG_POWERCNT = 0;

                while(1) {
                    scanKeys();
                    if(keysUp() & KEY_LID) {
                        REG_POWERCNT = s;
                        break;
                    }
                }
            }
        }
    }
}
示例#16
0
//---------------------------------------------------------------------------------
int main(void) {
//---------------------------------------------------------------------------------

	const int tile_base = 0;
	const int map_base = 20;


	videoSetMode(0);	

	videoSetModeSub(MODE_5_2D);	
	vramSetBankC(VRAM_C_SUB_BG); 

	PrintConsole *console = consoleInit(0, 3, BgType_ExRotation, BgSize_ER_256x256, map_base, tile_base, false, false);

	ConsoleFont font;

	font.gfx = (u16*)fontTiles;
	font.pal = (u16*)fontPal;
	font.numChars = 95;
	font.numColors =  fontPalLen / 2;
	font.bpp = 8;
	font.asciiOffset = 32;
	font.convertSingleColor = false;
	
	consoleSetFont(console, &font);

	int bg3 = console->bgId;

	iprintf("Custom Font Demo\n");
	iprintf("   by Poffy\n");
	iprintf("modified by WinterMute and dovoto\n");
	iprintf("for libnds examples\n");

	
	unsigned int angle = 0;
    int scrollX = 0;
	int scrollY = 0;
	int scaleX = intToFixed(1,8);
	int scaleY = intToFixed(1,8);

	while(1) {
		scanKeys();
		u32 keys = keysHeld();

		if ( keys & KEY_START ) break;

		if ( keys & KEY_L ) angle+=64; 
		if ( keys & KEY_R ) angle-=64;

		if ( keys & KEY_LEFT ) scrollX++;
		if ( keys & KEY_RIGHT ) scrollX--;
		if ( keys & KEY_UP ) scrollY++;
		if ( keys & KEY_DOWN ) scrollY--;

		if ( keys & KEY_A ) scaleX++;
		if ( keys & KEY_B ) scaleX--;

		if( keys & KEY_X ) scaleY++;
		if( keys & KEY_Y ) scaleY--;

		swiWaitForVBlank();


		bgSetRotateScale(bg3, angle, scaleX, scaleY);
		bgSetScroll(bg3, scrollX, scrollY);
		bgUpdate();
	}

}
示例#17
0
void _nds_draw_scroller(nds_nhwindow_t *window, int clear)
{
  u16 *vram = (u16 *)BG_BMP_RAM(2);

  int start_x, end_x, start_y, end_y;

  int maxidx;

  start_x = (256 / 2 - (window->region.dims.width / 2));
  end_x = 256 / 2 + (window->region.dims.width / 2);

  if (window->buffer == NULL) {
    start_x -= tag_width;
    end_x += tag_width;
  }

  if (start_x < 0) {
    end_x -= start_x;
    start_x = 0;
  }

  if (window->region.dims.height > 192 - 32) {
    start_y = 16;
    end_y = 192 - 16;
  } else {
    start_y = 192 / 2 - window->region.dims.height / 2;
    end_y = 192 / 2 + window->region.dims.height / 2;
  }

  swiWaitForVBlank();

  if (window->buffer == NULL) {
    nds_menu_t *menu = window->menu;
    int cur_y = 0;
    int i;

    if (clear) {
      nds_fill(vram, MAP_COLOUR(CLR_BLACK));
    }

    if (! window->img) {
      window->img = alloc_ppm(end_x - start_x, system_font->height * TITLE_MAX_LINES);
    }

    for (i = window->topidx; (i < menu->count) && ((cur_y + menu->items[i].region.dims.height) <= (end_y - start_y)); i++) {
      if (clear || menu->items[i].refresh) {
        char tag[3] = "  ";
        int linenum = 0;
        int fg, bg;

        fg = (menu->items[i].highlighted) ? CLR_BRIGHT_GREEN : -1;
        bg = (menu->focused_item == i) ? CLR_BLUE : -1;

        window->img->height = menu->items[i].region.dims.height;

        clear_ppm(window->img, MAP_COLOUR(bg));

        if (menu->items[i].selected) {
          if (menu->items[i].count > 0) {
            sprintf(tag, "%d", menu->items[i].count);
          } else {
            strcpy(tag, "* ");
          }
        }

        for (linenum = 0; menu->items[i].title[linenum][0]; linenum++) {
          int yoffs = linenum * system_font->height;

          if (menu->items[i].id.a_int == 0) {
            draw_string(system_font,
                        menu->items[i].title[linenum],
                        window->img, 0, yoffs, 
                        fg, bg);
          } else {
            if (linenum == 0) {
              draw_string(system_font,
                          tag,
                          window->img, 0, yoffs, 
                          fg, bg);
            }

            draw_string(system_font,
                        menu->items[i].title[linenum],
                        window->img, tag_width, yoffs, 
                        fg, bg);
          }
        }

        /* 
         * Yes, this is a complete frickin' hack.  Not all items take the full
         * image height, but rather than write a new version of draw_ppm_bw that
         * allowed cropping, I just change the height of the image to match the
         * height of the item.  This effectively crops the images to the height
         * of the item, while letting us use the same ppm struct during the
         * entire rendering process, which means fewer malloc/free pairs.
         */
        draw_ppm(window->img, vram, start_x, start_y + cur_y, 256);

        menu->items[i].refresh = 0;
      }

      menu->items[i].region.start.x = start_x + tag_width;
      menu->items[i].region.start.y = start_y + cur_y;

      cur_y += menu->items[i].region.dims.height;
    } 

    window->bottomidx = i - 1;
    maxidx = menu->count - 1;

    if (menu->how == PICK_ANY) {
      draw_ppm(okay_button, vram,
               256 - okay_button->width * 2 - 8, 192 - okay_button->height,
               256);
    }
  } else {
    nds_charbuf_t *charbuf = window->buffer;
    int cur_y = 0;
    int i;

    if (! window->img) {
      window->img = alloc_ppm(end_x - start_x, end_y - start_y);
    }
    
    clear_ppm(window->img, MAP_COLOUR(CLR_BLACK));

    for (i = window->topidx; (i < charbuf->count) && (cur_y < (end_y - start_y)); i++) {
      draw_string(system_font,
                  charbuf->lines[i].text,
                  window->img, 0, cur_y,
                  -1, -1);

      cur_y += charbuf->lines[i].height;
    }

    window->bottomidx = i - 1;
    maxidx = charbuf->count - 1;

    if (clear) {
      nds_fill(vram, 254);
    }

    draw_ppm(window->img, vram, start_x, start_y, 
             256);
  }

  if (window->topidx > 0) {
    draw_ppm(up_arrow, vram, 
             256 / 2 - up_arrow->width / 2, 0, 
             256);
  }

  if (window->bottomidx < maxidx) {
    draw_ppm(down_arrow, vram, 
             256 / 2 - down_arrow->width / 2, 192 - down_arrow->height, 
             256);
  }

  draw_ppm(cancel_button, vram,
           256 - cancel_button->width, 192 - cancel_button->height,
           256);
}
示例#18
0
void fill_map(Map* map) {
	// Map
	map->map = (u16*)malloc(map->length * map->height * sizeof(u16));
	
	char filename[25];
	sprintf(filename, "efs:/level%i/map", map->id);
	
	FILE* file = fopen(filename, "r");
	int currentChar = 0;
	int n = 0;
	char c[2];
	
	if(file != NULL) {
		
		printf("\x1b[11;11HLoading...");
		
		while(currentChar != EOF) {
			currentChar = fgetc(file);
			sprintf(c, "%c", currentChar);
			if((currentChar != ',') && (currentChar != '\n')) {
				map->map[n] = (u16)atoi(c);
				n++;
			}
		}
		
		fclose(file);
	} else {
		printf("Error while reading map %i\nFilename: %s", map->id, filename);
		while(1) { swiWaitForVBlank(); }
	}
	
	// Enemies
	map->enemies = (Enemy**)malloc(119 * sizeof(Enemy*));
	
	sprintf(filename, "efs:/level%i/enemies", map->id);
	
	file = fopen(filename, "r");
	char line[MAX_SIZE] = "";
	int id = 1;
	s16 x,y = 0;
	s32 vx,vy = 1;
	
	n = 0;
	
	if(file != NULL) {
		
		printf("\x1b[11;11HLoading...");
		
		while(fgets(line, MAX_SIZE, file) != NULL) {
			sscanf(line, "%i;%hi;%hi;%i;%i", &id, &x, &y, &vx, &vy);
			map->enemies[n] = new Enemy(id, x, y, vx, vy);
			n++;
		}
		
		fclose(file);
	} else {
		printf("Error while reading enemies set %i\nFilename: %s", map->id, filename);
		while(1) { swiWaitForVBlank(); }
	}
	
	// Map params
	sprintf(filename, "efs:/level%i/params", map->id);
	
	file = fopen(filename, "r");
	
	n = 0;
	
	if(file != NULL) {
		
		printf("\x1b[11;11HLoading...");
		
		while(fgets(line, MAX_SIZE, file) != NULL) {
			sscanf(line, "%i;%i;%hi;%hi", &map->scrollX, &map->scrollY, &map->playerX, &map->playerY);
			n++;
		}
		
		fclose(file);
	} else {
		printf("Error while reading params %i\nFilename: %s", map->id, filename);
		while(1) { swiWaitForVBlank(); }
	}
}
示例#19
0
int BndsModifier::exec()
{
	/// Inicializa las 2 pantallas a negro.
	g_video->resetAllMain();
	g_video->resetAllSub();
	
	show();

	touchPosition touch;
	int pulsado;
	int pulsadoClick;
	int grosorX = 1;
	int grosorY = 2;
	bool tactil = false;
	int origenX = 0;
	int origenY = 0;
	
	/// Limites donde dibujar.
	int limXmin = 40 + 2;
	int limXmax = 256;
	int limYmin = 0;
	int limYmax = 171 - 2;
	
	u16* buffer = (u16*) bgGetGfxPtr ( g_video->backgroundMain() );
	
	/// Espera hasta que no se este pulsando en la pantalla. Nos aseguramos de
	/// no estar pintando antes de tiempo.
	while (1) {
	    scanKeys();
	    touchRead(&touch);
	    pulsado = keysHeld();
	    if (pulsado & KEY_TOUCH) {
	    } else {
		break;
	    } // end if
	} // end while


	while (1) {
	    scanKeys();
	    touchRead(&touch);
	    pulsado = keysHeld();
	    pulsadoClick = keysDown();
	    
	
	    if ((pulsado & KEY_TOUCH) && ((touch.px >= limXmin) && (touch.px <= limXmax) && (touch.py >= limYmin) && (touch.py <= limYmax)) ) {
		/// Se esta pulsando en la pantalla tactil.
		if (tactil == false) {
		    /// Se acaba de pulsar en la pantalla tactil. Se registra la posicion inicial.
		    origenX = touch.px;
		    origenY = touch.py;
		    tactil = true;
		} // end if
		
		//drawRectangle8bpp ( touch.px - (grosorX / 2), touch.py - (grosorY / 2), touch.px + (grosorX / 2), touch.py + (grosorY / 2), 1, buffer);
		drawLine(origenX, origenY, touch.px, touch.py, grosorX, grosorY, 0, buffer);
		
		/// Registra para el proximo dibujado.
		origenX = touch.px;
		origenY = touch.py;
		
	    } else {
		/// No se esta pulsando la pantalla tactil.
		tactil = false;
	    } // end if


	    if ( (pulsado & KEY_L) && (pulsado & KEY_R)) {
		/// Resetea la pantalla
		clearCanvas();
	    } // end if

	    if (pulsado & KEY_A) {
		/// Se pulsa la tecla A (aceptar).
		return 1;
	    } // end if

	    /// Si se pulsa en el boton 'aceptar'.
	    if ( (pulsadoClick & KEY_TOUCH) &&
		  (touch.px >= 180) && (touch.px <= 255 ) &&
		  (touch.py >= 175) && (touch.py <= 192 ) ) {

		  /// Se guarda la imagen en disco
		  time_t seconds;
		  seconds = time (NULL);
	    
		  string sec;
		  stringstream out;
		  out << seconds;
		  sec = out.str();
	    
		  string nombreArchivo = "tmp_ndsbulmatpv_" + sec + ".bmp.base64";
		  screenshotToBmp1BitBase64(nombreArchivo.c_str());
		  m_nombreArchivo = nombreArchivo;
	      
		  return 1;
	    } // end if

	    /// Si se pulsa en el boton 'cancelar'.
	    if ( (pulsadoClick & KEY_TOUCH) &&
		  (touch.px >= 0) && (touch.px <= 70 ) &&
		  (touch.py >= 175) && (touch.py <= 192 ) ) {
		    return -1;
	    } // end if

	    swiWaitForVBlank();
	
	} // end while

	return 0;
}
示例#20
0
int main(int _argc, char **_argv) {
    int framecount=0;
    int sramcount=0;

    argc=_argc, argv=_argv;
    defaultExceptionHandler();

    fifoSendValue32(FIFO_USER_06, (u32)ipc_region);

    DS_init(); //DS init.
#ifndef ROM_EMBEDED
    active_interface = fatInitDefault(); //init file operations to your external card.

    initNiFi();
#endif
    EMU_Init(); //emulation init.

    irqSet(IRQ_VBLANK, vblankinterrupt);
    irqEnable(IRQ_HBLANK);
    //fifoSetValue32Handler(FIFO_USER_06, aliveinterrupt, 0);
    //fifoSetValue32Handler(FIFO_USER_05, reg4015interrupt, 0);

    IPC_ALIVE = 0;
    IPC_APUIRQ = 0;
    IPC_REG4015 = 0;

    consoleinit(); //init subscreen to show chars.
    crcinit();	//init the crc table.

    //pre-alocate memory....
    //IPC_FILES = malloc(MAXFILES * 256 + MAXFILES * 4);
    //IPC_ROM = malloc(ROM_MAX_SIZE);

#ifndef ROM_EMBEDED
    if(!bootext()) {
        //chdir("/");
        do_rommenu(); //show a menu selecting rom files.
    }
#else
    do_romebd();
#endif

    //__emuflags |= PALSYNC;

    while(1) { // main loop to do the emulation
        framecount++;
        if(__emuflags & PALTIMING && global_playcount == 0) {
            framecount--;
        }
        if(debuginfo[VBLS]>59) {
            debuginfo[VBLS]-=60;
            debuginfo[1] = debuginfo[0];
            debuginfo[0] = 0;
            debuginfo[FPS]=framecount;
            framecount=0;
        }

        scanKeys();
        IPC_KEYS = keysCurrent();

        //change nsf states
        if(__emuflags & NSFFILE) {
            static int oldkey = 0;
            int keydown = IPC_KEYS & (~oldkey);
            oldkey = IPC_KEYS;

            if(keydown & KEY_LEFT) {
                if(__nsfsongno == 0) {
                    __nsfsongno = nsfheader.TotalSong-1;
                } else {
                    __nsfsongno--;
                }
            }
            if(keydown & KEY_RIGHT) {
                if(++__nsfsongno > nsfheader.TotalSong-1) {
                    __nsfsongno = 0;
                }
            }
            if(keydown & KEY_UP) {
                __nsfplay = 1;
                __nsfinit = 1;
            }
            if(keydown & KEY_DOWN) {
                __nsfplay = 0;
                Sound_reset();
            }
        }

        do_shortcuts();
        if((__emuflags & AUTOSRAM)) {
            if(__emuflags & NEEDSRAM) {
                sramcount = 1;
                __emuflags&=~NEEDSRAM;
            }
            if(sramcount > 0)
                sramcount++;
            if(sramcount > 120) {		//need auto save for sram.
                sramcount = 0;
                save_sram();
            }
        }

        touch_update(); // do menu functions.
        do_menu();	//do control menu.

        do_multi();
        if(nifi_stat == 0 || nifi_stat >= 5)
            play(); //emulate a frame of the NES game.
        else
            swiWaitForVBlank();
    }
}
示例#21
0
void PlaySeqNDS(const char* ndsFile, const u32 SSEQOffset, const u32 SSEQSize, const u32 BANKOffset, const u32 BANKSize, const u32 WAVEARC1Offset, const u32 WAVEARC1Size, const u32 WAVEARC2Offset, const u32 WAVEARC2Size, const u32 WAVEARC3Offset, const u32 WAVEARC3Size, const u32 WAVEARC4Offset, const u32 WAVEARC4Size)
{
	StopSeq();
	swiWaitForVBlank();
	swiWaitForVBlank();
	//free_seq();
	curr_seq.msg = SNDSYS_PLAYSEQ;

	if((SSEQOffset==curr_seq_offset[0])&&(SSEQSize==curr_seq_size[0]))
	{
		iprintf("SSEQ Already Loaded.\n");
	}
	else
	{
		free_pdata(&curr_seq.seq);
		curr_seq_offset[0]=SSEQOffset;
		curr_seq_size[0]=SSEQSize;
		iprintf("Loading SSEQ.\n");
		LoadNDS(&curr_seq.seq, ndsFile, SSEQOffset, SSEQSize);
	}

	if((BANKOffset==curr_seq_offset[1])&&(BANKSize==curr_seq_size[1]))
	{
		iprintf("BANK Already Loaded.\n");
	}
	else
	{
		free_pdata(&curr_seq.bnk);
		curr_seq_offset[1]=BANKOffset;
		curr_seq_size[1]=BANKSize;
		iprintf("Loading BANK.\n");
		LoadNDS(&curr_seq.bnk, ndsFile, BANKOffset, BANKSize);
	}

	if((WAVEARC1Offset==curr_seq_offset[2])&&(WAVEARC1Size==curr_seq_size[2]))
	{
		if(WAVEARC1Offset != 0)
			iprintf("WAVEARC1 Already Loaded\n");
	}
	else
	{
		free_pdata(curr_seq.war + 0);
		curr_seq_offset[2]=WAVEARC1Offset;
		curr_seq_size[2]=WAVEARC1Size;
		if(WAVEARC1Offset != 0)
		{
			iprintf("Loading WAVEARC1.\n");
			LoadNDS(curr_seq.war + 0, ndsFile, WAVEARC1Offset, WAVEARC1Size);
		}
	}
	
	if((WAVEARC2Offset==curr_seq_offset[3])&&(WAVEARC2Size==curr_seq_size[3]))
	{
		if(WAVEARC2Offset != 0)
			iprintf("WAVEARC2 Already Loaded\n");
	}
	else
	{
		free_pdata(curr_seq.war + 1);
		curr_seq_offset[3]=WAVEARC2Offset;
		curr_seq_size[3]=WAVEARC2Size;
		if(WAVEARC2Offset != 0)
		{
			iprintf("Loading WAVEARC2.\n");
			LoadNDS(curr_seq.war + 1, ndsFile, WAVEARC2Offset, WAVEARC2Size);
		}
	}

	if((WAVEARC3Offset==curr_seq_offset[4])&&(WAVEARC3Size==curr_seq_size[4]))
	{
		if(WAVEARC3Offset != 0)
			iprintf("WAVEARC3 Already Loaded\n");
	}
	else
	{
		free_pdata(curr_seq.war + 2);
		curr_seq_offset[4]=WAVEARC3Offset;
		curr_seq_size[4]=WAVEARC3Size;
		if(WAVEARC3Offset != 0)
		{
			iprintf("Loading WAVEARC3.\n");
			LoadNDS(curr_seq.war + 2, ndsFile, WAVEARC3Offset, WAVEARC3Size);
		}
	}

	if((WAVEARC4Offset==curr_seq_offset[5])&&(WAVEARC4Size==curr_seq_size[5]))
	{
		if(WAVEARC4Offset != 0)
			iprintf("WAVEARC4 Already Loaded\n");
	}
	else
	{
		free_pdata(curr_seq.war + 3);
		curr_seq_offset[5]=WAVEARC4Offset;
		curr_seq_size[5]=WAVEARC4Size;
		if(WAVEARC4Offset != 0)
		{
			iprintf("Loading WAVEARC4.\n");
			LoadNDS(curr_seq.war + 3, ndsFile, WAVEARC4Offset, WAVEARC4Size);
		}
	}

	fifoSendDatamsg(FIFO_SNDSYS, sizeof(curr_seq), (u8*) &curr_seq);
}
示例#22
0
//run 1 NES frame with FF/REW control
void play() {
    static int framecount=0;
    static int fcount = 0;
    int forward = 0;
    int backward = 0;

    do_cheat();

    global_playcount++;
    if(global_playcount > 6)
        global_playcount = 0;

    if(nifi_stat)
        __emuflags &= ~(FASTFORWARD | REWIND);		//when nifi enabled, disable the fastforward & rewind.

    forward = __emuflags & FASTFORWARD;
    backward = __emuflags & REWIND;

    if(backward) { // for rolling back... a nice function?
        swiWaitForVBlank();
        framecount++;
        if(framecount>2) {
            framecount-=3;
            if(firstsave!=lastsave) {
                lastsave--;
                if(lastsave<0)
                    lastsave=maxsaves-1;
                loadstate(freemem_start+SAVESTATESIZE*lastsave);
                EMU_Run();
            }
        }
    } else {
        if(__emuflags & SOFTRENDER) {
            if(!(forward) && (fcount >= debuginfo[6] && fcount - debuginfo[6] < 10) ) // disable VBlank to speed up emulation.
                swiWaitForVBlank();
        } else {
            if(!(forward)) {
                if(__emuflags & PALSYNC) {
                    if(__emuflags & (SOFTRENDER | PALTIMING))
                        __emuflags ^= PALSYNC;
                    if(REG_VCOUNT < 190) {
                        swiWaitForVBlank();
                    }
                }
                else {
                    if((!(__emuflags & ALLPIXEL)) || (all_pix_start != 0))
                        swiWaitForVBlank();
                }
            }
        }

        if(!(__emuflags & PALTIMING && global_playcount == 6)) {
            EMU_Run(); //run a frame
            framecount++;
            if(framecount>8) {	//save state every 9th frame
                framecount-=9;
                savestate(freemem_start+SAVESTATESIZE*lastsave);
                lastsave++;
                if(lastsave>=maxsaves)
                    lastsave=0;
                if(lastsave==firstsave) {
                    firstsave++;
                    if(firstsave>=maxsaves)
                        firstsave=0;
                }
            }
        }
        else {
            if((__emuflags & PALTIMING) && (__emuflags & ALLPIXEL) && !(__emuflags & SOFTRENDER))
                swiWaitForVBlank();
        }
    }

    if(__emuflags & SOFTRENDER) {
        __emuflags &= ~AUTOSRAM;
        __rendercount++;
        if(SOFT_FRAMESKIP <= 1 ||__rendercount == 1) {
            if(__emuflags & ALLPIXEL)
                render_sub();
            render_all();
        }
        if(!(forward) && __rendercount >= SOFT_FRAMESKIP)
            __rendercount = 0;
        if((forward) && __rendercount > 16)
            __rendercount = 0;
    } else if(__emuflags & ALLPIXEL) {
        render_sub();
    }

    fcount++;
    if(fcount > 59)
        fcount = 0;

    __emuflags &= ~(FASTFORWARD | REWIND);
}
示例#23
0
int main(void)
{
	aplist *head = NULL;
	aplist *cur;
	
	bool attached = true;
	// change this to false if you are only testing servos
	bool wifi_scan = true;
	// change this for emulator 
	bool emulate = false;

	float pain = 0.9f;
	time_t update = 0;
	uint8 num;
	uint8 servo_pos = 0;
	uint8 current_servo = 1;
	unsigned char SERVO_PINS[3] = { SERVO_PIN1 ,SERVO_PIN2 ,SERVO_PIN3 } ;

	uint16 val[3] = { 0 };
	uint8 i;

	touchPosition touch;
	
	videoSetMode(MODE_4_2D);
	vramSetBankA(VRAM_A_MAIN_BG);

	// set up our bitmap background
	bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
	decompress(cclogoBitmap, BG_GFX,  LZ77Vram);

	// initialise lower screen for textoutput
	consoleDemoInit();

	if (emulate == false) {	

	  iprintf("Initializing WiFi.. ");
	  Wifi_InitDefault(false);
	  while (Wifi_CheckInit() != 1) {
	  }
	  Wifi_ScanMode();
	  iprintf("done\n");
	  
	  iprintf("Initializing DS brut.. ");
	  uart_init();
	  uart_set_spi_rate(1000);
	  iprintf("done\n\n\n");

	  iprintf("Using servo pins: %u %u %u\n\n", SERVO_PIN1, SERVO_PIN2, SERVO_PIN3);
	  iprintf("Default pain multiplier: %.2f\n\n", pain);
	  swiDelay(60000000);
	  while (1) {
		  
		  scanKeys();
		  touchRead(&touch);	
		  if (keysDown() & KEY_X) {
			  if (attached) {
				  servo_detach(SERVO_PIN1);
				  servo_detach(SERVO_PIN2);
				  servo_detach(SERVO_PIN3);
				  attached = false;
			  } else {
				  attached = true;
			  }
		  }
		  if (keysDown() & KEY_A) {
			  if (attached) {
				uint8 i = 0;
				for (i=0;i<3;i++) {
					servo_set(SERVO_PINS[i],0);
				}
			  }
			  //servo_set(SERVO_PIN1, 180-((rand() % 100)+(rand() % 50)+(rand() % 25)));
			  //servo_set(SERVO_PIN2, 180-((rand() % 100)+(rand() % 50)+(rand() % 25)));
			  //servo_set(SERVO_PIN3, 180-((rand() % 100)+(rand() % 50)+(rand() % 25)));
		  }
		  if (keysDown() & KEY_B) {
			  if (wifi_scan == true)	{
				  wifi_scan = false;
			  }
			  else {
				  wifi_scan = true;
			  }
		  }
		  if (keysDown() & KEY_DOWN) {
			  pain -= 0.1f;
			  if (pain < 0.0f) {
				  pain = 0.0f;
			  }
			  update = time(NULL);
		  }
		  if (keysDown() & KEY_UP) {
			  pain += 0.1f;
			  if (2.0f < pain) {
				  pain = 2.0f;
			  }
			  update = time(NULL);
		  }
		  if (keysDown() & KEY_L) {
			  current_servo += 1;
			  if (current_servo > 3) {
				  current_servo = 1;
			  }
		  }
		  consoleClear();
		  if (wifi_scan == true) {
			num = 0;
			cur = head;
			iprintf("\n");
			while (cur && num < 15) {
				// display
				if (!(cur->flags & 0x2)) {
					cur = cur->next;
					continue;
				}
				iprintf("%2u ", num);
				if (cur->ssid[0] == '\0') {
					iprintf("%02x%02x%02x%02x%02x%02x", cur->mac[0], cur->mac[1], cur->mac[2], cur->mac[3], cur->mac[4], cur->mac[5]);
				} else {
					iprintf("%s", cur->ssid);
				}
				iprintf(" @ %u", cur->rssi);
				if ((cur->flags & 0x06) == 0x06) {
					iprintf(" WPA");
				} else if (cur->flags & 0x02) {
					iprintf(" WEP");
				}
				
				// calculate servo commands
				if (attached && num < 3) {
						val[num] = (uint16)(cur->rssi*pain);
						if (180 < val[num]) {
							val[num] = 180;
						}
						iprintf(" %u", val[num]);
				}
				
				iprintf("\n");
				if (num == 2) {
					iprintf ("\n");
				}
				
				num++;
				cur = cur->next;
			}
			iprintf("\n");
			if (time(NULL) < update+3) {
				printf("\npain multiplier: %.2f\n", pain);
			}
			
			// set the servo to zero if we don't have enough wifi nodes
			for (i=num; i<3; i++) {
				val[i] = 0;
			}
			
			if (attached) {
				servo_set(SERVO_PIN1, (uint8)val[0]);
				servo_set(SERVO_PIN2, 180-(uint8)val[1]);
				servo_set(SERVO_PIN3, (uint8)val[2]);
			}
			updateApList(&head, 0x00, NULL, NULL);
			sortApList(&head, false);

		  }

		  if (KEY_TOUCH && attached && !wifi_scan) {
			  servo_pos = (touch.rawx / 3850.) * 180;	
			  iprintf ("servo pos x: %d;", servo_pos);
			  iprintf ("\n");
			  servo_set(SERVO_PINS[current_servo-1],servo_pos);
			  iprintf ("current servo: %d", current_servo);
			  iprintf ("\n\n");
		  }
		  
		  
		  swiWaitForVBlank();
	  }
 	}	
while (1) {
		  swiWaitForVBlank();
}
	return 0;
}
示例#24
0
// ========================***************************==============================
void fileSelect(const char *startdir, char *out_dir, char *out_fname, netbuf *buf,
  bool allow_cancel, bool allow_up)
{
	bool select = false;
	static int size_list = 18;
	
	int num_files = 0;
	int sel_file = 0;
	int first_file = 0;
	
	// get list of files in current dir
	if (buf)
		ftpGetFileList("/", buf, num_files);
	else
		fileGetFileList(startdir, num_files);
	filePrintFileList(startdir, first_file, sel_file, num_files, allow_cancel);
		
	while (!select) {
		// get_event
		uint32 keys = keysCurrent();
		
		// handle_event
		if (keys & KEY_DOWN) {
			if (sel_file < num_files-1) {
				sel_file++;
				if (sel_file >= first_file + size_list - 1)
					first_file = sel_file - (size_list - 1);
				filePrintFileList(startdir, first_file, sel_file, num_files, allow_cancel);
			} else {
				// wrap around to top of list
				sel_file = 0;
				first_file = 0;
				filePrintFileList(startdir, first_file, sel_file, num_files, allow_cancel);
			}
		} else if (keys & KEY_UP) {
			if (sel_file > 0) {
				sel_file--;
				if (sel_file < first_file)
					first_file = sel_file;
				filePrintFileList(startdir, first_file, sel_file, num_files, allow_cancel);
			} else {
				// wrap around to bottom of list
				sel_file = num_files - 1;
				first_file = sel_file - (size_list - 1);
				filePrintFileList(startdir, first_file, sel_file, num_files, allow_cancel);
			}
		} else if (keys & KEY_A) {
			// get selected file name
			char *buf2 = (char*)data;
			char fname[128];
			for (int i = 0; i < sel_file; i++) {
				buf2 = strchr(buf2, '\n') + 1;
			}
			char c;
			sscanf(buf2, "%c%[^\n]", &c, fname); // gets 'd' or 'f' - dir or file			
			// special cases
			if (stricmp(fname, ".") == 0)
				// don't do anything
				continue;
			if (stricmp(fname, "..") == 0) {
				// return to parent function (usually results in "back to higher level")
				while (keysCurrent() & (KEY_A | KEY_B));
				if (!allow_up)
					continue;
				if (buf)
					FtpChdir("..", buf);
				return;
			}
			
			// get selected file properties
			char fullname[512];
			sprintf(fullname, "%s%s", startdir, fname);
			struct stat statbuf;
			stat(fullname, &statbuf);
			if (c == 'd') {
				char fullpath[512];
				sprintf(fullpath, "%s%s/", startdir, fname);
				if (buf)
					FtpChdir(fname, buf);
				fileSelect(fullpath, out_dir, out_fname, buf, allow_cancel, true);
				if ((keysCurrent() & (KEY_L | KEY_R)) && allow_cancel)
					return;
				while (keysCurrent() & (KEY_A | KEY_B));
				
				// did we select a file? if so, keep returning to parent calling function
				if (strlen(out_fname))
					return;
				
				// we did not select anything, so regenerate the old list
				num_files = 0;
				if (buf)
					ftpGetFileList("/", buf, num_files);
				else
					fileGetFileList(startdir, num_files);
				filePrintFileList(startdir, first_file, sel_file, num_files, allow_cancel);
				continue;
			} else {
				sprintf(out_dir, "%s", startdir);
				sprintf(out_fname, "%s", fname);
				while (keysCurrent() & (KEY_A | KEY_B));
				return;
			}
		} else if (keys & KEY_B) {
			if (!allow_up)
				continue;
			if (buf)
				FtpChdir("..", buf);
			return;
		} else if (keys & (KEY_L | KEY_R)) {
			if (allow_cancel) {
				sprintf(out_dir, "%s", startdir);
				out_fname[0] = 0;
				return;
			}
		}
		
		for (int i = 0; i < 5; i++)
			swiWaitForVBlank();
	}
}
示例#25
0
文件: main.cpp 项目: odelot/nds
int main() {
    /* Turn on the 2D graphics core. */
    powerOn(POWER_ALL_2D);

    /*
     *  Configure the VRAM and background control registers.
     *
     *  Place the main screen on the bottom physical screen. Then arrange the
     *  VRAM banks. Next, confiure the background control registers.
     */
    lcdMainOnBottom();
    initVideo();
    initBackgrounds();
    consoleDemoInit();
    

    /* Set up a few sprites. */
    SpriteInfo spriteInfo[SPRITE_COUNT];
    oam = new OAMTable();
    initOAM(oam);
    //initSprites(oam, spriteInfo);
    OAM_Manager oam_manager (spriteInfo,oam);
    Jogador jogador (spriteInfo, &oam_manager);
    jogador.initGfx ();

    NPC npc (spriteInfo, &oam_manager);
    npc.initGfx ();


    /*
     *  Update the OAM.
     *
     *  We have to copy our copy of OAM data into the actual OAM during VBlank
     *  (writes to it are locked during other times).
     */
    swiWaitForVBlank();
    updateOAM(oam);

    /* Loop forever so that the Nintendo DS doesn't reboot upon program
     * completion. */
    controle.reset ();
    for (;;) {
        consoleClear ();
        
        /* Update the game state. */
        updateInput();
        handleInput();

        jogador.update (&controle);
        npc.update (NULL);

       
        
        /*
         *  Update the OAM.
         *
         *  We have to copy our copy of OAM data into the actual OAM during
         *  VBlank (writes to it are locked during other times).
         */
        swiWaitForVBlank();
        updateOAM(oam);
    }

    return 0;
}
示例#26
0
文件: main.cpp 项目: jkroll20/libflux
int main(void)
{
    touchPosition touch;

    videoSetModeSub(MODE_0_2D | DISPLAY_BG0_ACTIVE);	//sub bg 0 will be used to print text
    vramSetBankC(VRAM_C_SUB_BG);

    SUB_BG0_CR = BG_MAP_BASE(31);

    BG_PALETTE_SUB[255] = RGB15(31,31,31);	//by default font will be rendered with color 255

    //consoleInit() is a lot more fluxible but this gets you up and running quick
    consoleInitDefault((u16*)SCREEN_BASE_BLOCK_SUB(31), (u16*)CHAR_BASE_BLOCK_SUB(0), 16);
    
/////////////
    powerON(POWER_ALL);

    // set mode 0, enable BG0 and set it to 3D
    videoSetMode(MODE_0_3D);
    vramSetBankA(VRAM_A_TEXTURE);

    // irqs are nice
    irqInit();
    irqEnable(IRQ_VBLANK);
    
    // initialize gl
    glInit();
    
    // setup the rear plane
    glClearColor(2, 4, 3, 16);
    glClearDepth(GL_MAX_DEPTH);
    
    // this should work the same as the normal gl call
    glViewPort(0,0, 255,191);
    
    glPolyFmt(POLY_ALPHA(31) | POLY_CULL_NONE);
    
    glMatrixMode(GL_PROJECTION);
    
    glLoadIdentity();
    //~ glOrtho(0, 1, 192.0/256.0, 0, -10, 10);
    glOrthof32(0, 1<<12, (192<<12)/256, 0, -10<<12, 10<<12);
    
    REG_POWERCNT^= POWER_SWAP_LCDS;
/////////////


    flux_init();
    create_frame_groups();
    create_button_groups();
    create_titleframe();
    
    dmaCopy(fluxcolors, syscol_table, sizeof(fluxcolors));
    
    dword rc1= create_rect(NOPARENT, 20,20, 128,96, 0x808080);
    dword rc= create_rect(NOPARENT, 10,10, 128,96, 0x404040|TRANSL_3);
    dword frm= clone_frame("titleframe", rc);
    clone_frame("titleframe", rc1);
    //~ clone_group("button", rc, 10,30, 30,14, ALIGN_LEFT|ALIGN_TOP);

    create_rect(rc, 10,10, 10,10, 0xFFFFFF|TRANSL_1);
    create_rect(rc, 20,10, 10,10, 0xFFFFFF|TRANSL_2);
    create_rect(rc, 30,10, 10,10, 0xFFFFFF|TRANSL_3);
    create_rect(rc, 10,15, 30,10, 0xFFFFFF|TRANSL_1);
    
    create_text(rc, 10,30, 40,40, "Text! Space!\nNewline!", 0xFFFFFF, FONT_DEFAULT);
    
    bool redraw_all= true;
    bool touch_wasdown= false;
    int lasttouch_x, lasttouch_y;
    while(1)
    {
	scanKeys();
    	u32 keysheld= keysHeld();
	u32 keysdown= keysDown();
	touch= touchReadXY();
	
	if(keysdown&KEY_A)
	{
	    redraw_all^= 1;
	    iprintf("redraw each frame: %s\n", redraw_all? "on": "off");
	}
	
	if(keysdown&KEY_B)
	{
	    do_texalpha^= 1;
	    iprintf("texture alpha: %s\n", do_texalpha? "on": "off");
	}
	
	if(touch.x || touch.y)
	{
	    flux_mouse_event(touch.px, touch.py, 1);
	    lasttouch_x= touch.px, lasttouch_y= touch.py;
	    touch_wasdown= true;
	}
	else
	{
	    if(touch_wasdown) flux_mouse_event(lasttouch_x, lasttouch_y, 0);
	    touch_wasdown= false;
	}
	    

	flux_tick();
	if(redraw_all)
	{
	    redraw_rect(&viewport);
	    update_rect(&viewport);
	}
	
	swiWaitForVBlank();
    }

    return 0;
}
示例#27
0
int main()
{	
	
	int textureID;
	int i;
	float rotateX = 0.0;
	float rotateY = 0.0;

	//set mode 0, enable BG0 and set it to 3D
	videoSetMode(MODE_0_3D);

	// initialize gl
	glInit();
	
	//enable textures
	glEnable(GL_TEXTURE_2D);
	
	//this should work the same as the normal gl call
	glViewport(0,0,255,191);
	
	// enable antialiasing
	glEnable(GL_ANTIALIAS);
	
	// setup the rear plane
	glClearColor(0,0,0,31); // BG must be opaque for AA to work
	glClearPolyID(63); // BG must have a unique polygon ID for AA to work
	glClearDepth(0x7FFF);
	
	vramSetBankA(VRAM_A_TEXTURE);

	glGenTextures(1, &textureID);
	glBindTexture(0, textureID);
	glTexImage2D(0, 0, GL_RGB, TEXTURE_SIZE_128 , TEXTURE_SIZE_128, 0, TEXGEN_TEXCOORD, (u8*)texture_bin);
	
	
	//any floating point gl call is being converted to fixed prior to being implemented
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(70, 256.0 / 192.0, 0.1, 40);
	
	gluLookAt(	0.0, 0.0, 1.0,		//camera possition 
				0.0, 0.0, 0.0,		//look at
				0.0, 1.0, 0.0);		//up
	
	while(1) {
		
		glLight(0, RGB15(31,31,31) , 0,				  floattov10(-1.0),		 0);
		glLight(1, RGB15(31,0,31),   0,				  floattov10(1) - 1,			 0);
		glLight(2, RGB15(0,31,0) ,   floattov10(-1.0), 0,					 0);
		glLight(3, RGB15(0,0,31) ,   floattov10(1.0) - 1,  0,					 0);

		glPushMatrix();

		//move it away from the camera
		glTranslate3f32(0, 0, floattof32(-1));
				
		glRotateX(rotateX);
		glRotateY(rotateY);
		
		glMatrixMode(GL_TEXTURE);
		glLoadIdentity();
		
		glMatrixMode(GL_MODELVIEW);

		glMaterialf(GL_AMBIENT, RGB15(8,8,8));
		glMaterialf(GL_DIFFUSE, RGB15(16,16,16));
		glMaterialf(GL_SPECULAR, BIT(15) | RGB15(8,8,8));
		glMaterialf(GL_EMISSION, RGB15(5,5,5));

		//ds uses a table for shinyness..this generates a half-ass one
		glMaterialShinyness();

		//not a real gl function and will likely change
		glPolyFmt(POLY_ALPHA(31) | POLY_CULL_BACK | POLY_FORMAT_LIGHT0 | POLY_FORMAT_LIGHT1 | 
													POLY_FORMAT_LIGHT2 | POLY_FORMAT_LIGHT3 ) ;
		
		scanKeys();
		
		u16 keys = keysHeld();
		
		if((keys & KEY_UP)) rotateX += 3;
		if((keys & KEY_DOWN)) rotateX -= 3;
		if((keys & KEY_LEFT)) rotateY += 3;
		if((keys & KEY_RIGHT)) rotateY -= 3;
		
		glBindTexture(0, textureID);

		//draw the obj
		glBegin(GL_QUAD);
			for(i = 0; i < 6; i++)
				drawQuad(i);
		
		glEnd();
		
		glPopMatrix(1);
			
		glFlush(0);

		swiWaitForVBlank();
	}

	return 0;
}//end main 
示例#28
0
文件: main.c 项目: 0xtob/dsmi
int main(void)
{
	lcdMainOnBottom();
	
	// Register vblank IRQ
	irqEnable(IRQ_VBLANK);
	
	// Set banks
	vramSetMainBanks(VRAM_A_MAIN_BG_0x06000000, VRAM_B_MAIN_BG_0x06020000,
	           VRAM_C_SUB_BG_0x06200000 , VRAM_D_LCD);
	
	// Set modes
	videoSetMode(MODE_5_2D);
	videoSetModeSub(MODE_5_2D);
	
	// sub display
	int sub_bg3 = bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 2, 0);
	bgSetPriority(sub_bg3, 1);
	
#ifdef DEBUG
	// Text bg on sub
	PrintConsole *pc = consoleInit(NULL, 0, BgType_Text4bpp, BgSize_T_256x256, 4, 0, false);
	bgSetPriority(pc->bgId, 0);
	BG_PALETTE_SUB[255] = RGB15(31,0,31);
#endif
	// The main display is for graphics.
	// Set up an extended rotation background for background gfx
	int main_bg2 = bgInit(2, BgType_Bmp16, BgSize_B16_256x256, 2, 0);
	bgSetPriority(main_bg2, 1);
	
	// Set up tile mode for the keyboard
	int main_bg0 = bgInit(0, BgType_Text4bpp, BgSize_T_256x256, 8, 0);
	bgSetPriority(main_bg0, 0);
	
	// Clear tile mem
	u16 *tile_ram = (u16*)bgGetGfxPtr(main_bg0);
	u32 i;
	for(i=0; i<(32*1024); ++i) {
		tile_ram[i] = 0;
	}
	
	// Copy tiles and palettes
	dmaCopy((uint16*)keyboard_Palette, (uint16*)BG_PALETTE, 32);
	dmaCopy((uint16*)keyboard_fullnotehighlight_Palette, (uint16*)BG_PALETTE+16, 32);
	dmaCopy((uint16*)keyboard_halfnotehighlight_Palette, (uint16*)BG_PALETTE+32, 32);
	dmaCopy((uint16*)keyboard_Tiles, (uint16*)CHAR_BASE_BLOCK(0), 736);
	
	// Fill screen with empty tiles
	u16 *map = (u16*)bgGetMapPtr(main_bg0);
	for(i=0;i<768;++i) {
		map[i] = 28;
	}
	
	// Draw the backgrounds
	main_vram = (u16*)bgGetGfxPtr(main_bg2);
	for(i=0; i<192*256; ++i) {
		main_vram[i] = ((uint16*)bg_main)[i];
	}
	
	u16 *sub_vram = (u16*)bgGetGfxPtr(sub_bg3);
	for(i=0; i<192*256; ++i) {
		sub_vram[i] = ((uint16*)bg_sub)[i];
	}

	
	displayChannel(channel);
	displayOctave(baseOctave);
	
	drawString("connecting ...", 89, 96);
	
	iprintf("Connecting\n");
	int res = dsmi_connect();
	if(res == 1) {
		iprintf("OK\n");
	} else {
		iprintf("Oh no! Could not connect\n");
		drawString("failed!", 180, 96);
		while(1);
	}
	
	iprintf("Ready.\n");

	// Copy the keyboard to the screen
	kb_map = (u16*)bgGetMapPtr(main_bg0);
	u8 x, y;
	for(y=0; y<5; ++y) {
		for(x=0; x<28; ++x) {
			kb_map[32*(y+keyb_ypos)+(x+keyb_xpos)] = keyboard_Map[29*y+x+1];
		}
	}

	while(1) {
		VblankHandler();
		swiWaitForVBlank();
	}

	return 0;
}
示例#29
0
//---------------------------------------------------------------------------------
Wifi_AccessPoint* findAP(void){
//---------------------------------------------------------------------------------

	int selected = 0;  
	int i;
	int count = 0, displaytop = 0;

	static Wifi_AccessPoint ap;

	Wifi_ScanMode(); //this allows us to search for APs

	int pressed = 0;
	do {
		scanKeys();

		//find out how many APs there are in the area
		count = Wifi_GetNumAP();


		consoleClear();

		iprintf("%d APs detected\n\n", count);

		int displayend = displaytop + 10;
		if (displayend > count) displayend = count;

		//display the APs to the user
		for(i = displaytop; i < displayend; i++) {
			Wifi_AccessPoint ap;

			Wifi_GetAPData(i, &ap);

			// display the name of the AP
			iprintf("%s %.29s\n  Wep:%s Sig:%i\n", 
				i == selected ? "*" : " ", 
				ap.ssid, 
				ap.flags & WFLAG_APDATA_WEP ? "Yes " : "No ",
				ap.rssi * 100 / 0xD0);

		}

		pressed = keysDown();
		//move the selection asterick
		if(pressed & KEY_UP) {
			selected--;
			if(selected < 0) {
				selected = 0;
			}
			if(selected<displaytop) displaytop = selected;
		}

		if(pressed & KEY_DOWN) {
			selected++;
			if(selected >= count) {
				selected = count - 1;
			}
			displaytop = selected - 9;
			if (displaytop<0) displaytop = 0;
		}
		swiWaitForVBlank();
	} while(!(pressed & KEY_A));

	//user has made a choice so grab the ap and return it
	Wifi_GetAPData(selected, &ap);

	return &ap;
}
示例#30
0
void titlescreen()
{
  videoSetMode(MODE_5_2D | DISPLAY_BG3_ACTIVE);
  videoSetModeSub(MODE_5_2D | DISPLAY_BG3_ACTIVE);

  vramSetMainBanks(VRAM_A_MAIN_BG_0x6000000, VRAM_B_LCD,
                   VRAM_C_SUB_BG, VRAM_D_LCD); 

  BG3_CR     = BG_BMP8_256x256 | BG_WRAP_ON | BG_MOSAIC_ON;
  SUB_BG3_CR = BG_BMP8_256x256 | BG_WRAP_ON | BG_MOSAIC_ON;

  // these are rotation backgrounds so you must set the rotation attributes:
  // these are fixed point numbers with the low 8 bits the fractional part
  // this basicaly gives it a 1:1 translation in x and y so you get a nice flat bitmap
  BG3_XDX = 1 << 8;
  BG3_XDY = 0;
  BG3_YDX = 0;
  BG3_YDY = 1 << 8;

  SUB_BG3_XDX = 1 << 8;
  SUB_BG3_XDY = 0;
  SUB_BG3_YDX = 0;
  SUB_BG3_YDY = 1 << 8;

  BG3_CX = 0;
  BG3_CY = 0;

  SUB_BG3_CX = 0;
  SUB_BG3_CY = 0;

  for(int i = 0; i < 256*192; ++i)
    BG_GFX[i] = ((u16*)titlescreen_img_bin)[i];
  for(int i = 0; i < 256; ++i)
    BG_PALETTE[i] = ((u16*)titlescreen_pal_bin)[i];

  for(int i = 0; i < 256*192; ++i)
    BG_GFX_SUB[i] = ((u16*)subtitlescreen_img_bin)[i];
  for(int i = 0; i < 256; ++i)
    BG_PALETTE_SUB[i] = ((u16*)subtitlescreen_pal_bin)[i];

  print("Hello World, 'This is a\nreally hard test,\nbla bla\nblabla");
  
  int count = 0;

  int mosaic_x = 0;
  int mosaic_y = 0;
  while(1) 
    {
      swiWaitForVBlank();
      scanKeys();    

      int pressed = keysDown();
      if (pressed & KEY_TOUCH)
        {
          //touchPosition touch_down = touchReadXY();
          count += 1;

          if (count > 0)
            break;
        }

      if (pressed & KEY_DOWN)
        mosaic_y -= 1;
      if (pressed & KEY_UP)
        mosaic_y += 1;

      if (pressed & KEY_LEFT)
        mosaic_x -= 1;
      if (pressed & KEY_RIGHT)
        mosaic_x += 1;

      if (pressed & KEY_X)
        mosaic_y = mosaic_x -= 1;
      if (pressed & KEY_Y)
        mosaic_y = mosaic_x += 1;

      mosaic_x = Math::mid(0, mosaic_x, 15);
      mosaic_y = Math::mid(0, mosaic_y, 15);
 
      BG3_CX = (mosaic_x/2) << 8;
      BG3_CY = (mosaic_y/2) << 8;

      MOSAIC_CR = mosaic_x | (mosaic_y << 4);
      SUB_MOSAIC_CR = mosaic_x | (mosaic_y << 4);
    }
}