Esempio n. 1
0
// --------------------------------------------------
ViewState Viewer::startMainLoop(Viewer* viewer)
// --------------------------------------------------
{
	viewer->initialize();

	u32 kDown, kHeld, kUp;
	touchPosition touch;
	while(viewer->isRunning() && aptMainLoop())
	{
		hidScanInput();
		kDown = hidKeysDown();
		kHeld = hidKeysHeld();
		kUp = hidKeysUp();
		hidTouchRead(&touch);

		sf2d_start_frame(GFX_TOP, GFX_LEFT);
			viewer->drawTopScreen();
		sf2d_end_frame();
		sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);
			viewer->drawBotScreen();
		sf2d_end_frame();
		sf2d_swapbuffers();

		viewer->updateControls(kDown, kHeld, kUp, &touch);
	}

	return viewer->state();
}
Esempio n. 2
0
void conn_main() {
    APP_STATUS status;
    u32 it = 0;
    int ret = 0;
    int first = 1;
    int exiting = 0;

    while((status = aptGetStatus()) != APP_EXITING)
    {
        hidScanInput();
        consoleClear(&bot);

        print(&bot, "frame: %08x\n", it);
        print(&bot, "ret: %08x\n", ret);
        print(&bot, "last_cmd: %02x\n", last_cmd & 0xFF);

        if(!first) {
            u32 bytes_read = 0;

            while(1) {
                ret = recv(sock, &cmd, sizeof(cmd), 0);
                if(ret < 0) {
                    if(ret == -EWOULDBLOCK)
                        continue;
                    break;
                }

                bytes_read += ret;
                if(bytes_read == sizeof(cmd)) {
                    svcSignalEvent(new_cmd_event);
                    svcWaitSynchronization(cmd_done_event, U64_MAX);
                    svcClearEvent(cmd_done_event);

                    send(sock, &resp, sizeof(resp), 0);

                    if(last_cmd_result == 0xDEAD)
                        exiting = 1;
                    break;
                }
            }
        }

        first = 0;
        it++;

        if(enable_draw)
            renderFrame(); 

        u32 keys = hidKeysUp();
        if(keys & KEY_A || exiting)
            break;     
    }
}
Esempio n. 3
0
void gameControls() {

  u32 kDown, kUp;

  struct eventTranslate *translateTable = gameKeyTable;
  int numTranslations = numGameKeys;

  kDown = hidKeysDown();
  kUp   = hidKeysUp();

  if (menuactive)
  {
    translateTable = menuKeyTable;
    numTranslations = numMenuKeys;
  } else if (automapmode & am_active) {
    translateTable = mapKeyTable;
    numTranslations = numMapKeys;
  } else {

    event_t event;

    if (last_weapon_key != 0 && players[displayplayer].pendingweapon != wp_nochange) {
        event.type = ev_keyup;
        event.data1 = last_weapon_key;
        D_PostEvent(&event);
        last_weapon_key = 0;
    }


    if(kDown & KEY_Y) {

        weapontype_t weapon_index = players[displayplayer].readyweapon;

        weapon_index++;
        while(players[displayplayer].weaponowned[weapon_index] == false) {
            weapon_index++;
            if (weapon_index >= NUMWEAPONS) weapon_index = 0;
        }

        last_weapon_key = weapons[weapon_index];
        event.type = ev_keydown;
        event.data1 = last_weapon_key;
        D_PostEvent(&event);
    }
  }

  translateKeys(ev_keydown, kDown, translateTable, numTranslations);

  translateKeys(ev_keyup, kUp, translateTable, numTranslations);


}
Esempio n. 4
0
int hidCollectData(struct hidInfo *info)
{
    info->keys.up   = hidKeysUp();
    info->keys.down = hidKeysDown();
    info->keys.held = hidKeysHeld();

    hidTouchRead(&info->touchscreen);
    hidCircleRead(&info->circlepad);
    hidGyroRead(&info->gyro);
    hidCstickRead(&info->cstick);

    return 0;
}
Esempio n. 5
0
void Sys_SendKeyEvents (void)
{
	hidScanInput();
	
	u32 kDown = hidKeysDown();

	u32 kUp = hidKeysUp();

	if(kDown)
		CTR_SetKeys(kDown, true);
	if(kUp)
		CTR_SetKeys(kUp, false);

	Touch_Update();
}
Esempio n. 6
0
void sharedBackupMenu(const titleData dat, FS_Archive arch)
{
    menu backupMenu(136, 80, false);
    backupMenu.addItem("Export Data");
    backupMenu.addItem("Import Data");
    backupMenu.addItem("Back");

    std::u32string info = tou32(dat.nameSafe) + U" : Shared Extdata";

    bool loop = true;
    while(loop)
    {
        hidScanInput();

        u32 up = hidKeysUp();

        backupMenu.handleInput(up);

        if(up & KEY_A)
        {
            switch(backupMenu.getSelected())
            {
                case _exp:
                    createTitleDir(dat, MODE_SHARED);
                    backupData(dat, arch, MODE_SHARED, false);
                    break;
                case _imp:
                    restoreData(dat, arch, MODE_SHARED);
                    break;
                case _back:
                    loop = false;
                    break;
            }
        }
        else if(up & KEY_B)
            break;

        sf2d_start_frame(GFX_TOP, GFX_LEFT);
            drawTopBar(info);
            backupMenu.draw();
        sf2d_end_frame();

        sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);
        sf2d_end_frame();

        sf2d_swapbuffers();
    }
}
Esempio n. 7
0
static void I_GetInput() {
	event_t event;
	event.data2 = event.data3 = 0;
	
	uint32_t down = hidKeysDown();
	uint32_t held = hidKeysHeld();
	uint32_t up = hidKeysUp();

	// iterate over other possible key values
	int i;
	for (i = 0; i < (usejoystick ? 28 : 32); i++) {
		uint32_t key = 1<<i;
		
		if (down & key) {
			event.data1 = I_TranslateKey(key);
			event.type = ev_keydown;
			D_PostEvent(&event);
		} else if (up & key) {
			event.data1 = I_TranslateKey(key);
			event.type = ev_keyup;
			D_PostEvent(&event);
		}
	}

	// handle touch pad movement
	if (usemouse) {
		static int px = 0;
		static int py = 0;
		touchPosition touch;
		hidTouchRead(&touch);
		if (down & KEY_TOUCH) {
			px = touch.px;
			py = touch.py;
			
		} else if (held & KEY_TOUCH && (touch.px != px || touch.py != py)) {
			event.type = ev_mouse;
			event.data1 = -1;
			event.data2 = (touch.px - px) << 5;
			event.data3 = -(touch.py - py) << 5;
			D_PostEvent(&event);
			
			px = touch.px;
			py = touch.py;
		}
	}
}
Esempio n. 8
0
int SYS::queue_events() {
	hidScanInput();
	u32 down = hidKeysDown();
	u32 up = hidKeysUp();
	for (int i = 0; i < 32; i++) {
		if (buttonMap3ds[i]) {
			if ((down & BIT(i)) != 0) {
				events.queue_event(m_msg_time, EV_KEY_DOWN, buttonMap3ds[i], 0);
			}
			if ((up & BIT(i)) != 0) {
				events.queue_event(m_msg_time, EV_KEY_UP, buttonMap3ds[i], 0);
			}
		}
	}
	static int key_last = 0;
	static int key = 0;

	key_last = key;
	key = keyboard_scankeys();
	if (key_last != 0 && key_last != key)
	{
		//printf("key up: %d %c\n", key_last, key_last);
		events.queue_event(m_msg_time, EV_KEY_UP, key_last, 0);
		//event.type = ev_keyup;
		//event.data1 = key_last;
		//D_PostEvent(&event);
	}

	if (key != 0 && key != key_last)
	{
		//printf("key down: %d %c\n", key, key);
		events.queue_event(m_msg_time, EV_KEY_DOWN, key, 0);
		//event.type = ev_keydown;
		//event.data1 = key;
		//D_PostEvent(&event);
	}
	return 0;
}
Esempio n. 9
0
void Update(float delta) {
	ActivityManager::current->dispatchUpdate(delta);

	u32 kDown = hidKeysDown();
	u32 kHeld = hidKeysHeld();
	u32 kUp = hidKeysUp();

	if (kDown != 0) ActivityManager::current->dispatchKeyPressed(kDown);
	if (kUp != 0) ActivityManager::current->dispatchKeyReleased(kUp);

	touchPosition touch;
	hidTouchRead(&touch);

	if ((!focused) && (kDown & KEY_TOUCH)) {
		focused = nullptr;

		// Find an element to focus

		// Get last group
		auto group = RootLayerGroup;
		while (group && group->next) {
			group = group->next;
		}

		while (group) {
			focused = group->find([&](auto element) {
				return element->bounds.contains(touch.px, touch.py) &&
					element->onTouchStart && element->onTouchStart(touch.px, touch.py);
			});

			if (focused) break;
			group = group->prev;
		}

		if (focused) {
			printf("Focused on element %p\n", focused);
			startTouch = touch;
			lastTouch = touch;
			tapValid = true;
		}
	} else if (focused) {
		if (kUp & KEY_TOUCH) { // On key up touch is invalid (0, 0)
			if (tapValid && focused->onTap) { // Tap is invalid if it ever strays away from the 5px requirement
				focused->onTap(lastTouch.px, lastTouch.py);
			}

			if (focused->onTouchEnd) {
				focused->onTouchEnd(lastTouch.px, lastTouch.py);
			}

			focused = nullptr;
		} else {
			if (tapValid) {
				s32 touchDiffX = ((s32)startTouch.px)-((s32)lastTouch.px);
				s32 touchDiffY = ((s32)startTouch.py)-((s32)lastTouch.py);
				if (std::abs(touchDiffX+touchDiffY) > 7) { // ~5 pixels away in each possible direction
					tapValid = false;
				}
			}

			// Only send onTouchMove if we are not eligible for onTap
			if (!tapValid) {
				if (focused->onTouchMove) {
					focused->onTouchMove(touch.px, touch.py);
				}
			}

			lastTouch = touch;
		}
	}
}
Esempio n. 10
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)
Esempio n. 11
0
int inputScan(lua_State *L) { // love.keyboard.scan()

	hidScanInput();

	kDown = hidKeysDown();
	kHeld = hidKeysHeld();
	kUp = hidKeysUp();

	hidTouchRead(&touch);

	if (kDown & BIT(20)) { // BIT(20) == "touch" -- love.mousepressed()

		touchIsDown = true;

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

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

			lua_pushinteger(L, touch.px);
			lua_pushinteger(L, touch.py);
			lua_pushstring(L, "l");

			lua_call(L, 3, 0);

			lastPosx = touch.px;
			lastPosy = touch.py;

		}

	}

	if (kUp & BIT(20)) { // love.mousereleased()

		touchIsDown = false;

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

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

			lua_pushinteger(L, touch.px);
			lua_pushinteger(L, touch.py);
			lua_pushstring(L, "l");

			lua_call(L, 3, 0);

		}

	}

	int i;
	for (i = 0; i < 32; i++) { // love.keypressed()
		if (kDown & BIT(i)) {
			if (strcmp(dsNames[i], "touch") != 0) { // Touch shouldn't be returned in love.keypressed.
				
				lua_getfield(L, LUA_GLOBALSINDEX, "love");
				lua_getfield(L, -1, "keypressed");
				lua_remove(L, -2);

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

					lua_pushstring(L, dsNames[i]);
					lua_pushboolean(L, 0);

					lua_call(L, 2, 0);

				}
			}
		} 
	}

	for (i = 0; i < 32; i++) { // love.keyreleased()
		if (kUp & BIT(i)) {
			if (strcmp(dsNames[i], "touch") != 0) { // Touch shouldn't be returned in love.keypressed.
				
				lua_getfield(L, LUA_GLOBALSINDEX, "love");
				lua_getfield(L, -1, "keyreleased");
				lua_remove(L, -2);

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

					lua_pushstring(L, dsNames[i]);

					lua_call(L, 1, 0);

				}
			}
		} 
	}

	return 0;

}
Esempio n. 12
0
/*----------------*/
int main(int argc, char *argv[])
{
    APP_STATUS status;

    srvInit();
    aptInit(APPID_APPLICATION);
    gfxInit();
    hidInit(NULL);
    fsInit();

    svcCreateEvent(&new_cmd_event, 0);
    svcCreateEvent(&cmd_done_event, 0);
    svcCreateThread(&thread, cmd_thread_func, 0x0,
                    (u32*)((char*)thread_stack + sizeof(thread_stack)),
                    0x31, 0xfffffffe);

    int where = 0;
    u32 ret = SOC_Initialize((u32*)0x08000000, 0x48000);

    if(ret == 0) {
        listen_socket = socket(AF_INET, SOCK_STREAM, 0);
        if(listen_socket == -1) {
            where = 1;
            ret = SOC_GetErrno();
        }
        else {
            u32 tmp = fcntl(listen_socket, F_GETFL);
            fcntl(listen_socket, F_SETFL, tmp | O_NONBLOCK);

            struct sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_port = __swap16(PORT);
            addr.sin_addr.s_addr = INADDR_ANY;

            ret = bind(listen_socket, (struct sockaddr *)&addr, sizeof(addr));
            if(ret != 0) {
                where = 2;
                ret = SOC_GetErrno();
            }
            else {
                ret = listen(listen_socket, 1);
                if(ret == -1) {
                    ret = SOC_GetErrno();
                    where = 3;
                }
            }
        }

    }

    u32 it = 0;
    int accept_errno = 0;
    int first = 1;


    while((status = aptGetStatus()) != APP_EXITING)
    {
        hidScanInput();
        consoleClear(&top);

        print(&top, "newver\n");
        print(&top, "ret: %08x, where: %d\n", ret, where);
        print(&top, "frame: %08x\n", it);
        u32 ip = gethostid();
        print(&top, "ip: %d.%d.%d.%d\n", ip & 0xFF, (ip>>8)&0xFF, (ip>>16)&0xFF, (ip>>24)&0xFF);
                
        if(accept_errno != 0) print(&top, "accept returned errno %d\n", accept_errno);

        if(!first) {
            int s = accept(listen_socket, NULL, NULL);
            if(s == -1) {
                int err = SOC_GetErrno();

                if(err != -EWOULDBLOCK)
                    accept_errno = err;
            }
            else {
                sock = s;
                conn_main();
                closesocket(sock);
            }
        }

        it++;
        first = 0;
        if(enable_draw)
            renderFrame(); 

        u32 keys = hidKeysUp();
        if(keys & KEY_A)
            break;
    }

    thread_exit = 1;
    svcSignalEvent(new_cmd_event);
    svcWaitSynchronization(thread, U64_MAX);
    svcCloseHandle(thread);

    svcCloseHandle(new_cmd_event);
    svcCloseHandle(cmd_done_event);

    SOC_Shutdown();
    fsExit();
    hidExit();
    gfxExit();
    aptExit();
    srvExit();
    return 0;
}
Esempio n. 13
0
void conn_main() {
    APP_STATUS status;
    u32 it = 0;
    int ret = 0;
    int first = 1;
    int exiting = 0;

    while((status = aptGetStatus()) != APP_EXITING)
    {
        hidScanInput();
        consoleClear(&bot);

        print(&bot, "frame: %08x\n", it);
        print(&bot, "ret: %08x\n", ret);
        print(&bot, "last_cmd: %02x\n", last_cmd & 0xFF);
        int i;for(i=0;i<GSPEVENT_MAX;i++)print(&bot, "%d : %08X\n", i, gspEventCounts[i]);

        if(!first) {
            u32 bytes_read = 0;

            while(1) {
                ret = recv(sock, &cmd, 4, 0);
                if(ret < 0) {
                    if(ret == -EWOULDBLOCK)
                        continue;
                    break;
                }

                if(!cmd.numarg)cmd.numarg=7;
                u32 size=cmd.numarg*4;
                ret = recv(sock, &cmd.args, size, 0);
                if(ret < 0) {
                    if(ret == -EWOULDBLOCK)
                        continue;
                    break;
                }

                bytes_read += ret;
                if(bytes_read == size) {
                    svcSignalEvent(new_cmd_event);
                    svcWaitSynchronization(cmd_done_event, U64_MAX);
                    svcClearEvent(cmd_done_event);

                    size=4+4*resp.numarg;
                    send(sock, &resp, size, 0);

                    if(last_cmd_result == 0xDEAD)
                        exiting = 1;
                    break;
                }
            }
        }

        first = 0;
        it++;

        if(enable_draw)
            renderFrame(); 

        u32 keys = hidKeysUp();
        if(keys & KEY_A || exiting)
            break;     
    }
}
Esempio n. 14
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;
}
Esempio n. 15
0
std::tuple<u32, u32, u32> dsIn() {
	hidScanInput();
	return std::make_tuple(hidKeysDown(), hidKeysHeld(), hidKeysUp());
}
Esempio n. 16
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
	}
}
Esempio n. 17
0
void state_man() {
   print_menu();
   u32 kDown = hidKeysDown();
   //hidKeysHeld returns information about which buttons have are held down in this frame
   u32 kHeld = hidKeysHeld();
   //hidKeysUp returns information about which buttons have been just released
   u32 kUp = hidKeysUp();

   touchPosition touch;

   //Read the touch screen coordinates
   hidTouchRead(&touch);

   if (play_box.is_within(touch.px, touch.py) && (kDown & KEY_TOUCH)) {
      paused = !paused;
      draw_ui = true;
   }

   if (loop_box.is_within(touch.px, touch.py) && (kDown & KEY_TOUCH)) {
      loop_flag = !loop_flag;
      draw_ui = true;
   }

   if (state == STATE_IDLE) {
      if (kDown & KEY_X) {
         state = STATE_FC;
         cursor_pos = 0;
         draw_ui = true;
      }

      if (kUp & KEY_UP) {
         loop_flag = !loop_flag;
         draw_ui = true;
      }
      if (kUp & KEY_A) {
         paused = !paused;
         draw_ui = true;
      }
   } else if (state == STATE_FC) {
      if (kDown & KEY_X) {
         state = STATE_IDLE;
         draw_ui = true;
      }

      if (kUp & KEY_UP) {
         cursor_pos--;
         if (cursor_pos < 0) cursor_pos = 0;
         draw_ui = true;
      }
      if (kDown & KEY_DOWN) {
         cursor_pos++;
         if (cursor_pos < 0) cursor_pos = 0;
         draw_ui = true;
      }

      if (kUp & KEY_A) {
         pick();
         draw_ui = true;
      }
   }
}
Esempio n. 18
0
void pick_file(file_s *picked, const char *path) {

    picker = malloc(sizeof(picker_s));
    get_dir(path);

    // key repeat timer
    static time_t t_start = 0, t_end = 0, t_elapsed = 0;

    while (aptMainLoop()) {

        hidScanInput();
        u32 kHeld = hidKeysHeld();
        u32 kDown = hidKeysDown();

        if (hidKeysUp()) {
            time(&t_start); // reset held timer
        }

        if (kDown & KEY_DOWN) {
            picker->file_index++;
            if (picker->file_index >= picker->file_count)
                picker->file_index = 0;
            time(&t_start);
        } else if (kHeld & KEY_DOWN) {
            time(&t_end);
            t_elapsed = t_end - t_start;
            if (t_elapsed > 0) {
                picker->file_index++;
                if (picker->file_index >= picker->file_count)
                    picker->file_index = 0;
                svcSleep(100);
            }
        }

        if (kDown & KEY_UP) {
            picker->file_index--;
            if (picker->file_index < 0)
                picker->file_index = picker->file_count - 1;
            time(&t_start);
        } else if (kHeld & KEY_UP) {
            time(&t_end);
            t_elapsed = t_end - t_start;
            if (t_elapsed > 0) {
                picker->file_index--;
                if (picker->file_index < 0)
                    picker->file_index = picker->file_count - 1;
                svcSleep(100);
            }
        }

        if (kDown & KEY_A) {
            if (picker->file_count > 0) {
                int index = picker->file_index;
                if (!picker->files[index].isDir) {
                    if (confirm(0, "Launch \"%s\" ?", picker->files[index].name)) {
                        strncpy(picked->name, picker->files[index].name, 512);
                        strncpy(picked->path, picker->files[index].path, 512);
                        picked->isDir = picker->files[index].isDir;
                        picked->size = picker->files[index].size;
                        break;
                    }
                }
                else {
                    get_dir(picker->files[index].path);
                }
            }
        } else if (kDown & KEY_X) {
            int index = picker->file_index;
            if (!picker->files[index].isDir) {
                const char *ext = get_filename_ext(picker->files[index].name);
                if (strcasecmp(ext, "3dsx") == 0) {
                    if (confirm(3, "Add entry to boot menu: \"%s\" ?", picker->files[index].name)) {
                        if (config->count > CONFIG_MAX_ENTRIES - 1) {
                            debug("Maximum entries reached (%i)\n", CONFIG_MAX_ENTRIES);
                        } else if (configAddEntry(picker->files[index].name, picker->files[index].path, 0) == 0) {
                            debug("Added entry: %s\n", picker->files[index].name);
                        } else {
                            debug("Error adding entry: %s\n", picker->files[index].name);
                        }
                    }
                }
            }
        }
        else if (kDown & KEY_B) {
            // exit if we can't go back
            if (strlen(picker->now_path) <= 1)
                break;

            // remove slash if needed
            if (end_with(picker->now_path, '/'))
                picker->now_path[strlen(picker->now_path) - 1] = '\0';

            // build path
            char *slash = strrchr(picker->now_path, '/');
            if (slash == NULL)
                break;
            int len = (int) (slash - picker->now_path);
            picker->now_path[len] = '\0';

            // enter new dir
            get_dir(picker->now_path);
        }

        drawBg();
        drawTitle("*** Select a file ***");

        int i, y = 0;
        int page = picker->file_index / MAX_LINE;
        for (i = page * MAX_LINE; i < page * MAX_LINE + MAX_LINE; i++) {
            if (i >= picker->file_count)
                break;

            drawItemN(i == picker->file_index, 47, 16 * i, picker->files[i].name);
            if (i == picker->file_index && !picker->files[i].isDir) {
                drawInfo("Press (A) to launch\nPress (X) to add to boot menu");

            }
            y++;
        }
        gfxSwap();
    }
    free(picker);
}
Esempio n. 19
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;
}
Esempio n. 20
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;
}
Esempio n. 21
0
int main(int argc, char* argv[]) {
	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, &topScreen);
	consoleInit(GFX_BOTTOM,&bottomScreen);
	consoleSelect(&topScreen);
	APT_CheckNew3DS(&consoletype);
	printf("Console type:%s\n",consoletype?"New3DS. Good job!":"Old3DS. This may be a bit slow.");
	// Main loop
	while (aptMainLoop())
	{
		printf("Welcome to the adventure. Press A to continue, or any other key to exit.\n");
		hidScanInput();

		//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
		u32 kDown = hidKeysDown();
		//hidKeysHeld returns information about which buttons have are held down in this frame
		u32 kHeld = hidKeysHeld();
		//hidKeysUp returns information about which buttons have been just released
		u32 kUp = hidKeysUp();
		while (!kDown) {hidScanInput(); u32 kDown = hidKeysDown(); u32 kHeld = hidKeysHeld(); u32 kUp = hidKeysUp(); if (kDown || kHeld || kUp) printf("Down:%d Held:%d Up:%d", kDown, kHeld, kUp);}
		if (kDown & !KEY_A) break;
		else if (kDown) {
			notknow:
			rendscreen("\n\nYou are walking in a forest. You come to a part you don't know. You can go three ways. Do you go left, right, or straight? (Use the D-Pad to select) ");
			hidScanInput();

			//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
			kDown = hidKeysDown();
			//hidKeysHeld returns information about which buttons have are held down in this frame
			kHeld = hidKeysHeld();
			//hidKeysUp returns information about which buttons have been just released
			kUp = hidKeysUp();
			while (!kDown) {hidScanInput(); u32 kDown = hidKeysDown(); u32 kHeld = hidKeysHeld(); u32 kUp = hidKeysUp();}
			if (kDown & KEY_LEFT) {
				if (ldone) {
					rendscreen("You've already gone here! (A)");
					isButtonPressed('a');
					move="0";
					goto notknow;
				}
				else {
					rendscreen("You found a chest! Inside it was 5 bars of gold. (A to continue)");
					if (input()) goto exit;
					gold +=5;
					rendscreen("It's at a dead end, however. You walk back.");
					if (input()) goto exit;
					move="0";
					ldone=true;
					goto notknow;
				}
			}
			else if (kDown & KEY_RIGHT) {
				if (rdone) {
					rendscreen("You've already gone here!");
					if (input()) goto exit;
					move="0";
				}
				else {
					rendscreen("You walk into a trap and lose a life.(A to continue)");
					if (input()) goto exit;
					lives+=-1;
					rendscreen("You walk back.");
					if (input()) goto exit;
					move="0";
					rdone=true;
				}
			}
			else if (kDown & KEY_UP) continue;
			else if (kDown & KEY_START) goto exit;
			else goto notknow;
			rendscreen("You walk forward for a while.(A to continue)");
			if (input()) goto exit;
			rendscreen("The ground begins to shake...(A to continue)");
			if (input()) goto exit;
			cls();
			print("Louder...");
			usleep(1000);
			rendscreen("You come up to a monster!");
			usleep(1000);
			rendscreen("'I will eat you!'");
			usleep(1000);
			rendscreen("How to fight: Press A to kick and B to punch.");
			if (input()) goto exit;
			rendscreen("When it's your enemy's turn, hope for the best!");
			if (input()) goto exit;
			rendscreen("Press A to start.");
			if (input()) goto exit;
			
			while (enemyh>0) {
				rendscreenf();
				char fmove='0';
				printf("Kick or punch? \n");
				while (fmove != 'K' && fmove != 'P' && fmove != 'a') {
					if (isButtonPressed('a')) fmove = 'K';
					else if (isButtonPressed('b')) fmove = 'P';
					else if (isButtonPressed('e')) {
						if (isButtonPressed('l')) fmove = 'a';
					}
					else if (isButtonPressed('t')) goto exit;
				}
				if (fmove=='K') {
					sub=floor(random()*10)+5;
					enemyh=enemyh-sub*10;
					printf("Damage dealt: %i\n",sub*10);
					if (input()) goto exit;
				}
				else if (fmove=='a') {
					enemyh=0;
				}
				else {
					sub=floor(random()*10);
					enemyh+=-sub*18;
					printf("Damage dealt: %i\n", sub*18);
					if (input()) goto exit;
				}
				rendscreenf();
				usleep(200);
				if (enemyh>0) {
					health+=-floor(random()*100);
					health+=-60;
					printf("Monster attacks! Damage dealt: %i\n", sub+60);
					if (input()) goto exit;
				}
			}
			rendscreen("You won the battle!");
			if (input()) goto exit;
			rendscreen("The monster had 20 gold and you gained two lives from defeating him!");
			gold+=20;
			lives+=2;
			if (input()) goto exit;
			rendscreen("You continue along the path.");
			if (input()) goto exit;
			char berries = 'x';
			// Entrypoint 2																											===============
			rendscreen("You find some berries.  Do you eat them? (A/B) ");
			while (berries != 'y' && berries != 'n') {
				if (isButtonPressed('a')) berries = 'y';
				else if (isButtonPressed('b')) berries = 'n';
				else if (isButtonPressed('t')) goto exit;
			}
			if (berries=='y') {
				rendscreen("Under the leaves, you found a glove!  It grants +50 health in all battles!");
				ebhealth+=50;
				special.push_back("Glove");
				if (input()) goto exit;
				rendscreen("After eating some berries, you continue walking.");
			}
			else {
				rendscreen("You continue walking.");
			}
			if (input()) goto exit;
			char river='0';
			rendscreen("After walking for quite some time, you come to a river.  There's a bear right behind you.  Do you try to cross the river? (A/B) ");
			while (river!='y' && river!='n') {
				if (isButtonPressed('a')) river = 'y';
				else if (isButtonPressed('b')) river = 'n';
				else if (isButtonPressed('t')) goto exit;
			}
			if (river=='y') {
				rendscreen("You manage to cross the river, but you get sick and lose a life.");
				lives+=-1;
			}
			else {
				rendscreen("You stay and fight the bear!");
				if (input()) goto exit;
				health=1000+ebhealth;
				enemyh=400;
				while (enemyh>0) {
					rendscreenf();
					char fmove='0';
					printf("Kick or punch? \n");
					while (fmove!='k' && fmove!='p' && fmove!='a') {
						if (isButtonPressed('a')) fmove = 'k';
						else if (isButtonPressed('b')) fmove = 'p';
						else if (isButtonPressed('e')) {if (isButtonPressed('l')) fmove = 'a';}
						else if (kDown & KEY_START) goto exit;
					}
					if (fmove=='k') {
						sub=floor(random()*10)+6;
						enemyh=enemyh-sub*10;
						printf("Damage dealt: %i\n", sub*10);
						if (input()) goto exit;
					}
					else if (fmove=='a') enemyh=0;
					else {
						sub=floor(random()*10);
						enemyh+=-sub*1.85*10;
						printf("Damage dealt: %d\n", sub*1.85*10);
						if (input()) goto exit;
					}
					rendscreenf();
					usleep(200);
					if (enemyh>0) {
						sub=floor(random()*10)*1.4*10;
						health+=-sub;
						health+=-4*10;
						printf("Bear attacks! Damage dealt: %d\n", sub+4*10);
						if (input()) goto exit;
					}
					if (health<0) {
						lives+=-1;
						health=1000+ebhealth;
					}
				}
				rendscreen("You won the battle!");
				if (input()) goto exit;
				rendscreen("You keep the fur coat from the bear.  It gives you +200 health in all battles!");
				if (input()) goto exit;
				ebhealth+=200;
				special.push_back("Fur Coat");
				rendscreen("You decide to put down a log and cross the river.");
			}
			if (input()) goto exit;
			printf("Unfortunately, this is an *alpha* release for debugging only. This is the end of the program.\n\n\n");
			usleep(2000);
			printf("Exiting...\n");
			usleep(500);
			goto exit;
		}
	}
