Result httpwn_setup(char *serverconfig_localpath)
{
	Result ret = 0;
	u64 http_sysmodule_titleid = 0x0004013000002902ULL;
	AM_TitleEntry title_entry;

	u8 *cert = (u8*)builtin_rootca_der;
	u32 certsize = builtin_rootca_der_size;

	u8 *filebuffer;
	u32 filebuffer_size = 0x100000;
	u32 statuscode = 0;

	configctx config;
	targeturlctx *first_targeturlctx = NULL;

	FILE *f;

	memset(&config, 0, sizeof(configctx));
	config.first_targeturlctx = &first_targeturlctx;

	ret = amInit();
	if(ret!=0)
	{
		printf("Failed to initialize AM: 0x%08x.\n", (unsigned int)ret);
		if(ret==0xd8e06406)
		{
			printf("The AM service is inaccessible. With the *hax payloads this should never happen. This is normal with plain ninjhax v1.x: this app isn't usable from ninjhax v1.x without any further hax.\n");
		}
		return ret;
	}

	ret = AM_ListTitles(0, 1, &http_sysmodule_titleid, &title_entry);
	amExit();
	if(ret!=0)
	{
		printf("Failed to get the HTTP sysmodule title-version: 0x%08x.\n", (unsigned int)ret);
		return ret;
	}

	http_codebin_buf = NULL;
	http_codebin_buf32 = NULL;
	http_codebin_size = 0;

	ret = loadcodebin(http_sysmodule_titleid, MEDIATYPE_NAND, &http_codebin_buf, &http_codebin_size);
	if(R_FAILED(ret))
	{
		printf("Failed to load the HTTP sysmodule codebin: 0x%08x.\n", (unsigned int)ret);
		return ret;
	}

	http_codebin_buf32 = (u32*)http_codebin_buf;

	ret = httpcInit(0x1000);
	if(ret!=0)
	{
		printf("Failed to initialize HTTPC: 0x%08x.\n", (unsigned int)ret);
		if(ret==0xd8e06406)
		{
			printf("The HTTPC service is inaccessible. With the *hax payload this may happen if the process this app is running under doesn't have access to that service. Please try rebooting the system, boot *hax payload, then directly launch the app.\n");
		}

		free(http_codebin_buf);

		return ret;
	}

	filebuffer = malloc(filebuffer_size);
	if(filebuffer==NULL)
	{
		printf("Failed to allocate the config filebuffer.\n");
		ret = -2;
		httpcExit();
		free(http_codebin_buf);
		return ret;
		
	}
	memset(filebuffer, 0, filebuffer_size);

	printf("Downloading config...\n");
	ret = download_config("https://yls8.mtheall.com/ctr-httpwn/config.php", cert, certsize, filebuffer, filebuffer_size-1, &statuscode);
	if(ret!=0)
	{
		printf("Config downloading failed: 0x%08x.\n", (unsigned int)ret);

		if(statuscode==500)
		{
			printf("HTTP status-code 500 was returned, server reply:\n%s\n", (char*)filebuffer);
		}

		f = fopen(serverconfig_localpath, "rb");
		if(f)
		{
			printf("Use the cached server_config from SD instead?\nPress the A button to continue, B to abort.\n");
			while(1)
			{
				gspWaitForVBlank();
				hidScanInput();
				if(hidKeysDown() & KEY_A)break;
				if(hidKeysDown() & KEY_B)
				{
					fclose(f);
					httpcExit();
					free(http_codebin_buf);
					return ret;
				}
			}

			memset(filebuffer, 0, filebuffer_size);
			fread(filebuffer, 1, filebuffer_size-1, f);
			fclose(f);
		}
		else
		{
			httpcExit();
			free(http_codebin_buf);
			return ret;
		}
	}
	else
	{
		unlink(serverconfig_localpath);
		f = fopen(serverconfig_localpath, "wb");
		if(f)
		{
			fwrite(filebuffer, 1, strlen((char*)filebuffer), f);
			fclose(f);
		}
	}

	ret = config_parse(&config, (char*)filebuffer);

	if(ret==0)
	{
		if(title_entry.version != 13318)
		{
			printf("The installed HTTP sysmodule version(v%u) is not supported.", title_entry.version);
			if(config.incompatsysver_message[0])printf(" %s", config.incompatsysver_message);
			printf("\n");

			httpcExit();
			free(http_codebin_buf);
			free(filebuffer);

			return -1;
		}

		if(display_config_message(&config, "Message from the server:"))
		{
			httpcExit();
			free(http_codebin_buf);
			free(filebuffer);
			return 0;
		}
	}

	if(ret==0)
	{
		f = fopen("user_config.xml", "rb");
		if(f)
		{
			printf("Loading+parsing user_config.xml since it exists on SD...\n");

			memset(filebuffer, 0, filebuffer_size);
			fread(filebuffer, 1, filebuffer_size-1, f);
			fclose(f);

			ret = config_parse(&config, (char*)filebuffer);

			if(ret==0)
			{
				if(display_config_message(&config, "Message from the user_config:"))
				{
					httpcExit();
					free(http_codebin_buf);
					free(filebuffer);
					return 0;
				}
			}
		}
	}

	if(ret!=0)
	{
		printf("Config parsing failed: 0x%08x.\n", (unsigned int)ret);
		httpcExit();
		free(http_codebin_buf);
		free(filebuffer);
		return ret;
	}

	f = fopen("user_nim_rootcertchain_rootca.der", "rb");
	if(f)
	{
		printf("Loading user_nim_rootcertchain_rootca.der since it exists on SD, which will be used instead of the built-in ctr-httpwn cert...\n");

		memset(filebuffer, 0, filebuffer_size);
		certsize = fread(filebuffer, 1, filebuffer_size, f);
		fclose(f);

		cert = filebuffer;
	}

	printf("Preparing the haxx...\n");
	ret = http_haxx("http://localhost/", cert, certsize, first_targeturlctx);//URL doesn't matter much since this won't actually be requested over the network.
	config_freemem(&config);
	httpcExit();
	free(http_codebin_buf);
	free(filebuffer);
	if(ret!=0)
	{
		printf("Haxx setup failed: 0x%08x.\n", (unsigned int)ret);
		return ret;
	}

	return ret;
}
Exemple #2
0
//---------------------------------------------------------------------------
int main(int argc, char** argv)
{
	touchPosition lastTouch;
	int frame=0,lp_frame=0;
	
	CWebRequest::InitializeClient();	
	gfxInitDefault();
	GPU_Init(NULL);
	gfxSet3D(false);
	srand(svcGetSystemTick());
	CFBClient::Initialize();
	while(aptMainLoop()){
		hidScanInput();		
		u32 press = hidKeysDown();
		u32 held = hidKeysHeld();
		u32 release = hidKeysUp();
		if((press & ~KEY_TOUCH)){
			CFBClient::onKeysPressEvent(press,1);
			hidCircleRead(&lcp);
		}
		if((release & ~KEY_TOUCH)){
			CFBClient::onKeysUpEvent(press,1);
			hidCircleRead(&lcp);
		}
		if (held & KEY_TOUCH){
			hidTouchRead(&lt);
			if(!lp_frame){
				lastTouch=lt;
				lp_frame++;
			}
			else{
				int i=0;
				
				if(abs(lt.px-lastTouch.px) <= 5){
					if(abs(lt.py-lastTouch.py) <= 5)
						i = 1;
				}
				if(i)
					lp_frame++;
				else{
					lp_frame = 0;
					CFBClient::onTouchEvent(&lt,2);
				}
			}
			if(!frame)
				CFBClient::onTouchEvent(&lt,1);
			frame++;
		}
		else{
			if(frame)
				CFBClient::onTouchEvent(&lt,lp_frame > 120 ? 8 : 4);
			frame = 0;
			lp_frame = 0;
		}
		CFBClient::main(0);
		gfxFlushBuffers();
		gfxSwapBuffers();
		gspWaitForVBlank();
	}
	CFBClient::Destroy();
	CWebRequest::DestroyClient();
	fsExit();
	hidExit();
	gfxExit();
	aptExit();
	srvExit();
	return 0;
}
Exemple #3
0
int main() {
	sf2d_init();
	csndInit();
	noItem = newItem(ITEM_NULL, 0);

	currentMenu = MENU_TITLE;
	currentSelection = 0;
	quitGame = false;

	icons = sfil_load_PNG_buffer(icons2_png, SF2D_PLACE_RAM);
	font = sfil_load_PNG_buffer(Font_png, SF2D_PLACE_RAM);

	//consoleInit(GFX_BOTTOM, NULL);
	// printf("Press 'Start' to exit.\n");

	loadSound(&snd_playerHurt, "resources/playerhurt.raw");
	loadSound(&snd_playerDeath, "resources/playerdeath.raw");
	loadSound(&snd_monsterHurt, "resources/monsterhurt.raw");
	loadSound(&snd_test, "resources/test.raw");
	loadSound(&snd_pickup, "resources/pickup.raw");
	loadSound(&snd_bossdeath, "resources/bossdeath.raw");
	loadSound(&snd_craft, "resources/craft.raw");

	bakeLights();
	
	dirtColor[0] = 0xAD9291FF;
	dirtColor[1] = 0x826D6CFF;
	dirtColor[2] = 0x666666FF;
	dirtColor[3] = 0x555555FF;
	dirtColor[4] = 0x444444FF;

	int i;
	for (i = 0; i < 5; ++i) {
		minimap[i] = sf2d_create_texture(128, 128, TEXFMT_RGBA8,
				SF2D_PLACE_RAM);
		sf2d_texture_tile32(minimap[i]);
	}

	sf2d_set_vblank_wait(true);

	sf2d_set_clear_color(0xFF);

	/* Default inputs */
	k_up.input = KEY_DUP | KEY_CPAD_UP | KEY_CSTICK_UP;
	k_down.input = KEY_DDOWN | KEY_CPAD_DOWN | KEY_CSTICK_DOWN;
	k_left.input = KEY_DLEFT | KEY_CPAD_LEFT | KEY_CSTICK_LEFT;
	k_right.input = KEY_DRIGHT | KEY_CPAD_RIGHT | KEY_CSTICK_RIGHT;
	k_attack.input = KEY_A | KEY_B | KEY_L | KEY_ZR;
	k_menu.input = KEY_X | KEY_Y | KEY_R | KEY_ZL;
	k_pause.input = KEY_START;
	k_accept.input = KEY_A;
	k_decline.input = KEY_B;
	k_delete.input = KEY_X;
	FILE * file;

	/* If btnSave exists, then use that. */
	if ((file = fopen("btnSave.bin", "rb"))) {
		fread(&k_up.input, sizeof(int), 1, file);
		fread(&k_down.input, sizeof(int), 1, file);
		fread(&k_left.input, sizeof(int), 1, file);
		fread(&k_right.input, sizeof(int), 1, file);
		fread(&k_attack.input, sizeof(int), 1, file);
		fread(&k_menu.input, sizeof(int), 1, file);
		fread(&k_pause.input, sizeof(int), 1, file);
		fread(&k_accept.input, sizeof(int), 1, file);
		fread(&k_decline.input, sizeof(int), 1, file);
		fread(&k_delete.input, sizeof(int), 1, file);
		fclose(file);
	}

	//screenShot = false;

	tickCount = 0;
	initRecipes();
	defineTables();
	while (aptMainLoop()) {
		++tickCount;
		hidScanInput();
		tickKeys(hidKeysHeld(), hidKeysDown());

		//if (quitGame || hidKeysHeld() & KEY_SELECT) break;
		if (quitGame)
			break;
		//if (hidKeysDown() & (KEY_L | KEY_R)) screenShot = true;
		//	else screenShot = false;

		if (initGame > 0)
			setupGame(initGame == 1 ? true : false);

		if (currentMenu == 0) {
			tick();
			sprintf(fpsstr, " FPS: %.0f, X:%d, Y:%d, E:%d", sf2d_get_fps(),
					player.x, player.y, eManager.lastSlot[currentLevel]);
			sf2d_start_frame(GFX_TOP, GFX_LEFT);
			if (currentLevel == 0) {
				sf2d_draw_texture_part_scale(minimap[1], (-xscr / 3) - 256,
						(-yscr / 3) - 32, 0, 0, 128, 128, 12.5, 7.5);
				//sf2d_draw_rectangle(0, 0, 400, 240, 0xDFDFDFAF);
			}

			offsetX = xscr;
			offsetY = yscr;
			//if(currentLevel)
			sf2d_draw_rectangle(0, 0, 400, 240, RGBA8(12, 12, 12, 255)); //You might think "real" black would be better, but it actually looks better that way
			renderLightsToStencil();

			renderBackground(xscr, yscr);
			renderEntities(player.x, player.y, &eManager);
			renderPlayer();

			resetStencilStuff();
			offsetX = 0;
			offsetY = 0;
			renderItemWithText(player.p.activeItem, 10, 205);
			// drawText(debugText,2,208);
			drawText(fpsstr, 2, 225);
			sf2d_end_frame();

			sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);
			if (currentLevel == 0 && airWizardHealthDisplay > 0) {
				sprintf(bossHealthText, "BOSS: %.0f%%",
						((float) airWizardHealthDisplay / 2000.0) * 100);
				drawText(bossHealthText, 2, 225);
			}
			renderGui();
			sf2d_draw_texture(minimap[currentLevel], 192, 112);	//y:56
			sf2d_end_frame();
		} else {
			tickMenu(currentMenu);
			renderMenu(currentMenu, xscr, yscr);
		}

		sf2d_swapbuffers();
	}

	freeRecipes();

	freeLightBakes();
	sf2d_free_texture(icons);
	sf2d_free_texture(minimap[0]);
	sf2d_free_texture(minimap[1]);
	sf2d_free_texture(minimap[2]);
	sf2d_free_texture(minimap[3]);
	sf2d_free_texture(minimap[4]);
	freeSounds();
	csndExit();
	sf2d_fini();
	return 0;
}
Exemple #4
0
int main()
{
	Result ret=0;

	int draw=1;
	int ready=0;
	int type=0;

	gfxInit(GSP_RGB565_OES,GSP_BGR8_OES,false);
	consoleInit(GFX_BOTTOM, NULL);

	ret = romfsInit();
	if(R_FAILED(ret))
	{
		printf("romfsInit() failed: 0x%08x\n", (unsigned int)ret);
		ready = -1;
	}

	if(ready==0)
	{
		inaddr = linearMemAlign(0x1000000, 0x40);
		outaddr = linearMemAlign(0x100000, 0x40);

		if(!(inaddr && outaddr))
		{
			ready = -2;
			printf("Failed to allocate memory.\n");
		}
	}

	// Main loop
	while (aptMainLoop())
	{
		gspWaitForVBlank();
		hidScanInput();

		if(draw && type==0)
		{
			consoleClear();
			draw = 0;

			if(ready==0)printf("mvd example\n");

			printf("Press START to exit.\n");
			if(ready==0)
			{
				printf("Press A for color-format-conversion.\n");
				printf("Press B for video(no sound).\n");
			}
		}

		u32 kDown = hidKeysDown();

		if(type)
		{
			if(kDown & KEY_A)
			{
				type = 0;
				continue;
			}
		}

		if(type)continue;

		if (kDown & KEY_START)
			break; // break in order to return to hbmenu

		if(ready==0)
		{
			type = 0;
			if (kDown & KEY_A)type = 1;
			if (kDown & KEY_B)type = 2;

			if(type)
			{
				memset(inaddr, 0, 0x100000);
				memset(outaddr, 0, 0x100000);

				if(type==1)mvd_colorconvert();
				if(type==2)mvd_video();

				draw = 1;
				printf("Press A to continue.\n");
			}
		}
	}

	if(inaddr)linearFree(inaddr);
	if(outaddr)linearFree(outaddr);

	if(ready!=-1)romfsExit();

	gfxExit();
	return 0;
}
Exemple #5
0
static bool ctr_frame(void* data, const void* frame,
      unsigned width, unsigned height, 
      uint64_t frame_count,
      unsigned pitch, const char* msg)
{
   uint32_t diff;
   static uint64_t currentTick,lastTick;
   ctr_video_t       *ctr  = (ctr_video_t*)data;
   settings_t   *settings  = config_get_ptr();
   static float        fps = 0.0;
   static int total_frames = 0;
   static int       frames = 0;
   static struct retro_perf_counter ctrframe_f = {0};
   uint32_t state_tmp;
   touchPosition state_tmp_touch;

   extern bool select_pressed;

   if (!width || !height)
   {
      gspWaitForEvent(GSPGPU_EVENT_VBlank0, true);
      return true;
   }

   if(!aptMainLoop())
   {
      command_event(CMD_EVENT_QUIT, NULL);
      return true;
   }

   if (select_pressed)
   {
      command_event(CMD_EVENT_QUIT, NULL);
      return true;
   }

   state_tmp = hidKeysDown();
   hidTouchRead(&state_tmp_touch);
   if((state_tmp & KEY_TOUCH) && (state_tmp_touch.py < 120))
   {
      Handle lcd_handle;
      u8 not_2DS;
      extern PrintConsole* currentConsole;

      gfxBottomFramebuffers[0] = ctr->lcd_buttom_on ? (u8*)ctr->empty_framebuffer:
                                                      (u8*)currentConsole->frameBuffer;

      CFGU_GetModelNintendo2DS(&not_2DS);
      if(not_2DS && srvGetServiceHandle(&lcd_handle, "gsp::Lcd") >= 0)
      {
         u32 *cmdbuf = getThreadCommandBuffer();
         cmdbuf[0] = ctr->lcd_buttom_on? 0x00120040:  0x00110040;
         cmdbuf[1] = 2;
         svcSendSyncRequest(lcd_handle);
         svcCloseHandle(lcd_handle);
      }

      ctr->lcd_buttom_on = !ctr->lcd_buttom_on;
   }

   svcWaitSynchronization(gspEvents[GSPGPU_EVENT_P3D], 20000000);
   svcClearEvent(gspEvents[GSPGPU_EVENT_P3D]);
   svcWaitSynchronization(gspEvents[GSPGPU_EVENT_PPF], 20000000);
   svcClearEvent(gspEvents[GSPGPU_EVENT_PPF]);

   frames++;

   if (ctr->vsync)
      svcWaitSynchronization(gspEvents[GSPGPU_EVENT_VBlank0], U64_MAX);

   svcClearEvent(gspEvents[GSPGPU_EVENT_VBlank0]);

   currentTick = svcGetSystemTick();
   diff        = currentTick - lastTick;
   if(diff > CTR_CPU_TICKS_PER_SECOND)
   {
      fps = (float)frames * ((float) CTR_CPU_TICKS_PER_SECOND / (float) diff);
      lastTick = currentTick;
      frames = 0;
   }


//#define CTR_INSPECT_MEMORY_USAGE

#ifdef CTR_INSPECT_MEMORY_USAGE
   uint32_t ctr_get_stack_usage(void);
   void ctr_linear_get_stats(void);
   extern u32 __linear_heap_size;
   extern u32 __heap_size;

   MemInfo mem_info;
   PageInfo page_info;
   u32 query_addr = 0x08000000;
   printf(PRINTFPOS(0,0));
   while (query_addr < 0x40000000)
   {
      svcQueryMemory(&mem_info, &page_info, query_addr);
      printf("0x%08X --> 0x%08X (0x%08X) \n", mem_info.base_addr, mem_info.base_addr + mem_info.size, mem_info.size);
      query_addr = mem_info.base_addr + mem_info.size;
      if(query_addr == 0x1F000000)
         query_addr = 0x30000000;
   }
//   static u32* dummy_pointer;
//   if(total_frames == 500)
//      dummy_pointer = malloc(0x2000000);
//   if(total_frames == 1000)
//      free(dummy_pointer);


   printf("========================================");
   printf("0x%08X 0x%08X 0x%08X\n", __heap_size, gpuCmdBufOffset, (__linear_heap_size - linearSpaceFree()));
   printf("fps: %8.4f frames: %i (%X)\n", fps, total_frames++, (__linear_heap_size - linearSpaceFree()));
   printf("========================================");
   u32 app_memory = *((u32*)0x1FF80040);
   u64 mem_used;
   svcGetSystemInfo(&mem_used, 0, 1);
   printf("total mem : 0x%08X          \n", app_memory);
   printf("used: 0x%08X free: 0x%08X      \n", (u32)mem_used, app_memory - (u32)mem_used);
   static u32 stack_usage = 0;
   extern u32 __stack_bottom;
   if(!(total_frames & 0x3F))
      stack_usage = ctr_get_stack_usage();
   printf("stack total:0x%08X used: 0x%08X\n", 0x10000000 - __stack_bottom, stack_usage);

   printf("========================================");
   ctr_linear_get_stats();
   printf("========================================");

#else
   printf(PRINTFPOS(29,0)"fps: %8.4f frames: %i\r", fps, total_frames++);
#endif
   fflush(stdout);

   performance_counter_init(&ctrframe_f, "ctrframe_f");
   performance_counter_start(&ctrframe_f);

   if (ctr->should_resize)
      ctr_update_viewport(ctr);

   ctrGuSetMemoryFill(true, (u32*)CTR_TOP_FRAMEBUFFER, 0x00000000,
                    (u32*)(CTR_TOP_FRAMEBUFFER + 2 * CTR_TOP_FRAMEBUFFER_WIDTH * CTR_TOP_FRAMEBUFFER_HEIGHT * sizeof(uint32_t)),
                    0x201, (u32*)CTR_GPU_DEPTHBUFFER, 0x00000000,
                    (u32*)(CTR_GPU_DEPTHBUFFER + CTR_TOP_FRAMEBUFFER_WIDTH * CTR_TOP_FRAMEBUFFER_HEIGHT * sizeof(uint32_t)),
                    0x201);

   GPUCMD_SetBufferOffset(0);

   if (width > ctr->texture_width)
      width = ctr->texture_width;
   if (height > ctr->texture_height)
      height = ctr->texture_height;

   if(frame)
   {
      if(((((u32)(frame)) >= 0x14000000 && ((u32)(frame)) < 0x40000000)) /* frame in linear memory */
         && !((u32)frame & 0x7F)                                         /* 128-byte aligned */
         && !(pitch & 0xF)                                               /* 16-byte aligned */
         && (pitch > 0x40))
      {
         /* can copy the buffer directly with the GPU */
//         GSPGPU_FlushDataCache(frame, pitch * height);
         ctrGuSetCommandList_First(true,(void*)frame, pitch * height,0,0,0,0);
         ctrGuCopyImage(true, frame, pitch / (ctr->rgb32? 4: 2), height, ctr->rgb32 ? CTRGU_RGBA8: CTRGU_RGB565, false,
                        ctr->texture_swizzled, ctr->texture_width, ctr->rgb32 ? CTRGU_RGBA8: CTRGU_RGB565,  true);
      }
      else
      {
         int i;
         uint8_t      *dst = (uint8_t*)ctr->texture_linear;
         const uint8_t *src = frame;

         for (i = 0; i < height; i++)
         {
            memcpy(dst, src, width * (ctr->rgb32? 4: 2));
            dst += ctr->texture_width * (ctr->rgb32? 4: 2);
            src += pitch;
         }
         GSPGPU_FlushDataCache(ctr->texture_linear,
                               ctr->texture_width * ctr->texture_height * (ctr->rgb32? 4: 2));

         ctrGuCopyImage(false, ctr->texture_linear, ctr->texture_width, ctr->texture_height, ctr->rgb32 ? CTRGU_RGBA8: CTRGU_RGB565, false,
                        ctr->texture_swizzled, ctr->texture_width, ctr->rgb32 ? CTRGU_RGBA8: CTRGU_RGB565,  true);

      }

      ctr->frame_coords->u0 = 0;
      ctr->frame_coords->v0 = 0;
      ctr->frame_coords->u1 = width;
      ctr->frame_coords->v1 = height;
      GSPGPU_FlushDataCache(ctr->frame_coords, sizeof(ctr_vertex_t));
      ctrGuSetVertexShaderFloatUniform(0, (float*)&ctr->scale_vector, 1);
   }

   ctrGuSetTexture(GPU_TEXUNIT0, VIRT_TO_PHYS(ctr->texture_swizzled), ctr->texture_width, ctr->texture_height,
                  (ctr->smooth? GPU_TEXTURE_MAG_FILTER(GPU_LINEAR)  | GPU_TEXTURE_MIN_FILTER(GPU_LINEAR)
                              : GPU_TEXTURE_MAG_FILTER(GPU_NEAREST) | GPU_TEXTURE_MIN_FILTER(GPU_NEAREST)) |
                  GPU_TEXTURE_WRAP_S(GPU_CLAMP_TO_EDGE) | GPU_TEXTURE_WRAP_T(GPU_CLAMP_TO_EDGE),
                  ctr->rgb32 ? GPU_RGBA8: GPU_RGB565);

   ctr_check_3D_slider(ctr);

   /* ARGB --> RGBA */
   if (ctr->rgb32)
   {
      GPU_SetTexEnv(0,
                    GPU_TEVSOURCES(GPU_TEXTURE0, GPU_CONSTANT, 0),
                    GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, 0),
                    GPU_TEVOPERANDS(GPU_TEVOP_RGB_SRC_G, 0, 0),
                    GPU_TEVOPERANDS(0, 0, 0),
                    GPU_MODULATE, GPU_MODULATE,
                    0x0000FF);
      GPU_SetTexEnv(1,
                    GPU_TEVSOURCES(GPU_TEXTURE0, GPU_CONSTANT, GPU_PREVIOUS),
                    GPU_TEVSOURCES(GPU_PREVIOUS, GPU_PREVIOUS, 0),
                    GPU_TEVOPERANDS(GPU_TEVOP_RGB_SRC_B, 0, 0),
                    GPU_TEVOPERANDS(0, 0, 0),
                    GPU_MULTIPLY_ADD, GPU_MODULATE,
                    0x00FF00);
      GPU_SetTexEnv(2,
                    GPU_TEVSOURCES(GPU_TEXTURE0, GPU_CONSTANT, GPU_PREVIOUS),
                    GPU_TEVSOURCES(GPU_PREVIOUS, GPU_PREVIOUS, 0),
                    GPU_TEVOPERANDS(GPU_TEVOP_RGB_SRC_ALPHA, 0, 0),
                    GPU_TEVOPERANDS(0, 0, 0),
                    GPU_MULTIPLY_ADD, GPU_MODULATE,
                    0xFF0000);
   }

   GPU_SetViewport(VIRT_TO_PHYS(CTR_GPU_DEPTHBUFFER),
                   VIRT_TO_PHYS(CTR_TOP_FRAMEBUFFER),
                   0, 0, CTR_TOP_FRAMEBUFFER_HEIGHT,
                   ctr->video_mode == CTR_VIDEO_MODE_800x240 ? CTR_TOP_FRAMEBUFFER_WIDTH * 2 : CTR_TOP_FRAMEBUFFER_WIDTH);

   if (ctr->video_mode == CTR_VIDEO_MODE_3D)
   {
      if (ctr->menu_texture_enable)
      {
         ctrGuSetAttributeBuffersAddress(VIRT_TO_PHYS(&ctr->frame_coords[1]));
         GPU_DrawArray(GPU_GEOMETRY_PRIM, 0, 1);
         ctrGuSetAttributeBuffersAddress(VIRT_TO_PHYS(&ctr->frame_coords[2]));
      }
      else
      {
         ctrGuSetAttributeBuffersAddress(VIRT_TO_PHYS(ctr->frame_coords));
         GPU_DrawArray(GPU_GEOMETRY_PRIM, 0, 1);
      }
      GPU_SetViewport(VIRT_TO_PHYS(CTR_GPU_DEPTHBUFFER),
                      VIRT_TO_PHYS(CTR_TOP_FRAMEBUFFER_RIGHT),
                      0, 0, CTR_TOP_FRAMEBUFFER_HEIGHT,
                      CTR_TOP_FRAMEBUFFER_WIDTH);
   }
   else
      ctrGuSetAttributeBuffersAddress(VIRT_TO_PHYS(ctr->frame_coords));

   GPU_DrawArray(GPU_GEOMETRY_PRIM, 0, 1);

   /* restore */
   if (ctr->rgb32)
   {
      GPU_SetTexEnv(0, GPU_TEXTURE0, GPU_TEXTURE0, 0, 0, GPU_REPLACE, GPU_REPLACE, 0);
      GPU_SetTexEnv(1, GPU_PREVIOUS, GPU_PREVIOUS, 0, 0, 0, 0, 0);
      GPU_SetTexEnv(2, GPU_PREVIOUS, GPU_PREVIOUS, 0, 0, 0, 0, 0);
   }

   if (ctr->menu_texture_enable)
   {

      GSPGPU_FlushDataCache(ctr->menu.texture_linear,
                            ctr->menu.texture_width * ctr->menu.texture_height * sizeof(uint16_t));

      ctrGuCopyImage(false, ctr->menu.texture_linear, ctr->menu.texture_width, ctr->menu.texture_height, CTRGU_RGBA4444,false,
                     ctr->menu.texture_swizzled, ctr->menu.texture_width, CTRGU_RGBA4444,  true);

      ctrGuSetTexture(GPU_TEXUNIT0, VIRT_TO_PHYS(ctr->menu.texture_swizzled), ctr->menu.texture_width, ctr->menu.texture_height,
                     GPU_TEXTURE_MAG_FILTER(GPU_LINEAR) | GPU_TEXTURE_MIN_FILTER(GPU_LINEAR) |
                     GPU_TEXTURE_WRAP_S(GPU_CLAMP_TO_EDGE) | GPU_TEXTURE_WRAP_T(GPU_CLAMP_TO_EDGE),
                     GPU_RGBA4);

      ctrGuSetVertexShaderFloatUniform(0, (float*)&ctr->menu.scale_vector, 1);
      GPU_SetViewport(VIRT_TO_PHYS(CTR_GPU_DEPTHBUFFER),
                      VIRT_TO_PHYS(CTR_TOP_FRAMEBUFFER),
                      0, 0, CTR_TOP_FRAMEBUFFER_HEIGHT,
                      ctr->video_mode == CTR_VIDEO_MODE_800x240 ? CTR_TOP_FRAMEBUFFER_WIDTH * 2 : CTR_TOP_FRAMEBUFFER_WIDTH);

      ctrGuSetAttributeBuffersAddress(VIRT_TO_PHYS(ctr->menu.frame_coords));
      GPU_DrawArray(GPU_GEOMETRY_PRIM, 0, 1);

      if (ctr->video_mode == CTR_VIDEO_MODE_3D)
      {
         GPU_SetViewport(VIRT_TO_PHYS(CTR_GPU_DEPTHBUFFER),
                         VIRT_TO_PHYS(CTR_TOP_FRAMEBUFFER_RIGHT),
                         0, 0, CTR_TOP_FRAMEBUFFER_HEIGHT,
                         CTR_TOP_FRAMEBUFFER_WIDTH);
         GPU_DrawArray(GPU_GEOMETRY_PRIM, 0, 1);
      }
   }

   GPU_FinishDrawing();
   GPUCMD_Finalize();
   ctrGuFlushAndRun(true);

   ctrGuDisplayTransfer(true, CTR_TOP_FRAMEBUFFER,
                        240,
                        ctr->video_mode == CTR_VIDEO_MODE_800x240 ? 800 : 400,
                        CTRGU_RGBA8,
                        gfxTopLeftFramebuffers[ctr->current_buffer_top], 240,CTRGU_RGB8, CTRGU_MULTISAMPLE_NONE);


   if ((ctr->video_mode == CTR_VIDEO_MODE_400x240) || (ctr->video_mode == CTR_VIDEO_MODE_3D))
      ctrGuDisplayTransfer(true, CTR_TOP_FRAMEBUFFER_RIGHT,
                           240,
                           400,
                           CTRGU_RGBA8,
                           gfxTopRightFramebuffers[ctr->current_buffer_top], 240,CTRGU_RGB8, CTRGU_MULTISAMPLE_NONE);


   // Swap buffers :
   ctr->current_buffer_top ^= 1;
   extern GSPGPU_FramebufferInfo topFramebufferInfo;
   extern u8* gfxSharedMemory;
   extern u8 gfxThreadID;

   topFramebufferInfo.active_framebuf=ctr->current_buffer_top;
   topFramebufferInfo.framebuf0_vaddr=(u32*)gfxTopLeftFramebuffers[ctr->current_buffer_top];
   if(ctr->video_mode == CTR_VIDEO_MODE_800x240)
   {
      topFramebufferInfo.framebuf1_vaddr=(u32*)(gfxTopLeftFramebuffers[ctr->current_buffer_top] + 240 * 3);
      topFramebufferInfo.framebuf_widthbytesize = 240 * 3 * 2;
   }
   else
   {
      topFramebufferInfo.framebuf1_vaddr=(u32*)gfxTopRightFramebuffers[ctr->current_buffer_top];
      topFramebufferInfo.framebuf_widthbytesize = 240 * 3;
   }


   topFramebufferInfo.format=(1<<8)|(1<<5)|GSP_BGR8_OES;
   topFramebufferInfo.framebuf_dispselect=ctr->current_buffer_top;
   topFramebufferInfo.unk=0x00000000;

   u8* framebufferInfoHeader=gfxSharedMemory+0x200+gfxThreadID*0x80;
	GSPGPU_FramebufferInfo* framebufferInfo=(GSPGPU_FramebufferInfo*)&framebufferInfoHeader[0x4];
	framebufferInfoHeader[0x0] ^= 1;
	framebufferInfo[framebufferInfoHeader[0x0]] = topFramebufferInfo;
	framebufferInfoHeader[0x1]=1;

   performance_counter_stop(&ctrframe_f);

   return true;
}
Exemple #6
0
int main(int argc, char **argv){

    // Initialize services
    gfxInitDefault();

    //Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one
    consoleInit(GFX_TOP, NULL);


    int alevel=0, glevel = 0;

    //print GyroscopeRawToDpsCoefficient
    float gyroCoef;
    HIDUSER_GetGyroscopeRawToDpsCoefficient_(&gyroCoef);
    printf("\x1b[0;0HGyroCoef:%f", gyroCoef);

    //print GyroscopeLowCalibrateParam
    u8 Calibrate[20];
    HIDUSER_GetGyroscopeLowCalibrateParam(Calibrate);
    for(int i = 0; i<3; ++i){
        printf("\x1b[%d;0HGyroCalibrate(%d):", i+1, i+1);
        for(int j = 0; j<6; ++j){
            printf("%02X ", Calibrate[i*6+j]);
        }
    }


    printf("\x1b[13;0HPad:\n"); 
    printf("A:call EnableGyroscope\n");
    printf("B:call DisableGyroscope\n");
    printf("X:call EnableAccelerometer\n");
    printf("Y:call DisableAccelerometer\n");

    Result result=0;
    while(aptMainLoop()){
        hidScanInput();

        u32 kDown = hidKeysDown();

        if(kDown & KEY_START) break; // break in order to return to hbmenu
        if(kDown & KEY_A){
            ++glevel;
            result=HIDUSER_EnableGyroscope();
        }
        if(kDown & KEY_B){
            --glevel;
            result = HIDUSER_DisableGyroscope();
        }
        if(kDown & KEY_X){
            ++alevel;
            result = HIDUSER_EnableAccelerometer();
        }
        if(kDown & KEY_Y){
            --alevel;
            result = HIDUSER_DisableAccelerometer();
        }


        //Read gyro data
        myAngularRate gyro;
        hidGyroRead((angularRate*)&gyro);
        printf("\x1b[5;0Hgyro(level=%3d)%6d;%6d;%6d",glevel, gyro.x, gyro.y, gyro.z);

        //Read raw gyro data
        gyro = *(myAngularRate*)&hidSharedMem[86+6];
        printf("\x1b[6;0Hgyro(raw      )%6d;%6d;%6d", gyro.x, gyro.y, gyro.z);

        //Read accel data
        accelVector vector;
        hidAccelRead(&vector);
        printf("\x1b[7;0Hacce(level=%3d)%6d;%6d;%6d",alevel, vector.x, vector.y, vector.z);

        //Read raw accel
        vector = *(accelVector*)&hidSharedMem[66+6];
        printf("\x1b[8;0Hacce(raw      )%6d;%6d;%6d", vector.x, vector.y, vector.z);

        //test if gyro and accel events are activated
        printf("\x1b[9;0Hgyro event: %s", hidTryWaitForEvent(HIDEVENT_Gyro, 10000000) ? "true " : "false");
        printf("\x1b[10;0Hacce event: %s", hidTryWaitForEvent(HIDEVENT_Accel, 10000000)?"true ":"false");

        //print the last result of enable/disable gyroscope/accelerometer call
        printf("\x1b[11;0Henable/disable call result=%08lX", result);

        // Flush and swap framebuffers
        gfxFlushBuffers();
        gfxSwapBuffers();

        //Wait for VBlank
        gspWaitForVBlank();
    }


    // Exit services
    gfxExit();
    return 0;
}
Exemple #7
0
int main(int argc, char **argv)
{
    InitPlatform(argc, argv);

    HsfOpen(&HSF, "puzzle.hsf");

    MIPS_R3000 Cpu;
    GPU Gpu;
    Cpu.CP1 = &Gpu;
    MapRegister(&Cpu, (mmr) {GPU_GP0, &Gpu, GpuGp0, empty_ret});
    MapRegister(&Cpu, (mmr) {GPU_GP1, &Gpu, GpuGp1, GpuStat});
    MapRegister(&Cpu, (mmr) {0x1F802064, &Cpu, std_out_putchar, empty_ret});
    MapRegister(&Cpu, (mmr) {0x1F802068, &Cpu, CTRXFileOpen, CTRXFileOpenReturn});
    MapRegister(&Cpu, (mmr) {0x1F802070, &Cpu, CTRXFileRead, CTRXFileReadReturn});
    MapRegister(&Cpu, (mmr) {0x1F802074, &Cpu, CTRXFileSeek, CTRXFileSeekReturn});
    MapRegister(&Cpu, (mmr) {0x1F802078, &Cpu, CTRXFirstFile, CTRXFirstFileReturn});
    MapRegister(&Cpu, (mmr) {0x1F8010A0, &Cpu, DMA2Trigger, empty_ret});
    MapRegister(&Cpu, (mmr) {JOY_TX_DATA, nullptr, JoyTxWrite, JoyRxRead});
    MapRegister(&Cpu, (mmr) {0x1F801070, nullptr, empty_write, CTRXInterruptRegisterRead});
    MapRegister(&Cpu, (mmr) {0x1F801070, nullptr, CTRXInterruptRegisterWrite, empty_ret});

    FILE *f = fopen("psx_bios.bin", "rb");
    fseek(f, 0, SEEK_END);
    long fsize = ftell(f);
    fseek(f, 0, SEEK_SET);

    u8 *BiosBuffer = (u8 *)linearAlloc(fsize + 1);
    fread(BiosBuffer, fsize, 1, f);
    fclose(f);

    for (int i = 0; i < fsize; ++i)
    {
        WriteMemByteRaw(&Cpu, RESET_VECTOR + i, BiosBuffer[i]);
    }
    linearFree(BiosBuffer);

    ResetCpu(&Cpu);

    bool Step = false;
    int CyclesToRun = 10000;
    bool EnableDisassembler = false;
    bool AutoStep = true;
    u32 IRQ0Steps = 0;
    while (MainLoopPlatform())
    {
#ifdef _3DS
        u32 KeysDown = hidKeysDown();

        if (KeysDown & KEY_START)
            break;
#endif

        if (Step || AutoStep)
        {
            StepCpu(&Cpu, CyclesToRun);
            IRQ0Steps += CyclesToRun;
            if (IRQ0Steps >= 50000)
            {
                C0GenerateException(&Cpu, C0_CAUSE_INT, Cpu.pc - 4);
                IRQ0Steps = 0;
                InterruptMask |= 1;
            }
        }

        if (EnableDisassembler)
        {
            printf("\x1b[0;0H");
            DisassemblerPrintRange(&Cpu, Cpu.pc - (13 * 4), 29, Cpu.pc);
        }

        SwapBuffersPlatform();
    }

    HsfClose(&HSF);
    ExitPlatform();

    return 0;
}
Exemple #8
0
int main(int argc, char **argv) {
    Result res;

    // Initialize services
    gfxInitDefault();

    PrintConsole topScreen;
    PrintConsole bottomScreen;

    consoleInit(GFX_TOP, &topScreen);
    consoleInit(GFX_BOTTOM, &bottomScreen);

    //Move the cursor to the top left corner of the screen
    consoleSelect(&topScreen);
    printf("\x1b[0;0H");

    //Print a REALLY crappy poeam with colored text
    //\x1b[cm set a SGR (Select Graphic Rendition) parameter, where c is the parameter that you want to set
    //Please refer to http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes to see all the possible SGR parameters
    //As of now ctrulib support only these parameters:
    //Reset (0), Half bright colors (2), Reverse (7), Text color (30-37) and Background color (40-47)
    printf("%sA:%s\tDump ticket.db\n", TEXT_GREEN, TEXT_RESET);

    consoleSelect(&bottomScreen);
    printf("\x1b[0;0H");

    printf("%sPatching service access...%s\n", TEXT_GREEN, TEXT_RESET);
    saveConstants();
    res = patchServices();
    if(res) {
        printf("%sPatching failed!%s\n", TEXT_RED, TEXT_RESET);
        while(aptMainLoop()) {
            if(hidKeysDown()) {
                break;
            }
        }
    }

    // Main loop
    while (aptMainLoop() && res == 0) {
        //Scan all the inputs. This should be done once for each frame
        hidScanInput();

        //hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
        u32 kDown = hidKeysDown();

        if (kDown & KEY_A) {
            dumpTicket();
        }

        // Flush and swap framebuffers
        gfxFlushBuffers();
        gfxSwapBuffers();

        //Wait for VBlank
        gspWaitForVBlank();
    }

    // Exit services
    gfxExit();

    return 0;
}
Exemple #9
0
//return true when we're ready to boot something
//(TEMP ?)
bool updateMenu(menu_s* m)
{
	if(!m)return false;
	if(!m->numEntries)return false;

	//controls
	s8 move=0;
	circlePosition cstick;
	touchPosition touch;
	hidCstickRead(&cstick);
	hidTouchRead(&touch);
	
	cstick.dy=(abs(cstick.dy)<5)?0:cstick.dy;

	if(hidKeysDown()&KEY_DOWN)move++;
	if(hidKeysDown()&KEY_UP)move--;
	if(hidKeysDown()&KEY_RIGHT)move+=4;
	if(hidKeysDown()&KEY_LEFT)move-=4;

	u16 oldEntry=m->selectedEntry;

	if(hidKeysDown()&KEY_TOUCH)
	{
		m->touchTimer=0;
		m->firstTouch=touch;
	}else if((hidKeysUp()&KEY_TOUCH) && m->touchTimer<30 && abs(m->firstTouch.px-m->previousTouch.px)+abs(m->firstTouch.py-m->previousTouch.py)<12){
		menuEntry_s* me=m->entries;
		int i=0;
		int p=0;
		while(me)
		{
			int h=(i==m->selectedEntry)?ENTRY_WIDTH_SELECTED:ENTRY_WIDTH;
			if((240-m->previousTouch.py)>=getEntryLocationPx(m,p)-h && (240-m->previousTouch.py)<getEntryLocationPx(m,p))break;
			p+=h;
			me=me->next;
			i++;
		}
		if(m->selectedEntry==i)return true;
		else m->selectedEntry=i;
	}else if(hidKeysHeld()&KEY_TOUCH){
		//condition to make sure previousTouch is valid
		cstick.dy+=(touch.py-m->previousTouch.py)*16;
		m->touchTimer++;
	}
	if(move+m->selectedEntry<0)m->selectedEntry=0;
	else if(move+m->selectedEntry>=m->numEntries)m->selectedEntry=m->numEntries-1;
	else m->selectedEntry+=move;

	if(m->selectedEntry!=oldEntry)m->atEquilibrium=false;

	if(hidKeysDown()&KEY_A)return true;

	m->previousTouch=touch;

	//scrolling code
	const int maxScroll=240-(m->numEntries)*ENTRY_WIDTH; //cf getEntryLocation

	if(!m->atEquilibrium)
	{
		m->scrollTarget=intToFpt(getEntryLocation(m, m->selectedEntry));
		if(m->scrollTarget>intToFpt(240-ENTRY_WIDTH) || (m->selectedEntry==0 && m->numEntries>3))
			m->scrollVelocity+=(intToFpt(240-ENTRY_WIDTH)-m->scrollTarget)/SCROLLING_SPEED;
		if(m->scrollTarget<0 || (m->selectedEntry==m->numEntries-1 && m->numEntries>3))
			m->scrollVelocity+=(intToFpt(0)-m->scrollTarget)/SCROLLING_SPEED;
	}else if(m->numEntries>3){
		s32 val=-cstick.dy*16; // TODO : make it inversely proportional to numEntries ?
		if(m->scrollLocation>intToFpt(-maxScroll))
		{
			m->scrollVelocity+=(intToFpt(-maxScroll)-m->scrollLocation)/SCROLLING_SPEED;
			if(val<0)m->scrollVelocity+=val;
		}else if(m->scrollLocation<intToFpt(0)){
			m->scrollVelocity-=m->scrollLocation/SCROLLING_SPEED;
			if(val>0)m->scrollVelocity+=val;
		}else m->scrollVelocity+=val;
	}

	m->scrollLocation+=m->scrollVelocity;
	m->scrollVelocity=(m->scrollVelocity*3)/4;

	m->scrollBarSize=40; //TEMP : make it adaptive to number of menu entries ?
	m->scrollBarPos=-fptToInt(m->scrollLocation*(200-m->scrollBarSize))/maxScroll;
	if(m->scrollBarPos<0)
	{
		m->currentScrollBarSize=m->scrollBarSize+m->scrollBarPos;
		if(m->currentScrollBarSize<10)m->currentScrollBarSize=10;
		m->scrollBarPos=m->currentScrollBarSize-m->scrollBarSize;
	}else if(m->scrollBarPos>=200-m->scrollBarSize)
	{
		m->currentScrollBarSize=-(m->scrollBarPos-200);
		if(m->currentScrollBarSize<10)m->currentScrollBarSize=10;
		debugValues[3]=m->scrollBarPos-200;
		m->scrollBarPos=200-m->scrollBarSize;
	}else m->currentScrollBarSize=m->scrollBarSize;

	if(!m->scrollVelocity)m->atEquilibrium=true;

	// debugValues[0]=m->scrollLocation;
	// debugValues[1]=m->scrollTarget;
	// debugValues[1]=fptToInt(m->scrollLocation);
	// debugValues[2]=intToFpt(maxScroll);
	// debugValues[3]=maxScroll;

	return false;
}
Exemple #10
0
int main()
{
	httpcInit();

	gfxInitDefault();
	gfxSet3D(false);

	Result ret = filesystemInit();

	PrintConsole topConsole, bttmConsole;
	consoleInit(GFX_TOP, &topConsole);
	consoleInit(GFX_BOTTOM, &bttmConsole);

	consoleSelect(&topConsole);
	consoleClear();

	state_t current_state = STATE_NONE;
	state_t next_state = STATE_INITIAL;

	static char top_text[2048];
	top_text[0] = '\0';

	int selected_slot = 0;
	int selected_iron_version = 1;

	int firmware_version[firmware_length] = {0, 0, 9, 0, 0};
	int firmware_selected_value = 0;
	
	static char payload_name[256];
	u8* payload_buf = NULL;
	u32 payload_size = 0;

	while (aptMainLoop())
	{
		hidScanInput();
		if(hidKeysDown() & KEY_START)break;

		// transition function
		if(next_state != current_state)
		{
			switch(next_state)
			{
				case STATE_INITIAL:
					strcat(top_text, " Welcome to the oot3dhax installer! Please proceedwith caution, as you might lose data if you don't.You may press START at any time to return to menu.\n                            Press A to continue.\n\n");
					break;
				case STATE_SELECT_SLOT:
					strcat(top_text, " Please select the savegame slot oot3dhax will be\ninstalled to. D-Pad to select, A to continue.\n");
					break;
				case STATE_SELECT_IRON_VERSION:
					strcat(top_text, "\n\n\n This is your last chance to cancel.\nOh, what's your favourite version of Ironfall?\n");
					break;
				case STATE_SELECT_FIRMWARE:
					strcat(top_text, "\n\n\n Please select your console's firmware version.\nOnly select NEW 3DS if you own a New 3DS (XL).\nD-Pad to select, A to continue.\n");
					break;
				case STATE_DOWNLOAD_PAYLOAD:
					getPayloadName(firmware_version, payload_name);
					sprintf(top_text, "%s\n\n\n Downloading payload... %s\n", top_text, payload_name);
					break;
				case STATE_COMPRESS_PAYLOAD:
					strcat(top_text, " Processing payload...\n");
					break;
				case STATE_INSTALL_PAYLOAD:
					strcat(top_text, " Installing payload...\n");
					break;
				case STATE_INSTALLED_PAYLOAD:
					strcat(top_text, " Done! oot3dhax was successfully installed.");
					break;
				case STATE_ERROR:
					strcat(top_text, " Looks like something went wrong. :(\n");
					break;
				default:
					break;
			}
			current_state = next_state;
		}

		consoleSelect(&topConsole);
		printf("\x1b[0;%dHoot3dhax installer", (50 - 17) / 2);
		printf("\x1b[1;%dHmostly by smea\n\n\n", (50 - 7) / 2);
		printf(top_text);

		// state function
		switch(current_state)
		{
			case STATE_INITIAL:
				if(hidKeysDown() & KEY_A)next_state = STATE_SELECT_SLOT;
				break;
			case STATE_SELECT_SLOT:
				{
					if(hidKeysDown() & KEY_UP)selected_slot++;
					if(hidKeysDown() & KEY_DOWN)selected_slot--;
					if(hidKeysDown() & KEY_A)next_state = STATE_SELECT_IRON_VERSION;

					if(selected_slot < 0) selected_slot = 0;
					if(selected_slot > 2) selected_slot = 2;

					printf((selected_slot >= 2) ? "                                             \n" : "                                            ^\n");
					printf("                            Selected slot : %d  \n", selected_slot + 1);
					printf((!selected_slot) ? "                                             \n" : "                                            v\n");
				}
				break;
			case STATE_SELECT_IRON_VERSION:
				{
					if(hidKeysDown() & KEY_UP)selected_iron_version++;
					if(hidKeysDown() & KEY_DOWN)selected_iron_version--;
					if(hidKeysDown() & KEY_A)next_state = STATE_SELECT_FIRMWARE;

					if(selected_iron_version < 0) selected_iron_version = 0;
					if(selected_iron_version > 1) selected_iron_version = 1;

					printf((selected_iron_version >= 1) ? "                                             \n" : "                                             ^\n");
					printf("                Selected IRONFALL version : 1.%d  \n", selected_iron_version);
					printf((!selected_iron_version) ? "                                             \n" : "                                             v\n");
				}
				break;
			case STATE_SELECT_FIRMWARE:
				{
					if(hidKeysDown() & KEY_LEFT)firmware_selected_value--;
					if(hidKeysDown() & KEY_RIGHT)firmware_selected_value++;

					if(firmware_selected_value < 0) firmware_selected_value = 0;
					if(firmware_selected_value >= firmware_length) firmware_selected_value = firmware_length - 1;

					if(hidKeysDown() & KEY_UP)firmware_version[firmware_selected_value]++;
					if(hidKeysDown() & KEY_DOWN)firmware_version[firmware_selected_value]--;

					if(firmware_version[firmware_selected_value] < 0) firmware_version[firmware_selected_value] = 0;
					if(firmware_version[firmware_selected_value] >= firmware_num_values[firmware_selected_value]) firmware_version[firmware_selected_value] = firmware_num_values[firmware_selected_value] - 1;
					
					if(hidKeysDown() & KEY_A)next_state = STATE_DOWNLOAD_PAYLOAD;

					int offset = 28 + firmware_format_offsets[firmware_selected_value];
					printf((firmware_version[firmware_selected_value] < firmware_num_values[firmware_selected_value] - 1) ? "%*s^%*s" : "%*s-%*s", offset, " ", 50 - offset - 1, " ");
					printf("        Selected firmware : " "%s %s-%s-%s %s" "\n", firmware_labels[0][firmware_version[0]], firmware_labels[1][firmware_version[1]], firmware_labels[2][firmware_version[2]], firmware_labels[3][firmware_version[3]], firmware_labels[4][firmware_version[4]]);
					printf((firmware_version[firmware_selected_value] > 0) ? "%*sv%*s" : "%*s-%*s", offset, " ", 50 - offset - 1, " ");
				}
				break;
			case STATE_DOWNLOAD_PAYLOAD:
				{
					httpcContext context;
					static char url[512];
					sprintf(url, "http://smealum.github.io/ninjhax2/Pvl9iD2Im5/otherapp/%s.bin", payload_name);

					Result ret = httpcOpenContext(&context, url, 0);
					if(ret)
					{
						sprintf(status, "Failed to open http context\n    Error code : %08X", (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}

					ret = http_download(&context, &payload_buf, &payload_size);
					if(ret)
					{
						sprintf(status, "Failed to download payload\n    Error code : %08X", (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}

					next_state = STATE_COMPRESS_PAYLOAD;
				}
				break;
			case STATE_COMPRESS_PAYLOAD:
				//payload_buf = BLZ_Code(payload_buf, payload_size, (unsigned int*)&payload_size, BLZ_NORMAL);
				next_state = STATE_INSTALL_PAYLOAD;
				break;
			case STATE_INSTALL_PAYLOAD:
				{
					static char filename[128];
                    
                    sprintf(filename, "save0x.bin.%s", firmware_labels[4][firmware_version[4]]);
					read_payload(filename, save_buffer);
					sprintf(filename, "/save0%d.bin", selected_slot);
					Result ret = write_savedata(filename, save_buffer, save_size);
					if(ret)
					{
						sprintf(status, "Failed to install %s.\n    Error code : %08X", filename, (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}
				}

				{
					Result ret = write_savedata("/payload.bin", payload_buf, payload_size);
					if(ret)
					{
						sprintf(status, "Failed to install payload\n    Error code : %08X", (unsigned int)ret);
						next_state = STATE_ERROR;
						break;
					}

					next_state = STATE_INSTALLED_PAYLOAD;	
				}
				break;
			case STATE_INSTALLED_PAYLOAD:
				next_state = STATE_NONE;
				break;
			default:
				break;
		}

		consoleSelect(&bttmConsole);
		printf("\x1b[0;0H  Current status :\n    %s\n", status);

		gspWaitForVBlank();
	}

	filesystemExit();

	gfxExit();
	httpcExit();
	return 0;
}
Exemple #11
0
int menu_boot() {

    time_t start, end, elapsed;
    int boot_index = config->index;

    hidScanInput();

    u32 k = hidKeysHeld();
    if (config->timeout < 0 || k & BIT(config->recovery)) { // disable autoboot
        timer = false;
    } else if (config->timeout == 0) { // autoboot
        if(k) {
            int i = 0;
            for(i=0; i<config->count; i++) {
                if(k & BIT(config->entries[i].key)) {
                    boot_index = i;
                    break;
                }
            }
        }
        return autoBootFix(boot_index);
    }

    time(&start);

    while (aptMainLoop()) {
        hidScanInput();
        u32 kDown = hidKeysDown();

        if (timer) {
            time(&end);
            elapsed = end - start;
            if (elapsed >= config->timeout
                && config->count > boot_index) {
                return autoBootFix(boot_index);
            }
        }

        if (kDown & KEY_DOWN) {
            timer = false;
            boot_index++;
            if (boot_index > config->count)
                boot_index = 0;
        }

        if (kDown & KEY_UP) {
            timer = false;
            boot_index--;
            if (boot_index < 0)
                boot_index = config->count;
        }

        if (kDown & KEY_A) {
            timer = false;
            if (boot_index == config->count) {
                if (menu_more() == 0) {
                    break;
                }
            } else {
                if (load(config->entries[boot_index].path,
                         config->entries[boot_index].offset) == 0) {
                    break;
                }
            }
        }

        if (kDown & KEY_X) {
            timer = false;
            if (boot_index != config->count) {
                if (confirm(3, "Delete boot entry: \"%s\" ?\n", config->entries[boot_index].title)) {
                    configRemoveEntry(boot_index);
                    boot_index--;
                }
            }
        }

        gfxClear();

        if (!timer) {
            gfxDrawText(GFX_TOP, GFX_LEFT, &fontDefault, "*** Select a boot entry ***", 140, 20);
        } else {
            gfxDrawTextf(GFX_TOP, GFX_LEFT, &fontDefault, 100, 20,
                         "*** Booting %s in %i ***", config->entries[boot_index].title,
                         config->timeout - elapsed);
        }

        int minX = 16, maxX = 400 - 16;
        int minY = 32, maxY = 240 - 8;
        drawRect(GFX_TOP, GFX_LEFT, minX, minY, maxX, maxY, 0xFF, 0xFF, 0xFF);
        minY += 20;

        int i;
        for (i = 0; i < config->count; i++) {
            if (i >= config->count)
                break;

            if (i == boot_index) {
                gfxDrawRectangle(GFX_TOP, GFX_LEFT, (u8[]) {0xDC, 0xDC, 0xDC}, minX + 4, minY + (16 * i), maxX - 23,
                                 15);
                gfxDrawTextf(GFX_TOP, GFX_LEFT, &fontSelected, minX + 6, minY + (16 * i), "%s",
                             config->entries[i].title);

                gfxDrawText(GFX_BOTTOM, GFX_LEFT, &fontDefault, "Informations", minX + 6, 20);
                gfxDrawTextf(GFX_BOTTOM, GFX_LEFT, &fontDefault, minX + 12, 40,
                             "Name: %s\nPath: %s\nOffset: 0x%lx\n\n\nPress (A) to launch\nPress (X) to remove entry\n",
                             config->entries[i].title,
                             config->entries[i].path,
                             config->entries[i].offset);
            }
            else
                gfxDrawText(GFX_TOP, GFX_LEFT, &fontDefault, config->entries[i].title, minX + 6, minY + (16 * i));
        }
Exemple #12
0
int main(int argc, char **argv)
{
	srvInit();	
	aptInit();
	gfxInitDefault();
	acInit();
	cfguInit();
	httpcInit();
	ptmuInit();
	hidInit();
	irrstInit();
	aptOpenSession();
	Result ret=APT_SetAppCpuTimeLimit(30);
	aptCloseSession();
	fsInit();
	ftp_state = false;
	isTopLCDOn = true;
	isBottomLCDOn = true;
	Handle fileHandle;
	u64 size;
	u32 bytesRead;
	int restore;
	
	// Check user build and enables kernel access
	if (nsInit()==0){
		CIA_MODE = true;
		nsExit();
	}else CIA_MODE = false;
	isNinjhax2 = false;
	if (!hbInit()) khaxInit();
	else isNinjhax2 = true;
	
	// Select Audio System (csnd:SND preferred)
	if (csndInit() == 0){
		csndAccess = true;
		csndExit();
	}else csndAccess = false;
	
	// Init Audio-Device
	int i = 0;
	for (i=0;i < 32; i++){
		audioChannels[i] = false;
		if (!isNinjhax2 && (i < 0x08))  audioChannels[i] = true;
		else if (csndAccess && (i < 0x08)) audioChannels[i] = true;
	}
	
	// Set main script
	char path[256];
	if (argc > 0){
		int latest_slash = 0;
		int i=5;
		while (argv[0][i]  != '\0'){
			if (argv[0][i] == '/') latest_slash = i;
			i++;
		}
		strcpy(path,&argv[0][5]);
		path[latest_slash-5] = 0;
		strcpy(start_dir,path);
		strcpy(cur_dir,path); // Set current dir
		strcat(path,"/index.lua");
	}else{
		strcpy(start_dir,"/");
		strcpy(cur_dir,"/"); // Set current dir for GW Mode
		strcpy(path,"/index.lua");
	}
	
	while(aptMainLoop())
	{
		restore=0;		
		char error[2048];		
		
		// Load main script
		FS_Path filePath=fsMakePath(PATH_ASCII, path);
		FS_Archive script=(FS_Archive){ARCHIVE_SDMC, (FS_Path){PATH_EMPTY, 1, (u8*)""}};
		Result ret = FSUSER_OpenFileDirectly(&fileHandle, script, filePath, FS_OPEN_READ, 0x00000000);
		if (!ret){
			FSFILE_GetSize(fileHandle, &size);
			buffer = (unsigned char*)(malloc((size+1) * sizeof (char)));
			FSFILE_Read(fileHandle, &bytesRead, 0x0, buffer, size);
			buffer[size]=0;
			FSFILE_Close(fileHandle);
			svcCloseHandle(fileHandle);
			errMsg = runScript((const char*)buffer, true);
			free(buffer);
		}else errMsg = "index.lua file not found.";
		
		// Force LCDs power on
		if ((!isTopLCDOn) || (!isBottomLCDOn)){
			gspLcdInit();
			if (!isTopLCDOn) GSPLCD_PowerOnBacklight(GSPLCD_SCREEN_TOP);
			if (!isBottomLCDOn) GSPLCD_PowerOnBacklight(GSPLCD_SCREEN_BOTTOM);
			gspLcdExit();
			isTopLCDOn = true;
			isBottomLCDOn = true;
		}
		
		// Fake error to force interpreter shutdown
		if (strstr(errMsg, "lpp_exit_04")) break;
			
		if (ftp_state) ftp_exit();
		ftp_state = false;
		int connfd;
		while (restore==0){
			gspWaitForVBlank();
			RefreshScreen();
			ClearScreen(0);
			ClearScreen(1);
			strcpy(error,"Error: ");
			strcat(error,errMsg);
			if (ftp_state){ 
				u32 ip=(u32)gethostid();
				char ip_address[64];
				strcat(error,"\n\nPress A to restart\nPress B to exit\nPress Y to enable FTP server\n\nFTP state: ON\nIP: ");
				sprintf(ip_address,"%lu.%lu.%lu.%lu", ip & 0xFF, (ip>>8)&0xFF, (ip>>16)&0xFF, (ip>>24)&0xFF);
				strcat(error,ip_address);
				strcat(error,"\nPort: 5000");
				if(connfd<0)connfd=ftp_getConnection();
				else{
					int ret=ftp_frame(connfd);
					if(ret==1) connfd=-1;
				}
			}else strcat(error,"\n\nPress A to restart\nPress B to exit\nPress Y to enable FTP server\n\nFTP state: OFF");
			DebugOutput(error);
			hidScanInput();
			if(hidKeysDown() & KEY_A){
				strcpy(cur_dir,start_dir);
				restore=1;
			}else if(hidKeysDown() & KEY_B){
				restore=2;
			}else if(hidKeysDown() & KEY_Y){
				if (!ftp_state){
					u32 wifiStatus;
					if ((u32)ACU_GetWifiStatus(&wifiStatus) !=  0xE0A09D2E){
						if (wifiStatus != 0){
							ftp_init();
							connfd = -1;
							ftp_state = true;
						}
					}
				}
			}
			
			gfxFlushBuffers();
			gfxSwapBuffers();
		}
		if (ftp_state) ftp_exit();
		if (isCSND){
			if (csndAccess) csndExit();
			else ndspExit();
			isCSND = false;
		}
		if (restore==2){
			break;
		}
	}
Exemple #13
0
Result configureTitle(char* cfg_path, u8* region_code, u8* language_code, u8* clock, char** romfs, char** code, u8* nim, int* nimversion)
{
	u8 mediatype = 0;
	u64 tid = 0;

	getTitleInformation(&mediatype, &tid);

	if(!tid)return -1;

	static char _fn[256];
	char* fn = _fn;
	if(cfg_path) fn = cfg_path;
	else sprintf(fn, "titles/%08X.txt", (unsigned int)(tid & 0xffffffff));

	mkdir("titles", 777);

	u8 numChoices[] = {sizeof(regions) / sizeof(regions[0]), sizeof(languages) / sizeof(languages[0]), sizeof(yesno) / sizeof(yesno[0]), sizeof(clocks) / sizeof(clocks[0]), sizeof(yesno) / sizeof(yesno[0]), sizeof(yesno) / sizeof(yesno[0]), sizeof(yesno) / sizeof(yesno[0]), 0, 0};
	int choice[] = {numChoices[0]-1, numChoices[1]-1, 1, 0, 1, 1, 1, 0, 0};

	static char romfs_path[128];
	static char code_path[128];
	static char name[16];

	// grab config name from path
	int i, j;
	int n = strlen(fn);
	for(j=n-1; j>=0; j--) if(fn[j] == '/') break;
	j++; for(i=j; i<n && fn[i] != '.' && (i-j)<10; i++) name[i-j] = fn[i];
	name[i-j] = '\0';

	snprintf(romfs_path, 128, "/hans/%s.romfs", name);
	snprintf(code_path, 128, "/hans/%s.code", name);

	Result romfsValid = checkRomfs(romfs_path);

	if(nimversion) *nimversion = 0;

	hidScanInput();

	{
		FILE* f = fopen(fn, "r");
		if(f)
		{
			static char l[256];
			while(fgets(l, sizeof(l), f))
			{
				if(sscanf(l, "region : %d", &choice[CHOICE_REGION]) != 1)
				if(sscanf(l, "language : %d", &choice[CHOICE_LANGUAGE]) != 1);
				if(sscanf(l, "nim_checkupdate : %d", &choice[CHOICE_NIMUPDATE]) != 1);
				if(nimversion && sscanf(l, "nim_version : %d", nimversion) != 1);
				if(sscanf(l, "clock : %d", &choice[CHOICE_CLOCK]) != 1);
				if(sscanf(l, "romfs : %d", &choice[CHOICE_ROMFS]) != 1);
				if(sscanf(l, "code : %d", &choice[CHOICE_CODE]) != 1);
			}
			choice[CHOICE_SAVE] = 0;

			fclose(f);

			if(!(hidKeysHeld() & KEY_L))goto end;
		}else{
			u8* smdh_data = loadSmdh(tid, mediatype);
			if(smdh_data)
			{
				choice[CHOICE_REGION] = smdhGetRegionCode(smdh_data);
				free(smdh_data);
			}
		}
	}

	consoleClear();

	int field = 0;
	while(1)
	{
		hidScanInput();

		u32 kDown = hidKeysDown();

		if((kDown & KEY_START) || ((kDown & KEY_A) && (field == CHOICE_OK || field == CHOICE_EXIT)))break;

		if(kDown & KEY_UP)field--;
		if(kDown & KEY_DOWN)field++;

		if(field < 0)field = CHOICE_NUM - 1;
		if(field >= CHOICE_NUM)field = 0;

		if(kDown & KEY_LEFT)choice[field]--;
		if(kDown & KEY_RIGHT)choice[field]++;

		if(choice[field] < 0) choice[field] = numChoices[field] - 1;
		if(choice[field] >= numChoices[field]) choice[field] = 0;

		consoleSelect(&topScreen);

		printf("\x1b[0;0H\n");
		printf(                            "               HANS             \n");
		printf("\n");
		printf(field == CHOICE_REGION ?    "  Region             : < %s > \n" : "  Region             :   %s   \n", regions[choice[CHOICE_REGION]]);
		printf(field == CHOICE_LANGUAGE ?  "  Language           : < %s > \n" : "  Language           :   %s   \n", languages[choice[CHOICE_LANGUAGE]]);
		printf(field == CHOICE_NIMUPDATE ? "  FW Version Spoof   : < %s > \n" : "  FW Version Spoof   :   %s   \n", yesno[choice[CHOICE_NIMUPDATE]]);
		printf(field == CHOICE_CLOCK ?     "  N3DS CPU clock     : < %s > \n" : "  N3DS CPU clock     :   %s   \n", clocks[choice[CHOICE_CLOCK]]);
		printf(field == CHOICE_CODE ?      "  Code  -> SD        : < %s > \n" : "  Code  -> SD        :   %s   \n", yesno[choice[CHOICE_CODE]]);
		printf(field == CHOICE_ROMFS ?     "  Romfs -> SD        : < %s > \n" : "  Romfs -> SD        :   %s   \n", yesno[choice[CHOICE_ROMFS]]);
		printf(field == CHOICE_SAVE ?      "  Save configuration : < %s > \n" : "  Save configuration :   %s   \n", yesno[choice[CHOICE_SAVE]]);
		printf(                            "                                               \n");
		printf(                            "  Current title        : %08X%08X        \n", (unsigned int)(tid >> 32), (unsigned int)(tid & 0xFFFFFFFF));
		if(!choice[CHOICE_CODE])
			printf(                        "  Code path            : sd:%s \n", code_path);
		if(!choice[CHOICE_ROMFS])
			printf(!romfsValid ?           "  Romfs path           : sd:%s\n" : "  Romfs path (INVALID) : sd:%s\n", romfs_path);
		printf(                            "                                                  ");
		printf(                            "                                                  ");
		printf(field == CHOICE_OK ?        "             > OK  \n"              : "               OK    \n");
		printf(field == CHOICE_EXIT ?      "             > EXIT\n"              : "               EXIT\n");
		printf(                            "                                               \n");
		printf(                            "                                               \n");

		consoleSelect(&bottomScreen);
		printf("\x1b[0;0H\n");
		printf("Description :\n");
		printf("    %s%*s", descriptions[field], 240 - strlen(descriptions[field]), " ");

		gfxFlushBuffers();
		gfxSwapBuffers();

		gspWaitForVBlank();
	}

	if(field == CHOICE_EXIT)return -1;

	if(choice[CHOICE_REGION] >= numChoices[CHOICE_REGION] - 1) choice[CHOICE_REGION] = -1;
	if(choice[CHOICE_LANGUAGE] >= numChoices[CHOICE_LANGUAGE] - 1) choice[CHOICE_LANGUAGE] = -1;

	if(choice[CHOICE_SAVE] == 0)
	{
		FILE* f = fopen(fn, "w");
		if(f)
		{
			fprintf(f, "region : %d\nlanguage : %d\nclock : %d\nromfs : %d\ncode : %d\nnim_checkupdate : %d\n", choice[CHOICE_REGION], choice[CHOICE_LANGUAGE], choice[CHOICE_CLOCK], choice[CHOICE_ROMFS], choice[CHOICE_CODE], choice[CHOICE_NIMUPDATE]);

			fclose(f);
		}
	}

	end:
	if(region_code)*region_code = choice[CHOICE_REGION];
	if(language_code)*language_code = choice[CHOICE_LANGUAGE];
	if(nim)*nim = choice[CHOICE_NIMUPDATE] == 0;
	if(clock)*clock = choice[CHOICE_CLOCK];
	// romfs_path and code_path are static so as long as we're not idiots this is totally fine
	if(romfs)*romfs = (choice[CHOICE_ROMFS] == 0) ? romfs_path : NULL;
	if(code)*code = (choice[CHOICE_CODE] == 0) ? code_path : NULL;

	return 0;
}
Exemple #14
0
int main(int argc, char **argv) {
    //mode
    //1 = only execute memchunkhax2
    //2 = only execute service call
    //3 = execute memchunkhax2 and service call afterwards
    //4 = execute all
    u8 mode = 4;
    u8 success;

    const char* service = "am:u";

    gfxInitDefault();
    consoleInit(GFX_TOP, NULL);

    if (mode == 1) {
      // Run the exploit
      success = execute_memchunkhax2();
      printf("Exploit returned: %s\n", success ? "Success!" : "Failure.");
    }

    if (mode == 2) {
      testService(service);
    }

    if (mode == 3) {
      // Run the exploit
      success = execute_memchunkhax2();
      printf("Exploit returned: %s\n", success ? "Success!" : "Failure.");

      testService(service);
    }

    if (mode == 4) {
      // This one should fail
      testService(service);

      // Run the exploit
      success = execute_memchunkhax2();
      printf("Exploit returned: %s\n", success ? "Success!" : "Failure.");

      // This one hopefully won't
      testService(service);
    }

    printf("Press START to reboot.\n");
    printf("Press SELECT to (try to) exit.\n");


    u8 debugFirst = 1;
    while(aptMainLoop()) {
      hidScanInput();

      if (debugFirst == 1) {
        printf("entered loop");
        debugFirst = 0;
      }

      if(hidKeysDown() & KEY_SELECT) {
        break;
      }

      if(hidKeysDown() & KEY_START) {
        //Reboot console
        aptOpenSession();
        APT_HardwareResetAsync();
        aptCloseSession();
      }

      gfxFlushBuffers();
      gfxSwapBuffers();
      gspWaitForVBlank();
    }

    gfxExit();
    return 0;
}
int main(int argc, char **argv)
{
	int abort=0;
	FILE *f = NULL;
	char *serverconfig_localpath = "server_config.xml";

	Result ret = 0;

	// Initialize services
	gfxInitDefault();

	consoleInit(GFX_TOP, NULL);

	printf("ctr-httpwn %s by yellows8.\n", VERSION);

	f = fopen(serverconfig_localpath, "rb");//Only run the below block when this file doesn't exist, which normally only happens when this app wasn't run before with the config file being downloaded successfully.
	if(f)
	{
		fclose(f);
	}
	else
	{
		printf("Please read the documentation before continuing:\nhttps://github.com/yellows8/ctr-httpwn\nPress A to continue, B to abort.\n");

		while(1)
		{
			gspWaitForVBlank();
			hidScanInput();
			if(hidKeysDown() & KEY_A)break;
			if(hidKeysDown() & KEY_B)
			{
				abort = 1;
				break;
			}
		}
	}

	if(!abort)
	{
		ret = httpwn_setup(serverconfig_localpath);

		if(ret==0)printf("Done.\n");
	}

	if(ret==0xC920181A)printf("This error means the HTTP sysmodule crashed.\n");
	if(ret!=0)printf("An error occured. If this is an actual issue not related to user failure, please report this to here if it persists(or comment on an already existing issue if needed), with a screenshot: https://github.com/yellows8/ctr-httpwn/issues\n");

	printf("Press the START button to exit.\n");
	// Main loop
	while (aptMainLoop())
	{
		gspWaitForVBlank();
		hidScanInput();

		u32 kDown = hidKeysDown();
		if (kDown & KEY_START)
			break; // break in order to return to hbmenu
	}

	// Exit services
	gfxExit();
	return 0;
}
Exemple #16
0
int main() {
    srvInit();
    aptInit();
    hidInit(NULL);
    gfxInitDefault();
    resetGame();
    int x;
    while (aptMainLoop()) {
        hidScanInput();
        hidTouchRead(&touch);
        u32 kDown = hidKeysDown();
        //u32 kHeld = hidKeysHeld(); Not used an otherwise you'll get warning during compile, this makes compile more pleasant to look at yea!
        if (state != 0 && cur_row != 7) {
            if (secretCode() && state != 3)
                cheat=1;
            if (kDown & KEY_TOUCH) {
                cur_visable=false;
            }

            if (kDown & KEY_RIGHT) {
                cur_field+=1;
                if (cur_field > 3)
                    cur_field=0;
                cur_visable=true;
            }
            if (kDown & KEY_LEFT) {
                cur_field-=1;
                if (cur_field < 0)
                    cur_field=3;
                cur_visable=true;
            }
            if (kDown & KEY_UP) {
                local_field[cur_field]+=1;
                if (local_field[cur_field] > col_amount)
                    local_field[cur_field]=1;
                cur_visable=true;
            }
            if (kDown & KEY_DOWN) {
                local_field[cur_field]-=1;
                if (local_field[cur_field] < 1)
                    local_field[cur_field]=col_amount;
                cur_visable=true;
            }
            if (kDown & KEY_A)
                submitTry();
            if (touchInBox(touch,231,163,84,44))
                submitTry();

            if (touchInBox(touch,7,28,71,16)) {
                local_field[0]+=1;
                if (local_field[0] > col_amount)
                    local_field[0]=1;
            }
            if (touchInBox(touch,85,28,71,16)) {
                local_field[1]+=1;
                if (local_field[1] > col_amount)
                    local_field[1]=1;
            }
            if (touchInBox(touch,163,28,71,16)) {
                local_field[2]+=1;
                if (local_field[2] > col_amount)
                    local_field[2]=1;
            }
            if (touchInBox(touch,241,28,71,16)) {
                local_field[3]+=1;
                if (local_field[3] > col_amount)
                    local_field[3]=1;
            }
            if (touchInBox(touch,7,119,71,16)) {
                local_field[0]-=1;
                if (local_field[0] <= 0)
                    local_field[0]=col_amount;
            }
            if (touchInBox(touch,85,119,71,16)) {
                local_field[1]-=1;
                if (local_field[1] <= 0)
                    local_field[1]=col_amount;
            }
            if (touchInBox(touch,163,119,71,16)) {
                local_field[2]-=1;
                if (local_field[2] <= 0)
                    local_field[2]=col_amount;
            }
            if (touchInBox(touch,241,119,71,16)) {
                local_field[3]-=1;
                if (local_field[3] <= 0)
                    local_field[3]=col_amount;
            }
            if (state != 2) {
                for (x=0; x < 4; x++) {
                    full_field[cur_row*4+x]=local_field[x];
                }
            }
        } else if (state == 0) {
            if (touchInBox(touch,65,66,98,34))
                modeselector=1;
            if (touchInBox(touch,65,102,98,34))
                modeselector=2;
            if (modeselector != 0) {
                if (touchInBox(touch,168,65,88,22)) {
                    difficulty=0;
                    startGame(modeselector);
                }
                if (touchInBox(touch,168,90,88,22)) {
                    difficulty=1;
                    startGame(modeselector);
                }
                if (touchInBox(touch,168,125,88,22)) {
                    difficulty=2;
                    startGame(modeselector);
                }
            }
        }

        if (touchInBox(touch,0,211,320,30)) {
            resetGame();
            state=0;
            modeselector=0;
        }
        if (touchInBox(touch,0,0,74,21))
            break;

        render(full_field, full_judgement, local_field, cur_field, cur_row, cur_visable, ans, win, cheat, state, modeselector);
        gfxFlushBuffers();
        gfxSwapBuffers();
        gspWaitForEvent(GSPEVENT_VBlank0, false);
    }
    gfxExit();
    hidExit();
    aptExit();
    srvExit();
    return 0;
}
Exemple #17
0
int menu_more() {

    menu_index = 0;

    while (aptMainLoop()) {

        hidScanInput();
        u32 kDown = hidKeysDown();

        if (kDown & KEY_DOWN) {
            menu_index++;
            if (menu_index >= menu_count)
                menu_index = 0;
        }

        if (kDown & KEY_UP) {
            menu_index--;
            if (menu_index < 0)
                menu_index = menu_count - 1;
        }

        if (kDown & KEY_A) {
            if (menu_index == 0 && menu_choose() == 0) {
                return 0;
            } else if (menu_index == 1 && menu_netloader() == 0) {
                return 0;
            } else if (menu_index == 2) {
                menu_config();
            } else if (menu_index == 3) {
                reboot();
            } else if (menu_index == 4) {
                poweroff();
            }
        }

        if (kDown & KEY_B) {
            return -1;
        }

        gfxClear();
        gfxDrawText(GFX_TOP, GFX_LEFT, &fontDefault, "*** Select an option ***", 140, 20);

        int minX = 16;
        int maxX = 400 - 16;
        int minY = 32;
        int maxY = 240 - 16;
        drawRect(GFX_TOP, GFX_LEFT, minX, minY, maxX, maxY, 0xFF, 0xFF, 0xFF);
        minY += 20;

        int i;
        for (i = 0; i < menu_count; i++) {
            if (i >= menu_count) break;

            if (i == menu_index) {
                gfxDrawRectangle(GFX_TOP, GFX_LEFT, (u8[]) {
                    0xDC, 0xDC, 0xDC
                }, minX + 4, minY + (16 * i), maxX - 23,
                15);
                gfxDrawText(GFX_TOP, GFX_LEFT, &fontSelected, menu_item[i], minX + 6, minY + (16 * i));
            }
            else
                gfxDrawText(GFX_TOP, GFX_LEFT, &fontDefault, menu_item[i], minX + 6, minY + (16 * i));
        }
Exemple #18
0
//----------------------------------------------------------------------------
int main(int argc, char **argv) {
//----------------------------------------------------------------------------

	PrintConsole topScreen;
	ndspWaveBuf waveBuf[2];

	gfxInitDefault();

	consoleInit(GFX_TOP, &topScreen);

	consoleSelect(&topScreen);

	printf("libctru streaming audio\n");
	
	
	
	stb_vorbis_info info;
	int error;


      vorbisFile = stb_vorbis_open_filename("/mau5.ogg", &error, NULL);
      info = stb_vorbis_get_info(vorbisFile);
      Samples = info.sample_rate;
   
	

	u32 *audioBuffer = (u32*)linearAlloc(Samples*sizeof(s16)*2);

	bool fillBlock = false;

	ndspInit();

	ndspSetOutputMode(NDSP_OUTPUT_STEREO);

	ndspChnSetInterp(0, NDSP_INTERP_LINEAR);
	ndspChnSetRate(0, Samples);
	ndspChnSetFormat(0, NDSP_FORMAT_STEREO_PCM16);

	float mix[12];
	memset(mix, 0, sizeof(mix));
	mix[0] = 1.0;
	mix[1] = 1.0;
	ndspChnSetMix(0, mix);

	int note = 4;

	memset(waveBuf,0,sizeof(waveBuf));
	waveBuf[0].data_vaddr = &audioBuffer[0];
	waveBuf[0].nsamples = Samples;
	waveBuf[1].data_vaddr = &audioBuffer[Samples];
	waveBuf[1].nsamples = Samples;

	ndspChnWaveBufAdd(0, &waveBuf[0]);
	ndspChnWaveBufAdd(0, &waveBuf[1]);

	printf("Press up/down to change tone\n");

	
	
	
	
	
	
	while(aptMainLoop()) {

		gfxSwapBuffers();
		gfxFlushBuffers();
		gspWaitForVBlank();

		hidScanInput();
		u32 kDown = hidKeysDown();

		if (kDown & KEY_START)
			break; // break in order to return to hbmenu


		if (waveBuf[fillBlock].status == NDSP_WBUF_DONE) {

			fill_buffer(waveBuf[fillBlock].data_pcm16, waveBuf[fillBlock].nsamples);

			ndspChnWaveBufAdd(0, &waveBuf[fillBlock]);

			fillBlock = !fillBlock;
		}
	}

	ndspExit();

	linearFree(audioBuffer);

	gfxExit();
	return 0;
}
Exemple #19
0
int main()
{
	Handle rsrc;
	bool failed = true;

	gfxInitDefault();
	consoleInit(GFX_TOP, NULL);

	printf("\x1b[10;10HFetching DSP component...\x1b[12;10H");

	rsrc = envGetHandle("hb:ndsp");
	if (!rsrc)
	{
		printf("\x1b[31;1mFailed\x1b[0m: Need to run using *hax 2.0+");
	}
	else do
	{
		Result rc;
		u32 len;
		void* bin;
		extern u32 fake_heap_end;
		char* filename = "sdmc:/3ds/dspfirm.cdc";

		u32 mapAddr = (fake_heap_end+0xFFF) &~ 0xFFF;
		rc = svcMapMemoryBlock(rsrc, mapAddr, 0x3, 0x3);
		if (R_FAILED(rc)) break;

		len = *(u32*)(mapAddr + 0x104);
		bin = malloc(len);
		if (bin)
			memcpy(bin, (void*)mapAddr, len);
		svcUnmapMemoryBlock(rsrc, mapAddr);
		if (!bin) break;

		FILE* file = fopen(filename, "wb");
		if (!file) break;
		fwrite(bin, 1, len, file);
		fclose(file);

		failed = false;
		printf("\x1b[32;1mDone\x1b[0m: No further steps needed!\n");
		free(bin);
	} while (0);

	if (rsrc && failed)
		printf("\x1b[31;1mFailed\x1b[0m: Unknown error. Try again.");

	printf("\x1b[28;15HPress START to exit.");

	while (aptMainLoop())
	{
		hidScanInput();
		u32 kDown = hidKeysDown();

		if (kDown & KEY_START)
			break;

		gfxFlushBuffers();
		gfxSwapBuffers();
		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}
Exemple #20
0
int main() 
{
	int i, x, y;
	
	touchPosition lastTouch;
	u32 repeatkeys = 0;
	int repeatstate = 0;
	int repeatcount = 0;
	
	running = 0;
	pause = 0;
	exitemu = 0;
	
	
		
	PPU_Init();
	
	
	srvInit();
		
	aptInit();
	aptOpenSession();
	APT_SetAppCpuTimeLimit(NULL, 30); // enables syscore usage
	aptCloseSession();

	gfxInit();
	hidInit(NULL);
	fsInit();
	
	GPU_Init(NULL);
	gpuCmdSize = 0x40000;
	gpuCmd = (u32*)linearAlloc(gpuCmdSize*4);
	GPU_Reset(gxCmdBuf, gpuCmd, gpuCmdSize);
	
	shader = SHDR_ParseSHBIN((u32*)blarg_shbin, blarg_shbin_size);
	
	GX_SetMemoryFill(gxCmdBuf, (u32*)gpuOut, 0x404040FF, (u32*)&gpuOut[0x2EE00], 0x201, (u32*)gpuDOut, 0x00000000, (u32*)&gpuDOut[0x2EE00], 0x201);
	gfxSwapBuffersGpu();
	
	UI_SetFramebuffer(gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL));
	
	BorderTex = (u32*)linearAlloc(512*256*4);
	MainScreenTex = (u32*)linearAlloc(512*256*4);
	SubScreenTex = (u32*)linearAlloc(512*256*4);
	BrightnessTex = (u8*)linearAlloc(8*256);
	
	borderVertices = (float*)linearAlloc(5*3 * 2 * sizeof(float));
	screenVertices = (float*)linearAlloc(7*3 * 2 * sizeof(float));
	
	float* fptr = &vertexList[0];
	for (i = 0; i < 5*3*2; i++) borderVertices[i] = *fptr++;
	for (i = 0; i < 7*3*2; i++) screenVertices[i] = *fptr++;
	

	sdmcArchive = (FS_archive){0x9, (FS_path){PATH_EMPTY, 1, (u8*)""}};
	FSUSER_OpenArchive(NULL, &sdmcArchive);
	
	if (!LoadBorder("/blargSnesBorder.bmp"))
		CopyBitmapToTexture(defaultborder, BorderTex, 400, 240, 0xFF, 0, 64, true);
		
	CopyBitmapToTexture(screenfill, PPU_MainBuffer, 256, 224, 0, 16, 64, false);
	memset(PPU_SubBuffer, 0, 256*256*4);
	memset(PPU_Brightness, 0xFF, 224);
	
	UI_Switch(&UI_ROMMenu);
	
	svcCreateEvent(&SPCSync, 0);
	
	aptSetupEventHandler();

	
	APP_STATUS status;
	while((status = aptGetStatus()) != APP_EXITING)
	{
		if(status == APP_RUNNING)
		{
			svcSignalEvent(SPCSync);
			
			hidScanInput();
			u32 press = hidKeysDown();
			u32 held = hidKeysHeld();
			u32 release = hidKeysUp();
			
			GPUCMD_SetBuffer(gpuCmd, gpuCmdSize, 0);
			RenderTopScreen();
			GPUCMD_Finalize();
			GPUCMD_Run(gxCmdBuf);
			
			if (running)
			{
				// emulate
				
				CPU_Run(); // runs the SNES for one frame. Handles PPU rendering.
				
				// SRAM autosave check
				// TODO: also save SRAM under certain circumstances (pausing, returning to home menu, etc)
				framecount++;
				if (!(framecount & 7))
					SNES_SaveSRAM();
			}
			else
			{
				// update UI
				
				if (held & KEY_TOUCH)
				{
					hidTouchRead(&lastTouch);
					UI_Touch(true, lastTouch.px, lastTouch.py);
					held &= ~KEY_TOUCH;
				}
				else if (release & KEY_TOUCH)
				{
					UI_Touch(false, lastTouch.px, lastTouch.py);
					release &= ~KEY_TOUCH;
				}
				
				if (press)
				{
					UI_ButtonPress(press);
					
					// key repeat
					repeatkeys = press & (KEY_UP|KEY_DOWN|KEY_LEFT|KEY_RIGHT);
					repeatstate = 1;
					repeatcount = 15;
				}
				else if (held == repeatkeys)
				{
					repeatcount--;
					if (!repeatcount)
					{
						repeatcount = 7;
						if (repeatstate == 2)
							UI_ButtonPress(repeatkeys);
						else
							repeatstate = 2;
					}
				}
			}
			
			UI_SetFramebuffer(gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL));
			UI_Render();
			
			/*GPUCMD_SetBuffer(gpuCmd, gpuCmdSize, 0);
			RenderTopScreen();
			GPUCMD_Finalize();
			GPUCMD_Run(gxCmdBuf);*/
			
			// flush the bottomscreen cache while the PICA200 is busy rendering
			GSPGPU_FlushDataCache(NULL, gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL), 0x38400);
			
			// wait for the PICA200 to finish drawing
			gspWaitForP3D();
			
			// copy new screen textures
			// SetDisplayTransfer with flags=2 converts linear graphics to the tiled format used for textures
			GX_SetDisplayTransfer(gxCmdBuf, PPU_MainBuffer, 0x01000200, MainScreenTex, 0x01000200, 0x2);
			gspWaitForPPF();
			GX_SetDisplayTransfer(gxCmdBuf, PPU_SubBuffer, 0x01000200, SubScreenTex, 0x01000200, 0x2);
			gspWaitForPPF();
			
			// copy brightness.
			// TODO do better
			u8* bptr = BrightnessTex;
			for (i = 0; i < 224;)
			{
				u32 pixels = *(u32*)&PPU_Brightness[i];
				i += 4;
				
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 2;
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 6;
				
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 2;
				*bptr = (u8)pixels;
				pixels >>= 8;
				bptr += 22;
			}
			
			// transfer the final color buffer to the LCD and clear it
			// we can mostly overlap those two operations
			GX_SetDisplayTransfer(gxCmdBuf, gpuOut, 0x019001E0, (u32*)gfxGetFramebuffer(GFX_TOP, GFX_LEFT, NULL, NULL), 0x019001E0, 0x01001000);
			svcSleepThread(20000);
			GX_SetMemoryFill(gxCmdBuf, gpuOut, 0x404040FF, &gpuOut[0x2EE00], 0x201, gpuDOut, 0x00000000, &gpuDOut[0x2EE00], 0x201);
			gspWaitForPPF();
			gspWaitForPSC0();

			gspWaitForEvent(GSPEVENT_VBlank0, false);
			gfxSwapBuffersGpu();
		}
		else if(status == APP_SUSPENDING)
Exemple #21
0
static void eventThreadFunc(void *arg) {
	OSystem_3DS *osys = (OSystem_3DS *)g_system;
	auto eventQueue = (Common::Queue<Common::Event> *)arg;
	
	uint32 touchStartTime = osys->getMillis();
	touchPosition lastTouch = {0, 0};
	bool isRightClick = false;
	float cursorX = 0;
	float cursorY = 0;
	float cursorDeltaX = 0;
	float cursorDeltaY = 0;
	int circleDeadzone = 20;
	int borderSnapZone = 6;
	Common::Event event;
	
	while (!osys->exiting) {
		do {
			osys->delayMillis(10);
		} while (osys->sleeping && !osys->exiting);
		
		hidScanInput();
		touchPosition touch;
		circlePosition circle;
		u32 held = hidKeysHeld();
		u32 keysPressed = hidKeysDown();
		u32 keysReleased = hidKeysUp();
		
		// C-Pad used to control the cursor
		hidCircleRead(&circle);
		if (circle.dx < circleDeadzone && circle.dx > -circleDeadzone)
			circle.dx = 0;
		if (circle.dy < circleDeadzone && circle.dy > -circleDeadzone)
			circle.dy = 0;
		cursorDeltaX = (0.0002f + config.sensitivity / 100000.f) * circle.dx * abs(circle.dx);
		cursorDeltaY = (0.0002f + config.sensitivity / 100000.f) * circle.dy * abs(circle.dy);
		
		// Touch screen events
		if (held & KEY_TOUCH) {
			hidTouchRead(&touch);
			if (config.snapToBorder) {
				if (touch.px < borderSnapZone)
					touch.px = 0;
				if (touch.px > 319 - borderSnapZone)
					touch.px = 319;
				if (touch.py < borderSnapZone)
					touch.py = 0;
				if (touch.py > 239 - borderSnapZone)
					touch.py = 239;
			}
			cursorX = touch.px;
			cursorY = touch.py;
			osys->transformPoint(touch);

			osys->warpMouse(touch.px, touch.py);
			event.mouse.x = touch.px;
			event.mouse.y = touch.py;
			
			if (keysPressed & KEY_TOUCH) {
				touchStartTime = osys->getMillis();
				isRightClick = (held & KEY_X || held & KEY_DUP);
				if (inputMode == MODE_DRAG) {
					event.type = isRightClick ? Common::EVENT_RBUTTONDOWN : Common::EVENT_LBUTTONDOWN;
					pushEventQueue(eventQueue, event);
				}
			} else if (touch.px != lastTouch.px || touch.py != lastTouch.py) {
				event.type = Common::EVENT_MOUSEMOVE;
				pushEventQueue(eventQueue, event);
			}
			
			lastTouch = touch;
		} else if (keysReleased & KEY_TOUCH) {
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			if (inputMode == MODE_DRAG) {
				event.type = isRightClick ? Common::EVENT_RBUTTONUP : Common::EVENT_LBUTTONUP;
				pushEventQueue(eventQueue, event);
			} else if (osys->getMillis() - touchStartTime < 200) {
				// Process click in MODE_HOVER
				event.type = Common::EVENT_MOUSEMOVE;
				pushEventQueue(eventQueue, event);
				event.type = isRightClick ? Common::EVENT_RBUTTONDOWN : Common::EVENT_LBUTTONDOWN;
				pushEventQueue(eventQueue, event);
				event.type = isRightClick ? Common::EVENT_RBUTTONUP : Common::EVENT_LBUTTONUP;
				pushEventQueue(eventQueue, event);
			}
		} else if (cursorDeltaX != 0 || cursorDeltaY != 0) {
			cursorX += cursorDeltaX;
			cursorY -= cursorDeltaY;
			if (cursorX < 0) cursorX = 0;
			if (cursorY < 0) cursorY = 0;
			if (cursorX > 320) cursorX = 320;
			if (cursorY > 240) cursorY = 240;
			lastTouch.px = cursorX;
			lastTouch.py = cursorY;
			osys->transformPoint(lastTouch);
			osys->warpMouse(lastTouch.px, lastTouch.py); 
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			event.type = Common::EVENT_MOUSEMOVE;
			pushEventQueue(eventQueue, event);
		}
		
		// Button events
		if (keysPressed & KEY_R) {
			if (inputMode == MODE_DRAG) {
				inputMode = MODE_HOVER;
				osys->displayMessageOnOSD("Hover Mode");
			} else {
				inputMode = MODE_DRAG;
				osys->displayMessageOnOSD("Drag Mode");
			}
		}
		if (keysPressed & KEY_A || keysPressed & KEY_DLEFT || keysReleased & KEY_A || keysReleased & KEY_DLEFT) {
			// SIMULATE LEFT CLICK
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			if (keysPressed & KEY_A || keysPressed & KEY_DLEFT)
				event.type = Common::EVENT_LBUTTONDOWN;
			else
				event.type = Common::EVENT_LBUTTONUP;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_X || keysPressed & KEY_DUP || keysReleased & KEY_X || keysReleased & KEY_DUP) {
			// SIMULATE RIGHT CLICK
			event.mouse.x = lastTouch.px;
			event.mouse.y = lastTouch.py;
			if (keysPressed & KEY_X || keysPressed & KEY_DUP)
				event.type = Common::EVENT_RBUTTONDOWN;
			else
				event.type = Common::EVENT_RBUTTONUP;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_L) {
			event.type = Common::EVENT_VIRTUAL_KEYBOARD;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_START) {
			event.type = Common::EVENT_MAINMENU;
			pushEventQueue(eventQueue, event);
		}
		if (keysPressed & KEY_SELECT) {
			if (!optionMenuOpened)
				optionMenuOpening = true;
		}
		if (keysPressed & KEY_B || keysReleased & KEY_B || keysPressed & KEY_DDOWN || keysReleased & KEY_DDOWN) {
			if (keysPressed & KEY_B || keysPressed & KEY_DDOWN)
				event.type = Common::EVENT_KEYDOWN;
			else
				event.type = Common::EVENT_KEYUP;
			event.kbd.keycode = Common::KEYCODE_ESCAPE;
			event.kbd.ascii = Common::ASCII_ESCAPE;
			event.kbd.flags = 0;
			pushEventQueue(eventQueue, event);
		}
		
		// TODO: EVENT_PREDICTIVE_DIALOG
		// EVENT_SCREEN_CHANGED
	}
}
Exemple #22
0
int drawAlert(char * title, char * body, u8 * image, int numButtons,  char buttonTitles[3][32]) {
    //int ret = alertButtonNone;

    if (hidKeysDown()&KEY_A) {
        return alertSelectedButton;
    }

    if (hidKeysDown()&KEY_B) {
        return alertButtonKeyB;
    }

    if (hidKeysDown()&KEY_DOWN) {
        alertSelectedButton++;
        if (alertSelectedButton >= numButtons) {
            alertSelectedButton = 0;
        }
    }

    if (hidKeysDown()&KEY_UP) {
        alertSelectedButton--;
        if (alertSelectedButton < 0) {
            alertSelectedButton = numButtons-1;
        }
    }

    MAGFXDrawPanel(GFX_TOP, true);
    MAGFXDrawPanel(GFX_BOTTOM, false);

    MAFont font = MAFontRobotoRegular16;
    int leftOffset = 30;
    int topOffset = 240 - 50 - font.lineHeight;

    rgbColour * textCol = titleTextColour();
    MADrawText(GFX_TOP, GFX_LEFT, topOffset, leftOffset, title, &font, textCol->r, textCol->g, textCol->b);

    font = MAFontRobotoRegular10;
    topOffset -= font.lineHeight * 2;

    int totalWidthForText = 400;

    rgbColour * dark = darkTextColour();

    MADrawTextWrap(GFX_TOP, GFX_LEFT, topOffset, leftOffset, body, &font, dark->r, dark->g, dark->b, totalWidthForText-(2*leftOffset), 0);
    //MADrawTextWrap(GFX_TOP, GFX_LEFT, topOffset, leftOffset, body, &font, dark->r, dark->g, dark->b, totalWidthForText, 0);


    /*
        WEIRD BUG ALERT!

        It was discovered that some alerts did not display their body text.
        In the process of trying to work out what was happening, I created
        a string containing the number of lines drawn by MADrawTextWrap and
        drew this on the screen so I could see what was actually happening.
        When I did this, the body text started appearing as well as the text
        showing how many lines it had drawn. I then found that it was the
        process of creating a string and putting something in it which was
        allowing the text to be drawn. I actually have no idea why this fixes
        the bug with drawing the body text. It feels like a memory management
        thing, but I can't figure it out.
    */

    char s[64];
    strcpy(s, "5");

    int screenHeight = 240;
    int screenWidth = 320;

    int buttonGap = 10;

    int totalHeight = (numButtons*btnRectWidth) + ((numButtons-1)*buttonGap);
    int diff = screenHeight-totalHeight;

    int x = screenHeight - (diff/2) - btnRectWidth;
    int y = (screenWidth/2) - (btnRectHeight/2);

    touchPosition touch;
    hidTouchRead(&touch);
    int touchX = touch.px;
    int touchY = touch.py;

    int i;

    for (i=0; i<numButtons; i++) {
        button * aButton = malloc(sizeof(button));
        btnSetButtonType(aButton, btnButtonTypeRect);
        strcpy(aButton->longText, buttonTitles[i]);
        strcpy(aButton->shortText1, "");
        strcpy(aButton->shortText2, "");
        aButton->x = x;
        aButton->y = y;
        aButton->highlighted = (i == alertSelectedButton);
        aButton->selected = false;
        x -= (btnRectWidth+buttonGap);

        btnDrawButton(aButton);

        if (!touchesAreBlocked && hidKeysDown()&KEY_TOUCH && btnTouchWithin(touchX, touchY, aButton)) {
            if (i == alertSelectedButton) {
                return alertSelectedButton;
            }
            else {
                alertSelectedButton = i;
            }
        }

        free(aButton);


    }

    return alertButtonNone;
}
Exemple #23
0
void mvd_video()
{
	Result ret;
	size_t video_size, nalunitsize;
	u32 video_pos=0;
	u32 cur_nalunit_pos=0, prev_nalunit_pos=0;
	u32 nalcount=0;
	u8 *video;

	u32 flagval=0;

	FILE *f = NULL;

	u8* gfxtopadr=NULL;

	MVDSTD_Config config;

	u32 prefix_offset;
	u8 prefix[4] = {0x00, 0x00, 0x00, 0x01};

	printf("Loading video...\n");

	//This loads the entire video into memory, normally you'd use a library to stream it.
	f = fopen("romfs:/video.h264", "r");
	if(f==NULL)
	{
		printf("Faile to open the video in romfs.\n");
		return;
	}

	video = &inaddr[0x100000];
	video_size = fread(video, 1, 0xF00000, f);
	fclose(f);

	if(video_size==0 || video_size>=0xF00000)
	{
		printf("Failed to read video / video is too large.\n");
		return;
	}

	ret = mvdstdInit(MVDMODE_VIDEOPROCESSING, MVD_INPUT_H264, MVD_OUTPUT_BGR565, MVD_DEFAULT_WORKBUF_SIZE, NULL);
	printf("mvdstdInit(): 0x%08x\n", (unsigned int)ret);
	if(ret!=0)return;

	printf("Processing 0x%08x-byte video...\n", (unsigned int)video_size);

	mvdstdGenerateDefaultConfig(&config, 240, 400, 240, 400, NULL, (u32*)outaddr, (u32*)outaddr);//Normally you'd set the input dimensions here to dimensions loaded from the actual video.

	//Normally you'd use a library to load each NAL-unit, this example just parses the data manually.
	while(video_pos < video_size+1)
	{
		cur_nalunit_pos = video_pos;
		video_pos++;

		prefix_offset = 1;

		if(cur_nalunit_pos<video_size)
		{
			/*
			{
				if(memcmp(&video[cur_nalunit_pos], &prefix[1], 3)==0 && cur_nalunit_pos==0x2dd)
				{
					prefix_offset = 0;
				}
			}
			if(prefix_offset)*/
			//else
			{
				if(memcmp(&video[cur_nalunit_pos], prefix, 4))
				{
					continue;
				}
				else
				{
					video_pos++;
				}
			}
		}

		if(nalcount && prev_nalunit_pos!=cur_nalunit_pos)
		{
			nalunitsize = cur_nalunit_pos - prev_nalunit_pos - prefix_offset;
			if(nalunitsize > 0x100000)
			{
				printf("The NAL-unit at offset 0x%08x is too large.\n", (unsigned int)nalunitsize);
				break;
			}

			memcpy(inaddr, &video[prev_nalunit_pos+prefix_offset], nalunitsize);
			GSPGPU_FlushDataCache(inaddr, nalunitsize);

			MVDSTD_ProcessNALUnitOut tmpout;//Normally you don't really need to use this.

			//printf("Processing NAL-unit at offset 0x%08x size 0x%08x...\n", (unsigned int)prev_nalunit_pos, (unsigned int)nalunitsize);
			ret = mvdstdProcessVideoFrame(inaddr, nalunitsize, flagval, &tmpout);
			if(!MVD_CHECKNALUPROC_SUCCESS(ret))
			{
				printf("mvdstdProcessVideoFrame() at NAL-unit offset 0x%08x size 0x%08x returned: 0x%08x. remaining_size=0x%08x.\n", (unsigned int)prev_nalunit_pos, (unsigned int)nalunitsize, (unsigned int)ret, (unsigned int)tmpout.remaining_size);
				break;
			}

			if(ret!=MVD_STATUS_PARAMSET && ret!=MVD_STATUS_INCOMPLETEPROCESSING)
			{
				gfxtopadr = gfxGetFramebuffer(GFX_TOP, GFX_LEFT, NULL, NULL);
				config.physaddr_outdata0 = osConvertVirtToPhys(gfxtopadr);

				//This sets the MVD output to the framebuffer directly. This is to avoid doing the video->framebuffer image rotation on the ARM11.
				//Normally you'd use a seperate MVD output buffer, then transfer that to the framebuffer(such as with GPU rendering).

				ret = mvdstdRenderVideoFrame(&config, true);
				if(ret!=MVD_STATUS_OK)
				{
					printf("mvdstdRenderVideoFrame() at NAL-unit offset 0x%08x returned: 0x%08x\n", (unsigned int)prev_nalunit_pos, (unsigned int)ret);
					break;
				}

				hidScanInput();
				if(hidKeysDown() & KEY_B)break;

				//Enable/disable the flag passed to mvdstdProcessVideoFrame().
				if(hidKeysDown() & KEY_DOWN)
				{
					flagval-= 0x1;
					printf("0x%08x\n", (unsigned int)flagval);
				}
				if(hidKeysDown() & KEY_UP)
				{
					flagval+= 0x1;
					printf("0x%08x\n", (unsigned int)flagval);
				}

				//gspWaitForVBlank();//Can't use this under this example without a major slowdown. This is due to this example not doing any buffering for the frames.
				gfxSwapBuffersGpu();
			}
		}

		nalcount++;

		prev_nalunit_pos = cur_nalunit_pos;
	}

	mvdstdExit();
}
Exemple #24
0
int main(int argc, char *argv[])
{
//    char filename[]="/test400x240-mpeg4-witch.mp4";
//    char filename[]="/test400x240-witch.mp4";
//    char filename[]="/test800x400-witch-900kbps.mp4";
//    char filename[]="/test800x400-witch-1pass.mp4";
//    char filename[]="/test800x400-witch.mp4";
//    char filename[]="/test800x480-witch-mpeg4.mp4";
//    char filename[]="/test320x176-karanokyoukai.mp4";
    char filename[] = "/test.mp4";

    MovieState mvS;

    initServices();

    // Register all formats and codecs
    av_register_all();
    av_log_set_level(AV_LOG_INFO);


    printf("Press start to open the file\n");
    waitForStart();
    int ret = setup(&mvS, filename);
    if (ret)
    {
        waitForStartAndExit();
        return -1;
    }

    printf("Press start to decompress\n");
    waitForStart();
    // Read frames and save first five frames to disk
    int i = 0;
    int frameFinished;

    u64 timeBeginning, timeEnd;
    u64 timeBefore, timeAfter;
    u64 timeDecodeTotal = 0, timeScaleTotal = 0, timeDisplayTotal = 0;

    timeBefore = osGetTime();
    timeBeginning = timeBefore;
    bool stop = false;

    while (av_read_frame(mvS.pFormatCtx, &mvS.packet) >= 0 && !stop)
    {
        // Is this a packet from the video stream?
        if (mvS.packet.stream_index == mvS.videoStream)
        {

            /*********************
             * Decode video frame
             *********************/

            int err = avcodec_decode_video2(mvS.pCodecCtx, mvS.pFrame, &frameFinished, &mvS.packet);
            if (err <= 0)printf("decode error\n");
            // Did we get a video frame?
            if (frameFinished)
            {
                err = av_frame_get_decode_error_flags(mvS.pFrame);
                if (err)
                {
                    char buf[100];
                    av_strerror(err, buf, 100);
                }
                timeAfter = osGetTime();
                timeDecodeTotal += timeAfter - timeBefore;

                /*******************************
                 * Conversion of decoded frame
                 *******************************/
                timeBefore = osGetTime();
                colorConvert(&mvS);
                timeAfter = osGetTime();

                /***********************
                 * Display of the frame
                 ***********************/
                timeScaleTotal += timeAfter - timeBefore;
                timeBefore = osGetTime();

                if (mvS.renderGpu)
                {
                    gpuRenderFrame(&mvS);
                    gpuEndFrame();
                }
                else display(mvS.outFrame);

                timeAfter = osGetTime();
                timeDisplayTotal += timeAfter - timeBefore;

                ++i;//New frame

                hidScanInput();
                u32 kDown = hidKeysDown();
                if (kDown & KEY_START)
                    stop = true; // break in order to return to hbmenu
                if (i % 50 == 0)printf("frame %d\n", i);
                timeBefore = osGetTime();
            }

        }

        // Free the packet that was allocated by av_read_frame
        av_free_packet(&mvS.packet);
    }
    timeEnd = timeBefore;

    tearup(&mvS);

    printf("Played %d frames in %f s (%f fps)\n",
           i, (timeEnd - timeBeginning) / 1000.0,
           i / ((timeEnd - timeBeginning) / 1000.0));
    printf("\tdecode:\t%llu\t%f perframe"
           "\n\tscale:\t%llu\t%f perframe"
           "\n\tdisplay:\t%llu\t%f perframe\n",
           timeDecodeTotal, timeDecodeTotal / (double) i,
           timeScaleTotal, timeScaleTotal / (double) i,
           timeDisplayTotal, timeDisplayTotal / (double) i);

    waitForStartAndExit();
    return 0;
}
Exemple #25
0
int main() {

	L = luaL_newstate();
	luaL_openlibs(L);
	luaL_requiref(L, "love", initLove, 1);

	sf2d_init(); // 2D Drawing lib.
	sftd_init(); // Text Drawing lib.
	cfguInit();
	ptmuInit();

	// consoleInit(GFX_BOTTOM, NULL);

	sf2d_set_clear_color(RGBA8(0x0, 0x0, 0x0, 0xFF)); // Reset background color.

	osSetSpeedupEnable(true); // Enables CPU speedup for a free performance boost.

	// Detect if we are running on a .cia, because if we are
	// we load from RomFS rather than the SD Card.
	// TODO: Load RomFS from .3dsx's aswell.

	Result rc = romfsInit();

	romfsExists = (rc) ? false : true;

	// Change working directory

	if (romfsExists) {

		chdir("romfs:/");

	} else {

		char cwd[256];
		getcwd(cwd, 256);
		char newCwd[261];

		strcat(newCwd, cwd);
		strcat(newCwd, "game");
		chdir(newCwd);

	}

	luaL_dobuffer(L, boot_lua, boot_lua_size, "boot"); // Do some setup Lua side.

	// If main.lua exists, execute it.
	// If not then just load the nogame screen.

	if (fileExists("main.lua")) {
		if (luaL_dofile(L, "main.lua")) displayError();
	} else {
		if (luaL_dobuffer(L, nogame_lua, nogame_lua_size, "nogame")) displayError();
	}
	
	if (luaL_dostring(L, "love.timer.step()")) displayError();

	if (luaL_dostring(L, "if love.load then love.load() end")) displayError();

	while (aptMainLoop()) {

		if (shouldQuit) {

			if (forceQuit) break;

			bool shouldAbort = false;

			// lua_getfield(L, LUA_GLOBALSINDEX, "love");
			// lua_getfield(L, -1, "quit");
			// lua_remove(L, -2);

			// if (!lua_isnil(L, -1)) {

			// 	lua_call(L, 0, 1);
			// 	shouldAbort = lua_toboolean(L, 1);
			// 	lua_pop(L, 1);

			// }; TODO: Do this properly.

			if (luaL_dostring(L, "if love.quit then love.quit() end")) displayError();

			if (!shouldAbort && !errorOccured) break;

		} // Quit event

		if (!errorOccured) {

			if (luaL_dostring(L,
				"love.keyboard.scan()\n"
				"love.timer.step()\n"
				"if love.update then love.update(love.timer.getDelta()) end")) {
					displayError();
			}

			// Top screen
			// Left side

			sf2d_start_frame(GFX_TOP, GFX_LEFT);

				if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError();

			sf2d_end_frame();

			// Right side

			if (is3D) {

				sf2d_start_frame(GFX_TOP, GFX_RIGHT);

					if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError();

				sf2d_end_frame();

			}

			// Bot screen

			sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);

				if (luaL_dostring(L, "if love.draw then love.draw() end")) displayError();

			sf2d_end_frame();

			luaL_dostring(L, "love.graphics.present()");

		} else {

			hidScanInput();
			u32 kTempDown = hidKeysDown();
			if (kTempDown & KEY_START) {
				forceQuit = true;
				shouldQuit = true;
			}

			char *errMsg = lua_tostring(L, -1);

			sf2d_start_frame(GFX_TOP, GFX_LEFT);

				lua_getfield(L, LUA_GLOBALSINDEX, "love");
				lua_getfield(L, -1, "errhand");
				lua_remove(L, -2);

				if (!lua_isnil(L, -1)) {

					lua_pushstring(L, errMsg);
					lua_call(L, 1, 0);

				}

			sf2d_end_frame();

			sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);

				lua_getfield(L, LUA_GLOBALSINDEX, "love");
				lua_getfield(L, -1, "errhand");
				lua_remove(L, -2);

				if (!lua_isnil(L, -1)) {

					lua_pushstring(L, errMsg);
					lua_call(L, 1, 0);

				}

			sf2d_end_frame();

			luaL_dostring(L, "love.graphics.present()");

		}

	}

	luaL_dostring(L, "love.audio.stop()");

	lua_close(L);

	sftd_fini();
	sf2d_fini();
	cfguExit();
	ptmuExit();

	if (soundEnabled) ndspExit();
	if (romfsExists) romfsExit();

	return 0;

}
Exemple #26
0
int main(int argc, char **argv)
{
	srvInit();	
	aptInit();
	gfxInit();
	acInit();
	initCfgu();
	ptmInit();
	hidInit(NULL);
	irrstInit(NULL);
	fsInit();
	hbInit();
	Handle fileHandle;
	u64 size;
	u32 bytesRead;
	int restore;
	
	// Set main script
	char path[256];
	if (argc > 0){	
		int latest_slash = 0;
		int i=5;
		while (argv[0][i]  != '\0'){
		if (argv[0][i] == '/'){
		latest_slash = i;
		}
		i++;
		}
		strcpy(path,&argv[0][5]);
		path[latest_slash-5] = 0;
		strcpy(start_dir,path);
		strcpy(cur_dir,path); // Set current dir
	}else{
		strcpy(start_dir,"/");
		strcpy(cur_dir,"/"); // Set current dir for GW Mode
	}
		
	while(aptMainLoop())
	{
		restore=0;		
		char error[256];
		
		errMsg = runScript((const char*)index_lua, true);
		
		if (errMsg != NULL);
                {
				// Fake error to force interpreter shutdown
				if (strstr(errMsg, "lpp_exit_04")){
					break;
				}
				
				strcpy(error,"Error: ");
				strcat(error,errMsg);
				strcat(error,"\n\nPress A to restart\nPress B to exit");
				}

						while (restore==0){
							gspWaitForVBlank();
							RefreshScreen();
							ClearScreen(0);
							ClearScreen(1);
							DebugOutput(error);
							hidScanInput();
							if(hidKeysDown() & KEY_A){
								strcpy(cur_dir,start_dir);
								restore=1;
							}else if(hidKeysDown() & KEY_B){
								restore=2;
							}
							gfxFlushBuffers();
							gfxSwapBuffers();
						}
						if (restore==2){
							break;
						}
	}
	
	fsExit();
	irrstExit();
	hidExit();
	ptmExit();
	hbExit();
	acExit();
	exitCfgu();
	gfxExit();
	aptExit();
	srvExit();

	return 0;
}
Exemple #27
0
int main()
{
    char level_data_line[20*16];
    LEVELDATA this_level_data = {
        {&level_data_line[0],   &level_data_line[20], &level_data_line[40], &level_data_line[60],
         &level_data_line[80], &level_data_line[100],&level_data_line[120],&level_data_line[140],
         &level_data_line[160],&level_data_line[180],&level_data_line[200],&level_data_line[220],
         &level_data_line[240],&level_data_line[260],&level_data_line[280],&level_data_line[300]},
        19,11
    };
    // Initializations
    srvInit();  // services
    aptInit();  // applets
    hidInit();  // input
	gfxInitDefault();
//	gfxSet3D(true); // uncomment if using stereoscopic 3D
    gfxSetDoubleBuffering(GFX_TOP, true);
    gfxSetDoubleBuffering(GFX_BOTTOM, false);

    PrintConsole /*topScreen, */bottomScreen;
    consoleInit(GFX_BOTTOM, &bottomScreen);
//    consoleInit(GFX_TOP, &topScreen);
    clear_char_stack();
    int level = 0;
    int mode = MODE_INIT;
//    int mode_status  = 0;
    hcount = 0;

int timer = 0;
    // Main loop
    while (aptMainLoop())
    {
        hidScanInput();
        u32 kDown = hidKeysDown();
        u32 kUp   = hidKeysUp();
        u32 kHeld = hidKeysHeld();
        if (kDown & KEY_START){
            break; // break in order to return to hbmenu
        }

        if (mode == MODE_INIT){
//            consoleSelect(&topScreen);
//            printf("\033[2J");
            copyGame(level,&this_level_data);
            gspWaitForVBlank();
            printGame(&this_level_data);
            mode = MODE_GAME;
        }else if (mode == MODE_CLEAR){
            if ((kUp & KEY_A) || (kUp & KEY_B) || (kUp & KEY_X) || (kUp & KEY_Y)){
                level++;
                if (level >= sizeof(level_data)/sizeof(LEVELDATA)) {
                    mode = MODE_ALL_CLEAR;
                }else{
                    mode = MODE_INIT;
                }
            }
            if (level < sizeof(level_data)/sizeof(LEVELDATA)) {
                consoleSelect(&bottomScreen);
                printf("\033[2J");
                printf("\x1b[21;12HStage cleared!!");
                printf("\x1b[23;12HPush A to next Next Stage");
            }
        }else if (mode == MODE_ALL_CLEAR){
            level = 0;
            consoleSelect(&bottomScreen);
            printf("\033[2J");
            printf("\x1b[21;12HGame cleared!!!");
            printf("\x1b[23;12HPush Start to exit game");
            mode = MODE_NULL;
        }else if (mode == MODE_GAME){

        // Your code goes here


#ifdef DEBUG
consoleSelect(&bottomScreen);
if (timer%10==0){
//if (1    != 0){printf("\x1b[10;12HkUp  =%08x",(unsigned int)kUp);}
//if (1    != 0){printf("\x1b[11;12HkDown=%08x",(unsigned int)kDown);}
//if (1    != 0){printf("\x1b[12;12HkHeld=%08x",(unsigned int)kHeld);}
//printf("\x1b[22;12HKEY_CPAD_UP=%x",KEY_UP);
//printf("\x1b[23;12HKEY_CPAD_DN=%x",KEY_DOWN);
printf("\x1b[20;12HRest: [SELECT]");
printf("\x1b[22;12HExit: [START]");
printf("\x1b[24;12HTime: %08d",timer);
}
timer++;
#endif
            if (kDown != 0 || kHeld != 0){
                if (kDown & KEY_SELECT){
                    mode = MODE_INIT;
                }else{
                    moveMan(kDown, kHeld,level,&this_level_data);
                    if(checkCleared(&this_level_data,level)==0){ mode = MODE_CLEAR;}
                    gspWaitForVBlank();
                    draw_char_stack(this_level_data,spriteData, sizeof(spriteData)/sizeof(SPRITEDATA));
                }
            }else{
                gspWaitForVBlank();
            }
        }

        // Flush and swap framebuffers
        gfxFlushBuffers();
        gfxSwapBuffers();
    }

    gfxExit();
    hidExit();
    aptExit();
    srvExit();
	return 0;
}
int main (int argc, char *argv[]) {
	(void) argc;
	(void) argv;

	// init
	gfxInitDefault();
	gfxSetMode(GfxMode_TiledDouble);
	// wide screen, keep aspect ratio
	gfxConfigureResolution(SCR_WIDTH + 136, SCR_HEIGHT);

	u32* gamebuf = (u32*) malloc(SCR_HEIGHT * SCR_WIDTH * sizeof(u32));

	Game.InitSoundDriver();
	Game.InitGame();
	Game.LoadScores();
	Game.StartGame();

	int game_paused = 0;

	while(appletMainLoop()) {
		hidScanInput();

		//1 Player input loop
		// Get Controller state
		JOYSTICK *jptr = &Game.m_GameTarget.m_Joy1;

		u32 keys_down = hidKeysDown(CONTROLLER_P1_AUTO);
		u32 keys_up = hidKeysUp(CONTROLLER_P1_AUTO);

		if (keys_down & KEY_PLUS) break;

		if (keys_down & KEY_LEFT) jptr->left = 1;
		if (keys_down & KEY_RIGHT) jptr->right = 1;
		if (keys_down & KEY_A) jptr->up = 1;
		if (keys_down & KEY_DOWN) jptr->down = 1;
		if (keys_down & KEY_B) jptr->fire = 1;

		if (keys_down & KEY_X) Game.m_GameTarget.m_Game.TogglePuffBlow();
		if (keys_down & KEY_MINUS) game_paused ^= 1;

		if (keys_up & KEY_LEFT) jptr->left = 0;
		if (keys_up & KEY_RIGHT) jptr->right = 0;
		if (keys_up & KEY_A) jptr->up = 0;
		if (keys_up & KEY_DOWN) jptr->down = 0;
		if (keys_up & KEY_B) jptr->fire = 0;

		// Fake a key press (to pass getPlayerName screen)
		jptr->key = 13;

		// Execute game logic
		Game.MainLoop(gamebuf, game_paused);

		// Draw to screen, upscaling in hardware
		u32 *framebuf = (u32*) gfxGetFramebuffer(NULL, NULL);
		for (int y = 0; y < SCR_HEIGHT; y++)
			for (int x = 0; x < SCR_WIDTH; x++)
				framebuf[gfxGetFramebufferDisplayOffset(x + 68, y)] = gamebuf[y * SCR_WIDTH + x];

		gfxFlushBuffers();
		gfxSwapBuffers();
		gfxWaitForVsync();

		// Add a delay, FIXME: calculate this with:
		//u64 time_now = svcGetSystemTick();
		svcSleepThread(40000000);
	}

	Game.SaveScores();

	// save config here :)

	Game.RemoveSoundDriver();

	// deinit
	free(gamebuf);
	gfxExit();

	return 0;
}