exit:
	// Exit services
	gfxExit();
	return 0;
}
Esempio n. 22
0
bool inputIsReleased(Button button) {
    return (hidKeysUp() & button) != 0;
}
Esempio n. 23
0
bool isButtonPressed(char button, bool wait = true) {
	std::tuple<u32, u32, u32> input = dsIn();
	kDown = std::get<0>(input);
	kHeld = std::get<1>(input);
	kUp	  = std::get<2>(input);
	while (!kDown && wait) {hidScanInput(); u32 kDown = hidKeysDown(); u32 kHeld = hidKeysHeld(); u32 kUp = hidKeysUp();}
	if (kDown && KEY_A && button == 'a') return 0;
	else if (kDown && KEY_B && button == 'b') return 0;
	else if (kDown && KEY_X && button == 'x') return 0;
	else if (kDown && KEY_Y && button == 'y') return 0;
	else if (kDown && KEY_L && button == 'l') return 0;
	else if (kDown && KEY_R && button == 'r') return 0;
	else if (kDown && KEY_START && button == 't') return 0;
	else if (kDown && KEY_SELECT && button == 'e') return 0;
	else if (kDown && KEY_UP && button == 'u') return 0;
	else if (kDown && KEY_DOWN && button == 'd') return 0;
	else if (kDown && KEY_LEFT && button == 'q') return 0;
	else if (kDown && KEY_RIGHT && button == 'e') return 0;
	else if (consoletype) {
		if (kDown && KEY_ZR && button == 'c') return 0;
		else if (kDown && KEY_ZL && button == 'z') return 0;
	}
	return 1;
}
Esempio n. 24
0
void pick_file(file_s *picked, const char *path) {

    picker = malloc(sizeof(picker_s));
    get_dir(path);

    // key repeat timer
    static time_t t_start = 0, t_end = 0, t_elapsed = 0;

    while (aptMainLoop()) {

        hidScanInput();
        u32 kHeld = hidKeysHeld();
        u32 kDown = hidKeysDown();

        if (hidKeysUp()) {
            time(&t_start); // reset held timer
        }

        if (kDown & KEY_DOWN) {
            picker->file_index++;
            if (picker->file_index >= picker->file_count)
                picker->file_index = 0;
            time(&t_start);
        } else if (kHeld & KEY_DOWN) {
            time(&t_end);
            t_elapsed = t_end - t_start;
            if (t_elapsed > 0) {
                picker->file_index++;
                if (picker->file_index >= picker->file_count)
                    picker->file_index = 0;
                svcSleep(100);
            }
        }

        if (kDown & KEY_UP) {
            picker->file_index--;
            if (picker->file_index < 0)
                picker->file_index = picker->file_count - 1;
            time(&t_start);
        } else if (kHeld & KEY_UP) {
            time(&t_end);
            t_elapsed = t_end - t_start;
            if (t_elapsed > 0) {
                picker->file_index--;
                if (picker->file_index < 0)
                    picker->file_index = picker->file_count - 1;
                svcSleep(100);
            }
        }

        if (kDown & KEY_A) {
            int index = picker->file_index;
            if (!picker->files[index].isDir) {
                if (confirm(0, "Launch \"%s\" ?", picker->files[index].name)) {
                    strncpy(picked->name, picker->files[index].name, 512);
                    strncpy(picked->path, picker->files[index].path, 512);
                    picked->isDir = picker->files[index].isDir;
                    picked->size = picker->files[index].size;
                    break;
                }
            }
            else {
                get_dir(picker->files[index].path);
            }
        } else if (kDown & KEY_X) {
            int index = picker->file_index;
            if (!picker->files[index].isDir) {
                const char *ext = get_filename_ext(picker->files[index].name);
                if (strcasecmp(ext, "3dsx") == 0) {
                    if (confirm(3, "Add entry to boot menu: \"%s\" ?", picker->files[index].name)) {
                        if (config->count > CONFIG_MAX_ENTRIES - 1) {
                            debug("Maximum entries reached (%i)\n", CONFIG_MAX_ENTRIES);
                        } else if (configAddEntry(picker->files[index].name, picker->files[index].path, 0) == 0) {
                            debug("Added entry: %s\n", picker->files[index].name);
                        } else {
                            debug("Error adding entry: %s\n", picker->files[index].name);
                        }
                    }
                }
            }
        }
        else if (kDown & KEY_B) {
            // exit if we can't go back
            if (strlen(picker->now_path) <= 1)
                break;

            // remove slash if needed
            if (end_with(picker->now_path, '/'))
                picker->now_path[strlen(picker->now_path) - 1] = '\0';

            // build path
            char *slash = strrchr(picker->now_path, '/');
            if (slash == NULL)
                break;
            int len = (int) (slash - picker->now_path);
            picker->now_path[len] = '\0';

            // enter new dir
            get_dir(picker->now_path);
        }

        gfxClear();
        gfxDrawText(GFX_TOP, GFX_LEFT, &fontTitle, "*** Select a file ***", 130, 20);

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

        int i, y = 0;
        int page = picker->file_index / MAX_LINE;
        for (i = page * MAX_LINE; i < page * MAX_LINE + MAX_LINE; i++) {
            if (i >= picker->file_count)
                break;

            if (i == picker->file_index) {
                gfxDrawRectangle(GFX_TOP, GFX_LEFT, (u8[]) {0xDC, 0xDC, 0xDC}, minX + 4, minY + 16 * y, maxX - 23, 15);
                gfxDrawTextN(GFX_TOP, GFX_LEFT, &fontSelected, picker->files[i].name, 47, minX + 6, minY + 16 * y);
                if (!picker->files[i].isDir) {
                    gfxDrawText(GFX_BOTTOM, GFX_LEFT, &fontTitle, "Informations", minX + 6, 20);
                    gfxDrawText(GFX_BOTTOM, GFX_LEFT, &fontDefault,
                                "Press (A) to launch\nPress (X) to add to boot menu", minX + 12, 40);
                }
            } else {
                gfxDrawTextN(GFX_TOP, GFX_LEFT, &fontDefault, picker->files[i].name, 47, minX + 6, minY + 16 * y);
            }
            y++;
        }
Esempio n. 25
0
void sharedExtManager()
{
    menu sharedMenu(128, 72, false);
    sharedMenu.addItem("E0000000");
    sharedMenu.addItem("F0000001");
    sharedMenu.addItem("F0000002");
    sharedMenu.addItem("F0000009");
    sharedMenu.addItem("F000000B");
    sharedMenu.addItem("F000000C");
    sharedMenu.addItem("F000000D");
    sharedMenu.addItem("F000000E");
    sharedMenu.addItem("Back");

    std::u32string info = U"Shared ExtData";
    bool loop = true;
    while(loop)
    {
        hidScanInput();

        u32 up = hidKeysUp();

        sharedMenu.handleInput(up);

        if(up & KEY_A)
        {
            FS_Archive shared;
            titleData sharedDat;
            bool opened = false;
            switch(sharedMenu.getSelected())
            {
                case e0:
                    opened = openSharedExt(&shared, 0xE0000000);
                    sharedDat.nameSafe = tou16("E0000000");
                    break;
                case f1:
                    opened = openSharedExt(&shared, 0xF0000001);
                    sharedDat.nameSafe = tou16("F0000001");
                    break;
                case f2:
                    opened = openSharedExt(&shared, 0xF0000002);
                    sharedDat.nameSafe = tou16("F0000002");
                    break;
                case f9:
                    opened = openSharedExt(&shared, 0xF0000009);
                    sharedDat.nameSafe = tou16("F0000009");
                    break;
                case fb:
                    opened = openSharedExt(&shared, 0xF000000B);
                    sharedDat.nameSafe = tou16("F000000B");
                    break;
                case fc:
                    opened = openSharedExt(&shared, 0xF000000C);
                    sharedDat.nameSafe = tou16("F000000C");
                    break;
                case fd:
                    opened = openSharedExt(&shared, 0xF000000D);
                    sharedDat.nameSafe = tou16("F000000D");
                    break;
                case fe:
                    opened = openSharedExt(&shared, 0xF000000E);
                    sharedDat.nameSafe = tou16("F0000000E");
                    break;
                case back:
                    loop = false;
                    break;
            }

            if(opened)
            {
                sharedBackupMenu(sharedDat, shared);
            }
            FSUSER_CloseArchive(&shared);
        }
        else if(up & KEY_B)
            break;

        sf2d_start_frame(GFX_TOP, GFX_LEFT);
            drawTopBar(info);
            sharedMenu.draw();
        sf2d_end_frame();

        sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);
            sftd_draw_text_wrap(yashi, 0, 0, RGBA8(255, 255, 255, 255), 12, 320, descs[sharedMenu.getSelected()].c_str());
        sf2d_end_frame();

        sf2d_swapbuffers();
    }
}
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;
}