コード例 #1
0
ファイル: testsprite2.c プロジェクト: 03050903/Torque3D
int
main(int argc, char *argv[])
{
    int i;
    Uint32 then, now, frames;
    Uint64 seed;
    const char *icon = "icon.bmp";

    /* Initialize parameters */
    num_sprites = NUM_SPRITES;

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }

    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            consumed = -1;
            if (SDL_strcasecmp(argv[i], "--blend") == 0) {
                if (argv[i + 1]) {
                    if (SDL_strcasecmp(argv[i + 1], "none") == 0) {
                        blendMode = SDL_BLENDMODE_NONE;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "blend") == 0) {
                        blendMode = SDL_BLENDMODE_BLEND;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "add") == 0) {
                        blendMode = SDL_BLENDMODE_ADD;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
                        blendMode = SDL_BLENDMODE_MOD;
                        consumed = 2;
                    }
                }
            } else if (SDL_strcasecmp(argv[i], "--iterations") == 0) {
                if (argv[i + 1]) {
                    iterations = SDL_atoi(argv[i + 1]);
                    if (iterations < -1) iterations = -1;
                    consumed = 2;
                }
            } else if (SDL_strcasecmp(argv[i], "--cyclecolor") == 0) {
                cycle_color = SDL_TRUE;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--cyclealpha") == 0) {
                cycle_alpha = SDL_TRUE;
                consumed = 1;
            } else if (SDL_isdigit(*argv[i])) {
                num_sprites = SDL_atoi(argv[i]);
                consumed = 1;
            } else if (argv[i][0] != '-') {
                icon = argv[i];
                consumed = 1;
            }
        }
        if (consumed < 0) {
            SDL_Log("Usage: %s %s [--blend none|blend|add|mod] [--cyclecolor] [--cyclealpha] [--iterations N] [num_sprites] [icon.bmp]\n",
                    argv[0], SDLTest_CommonUsage(state));
            quit(1);
        }
        i += consumed;
    }
    if (!SDLTest_CommonInit(state)) {
        quit(2);
    }

    /* Create the windows, initialize the renderers, and load the textures */
    sprites =
        (SDL_Texture **) SDL_malloc(state->num_windows * sizeof(*sprites));
    if (!sprites) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
        quit(2);
    }
    for (i = 0; i < state->num_windows; ++i) {
        SDL_Renderer *renderer = state->renderers[i];
        SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
        SDL_RenderClear(renderer);
    }
    if (LoadSprite(icon) < 0) {
        quit(2);
    }

    /* Allocate memory for the sprite info */
    positions = (SDL_Rect *) SDL_malloc(num_sprites * sizeof(SDL_Rect));
    velocities = (SDL_Rect *) SDL_malloc(num_sprites * sizeof(SDL_Rect));
    if (!positions || !velocities) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
        quit(2);
    }

    /* Position sprites and set their velocities using the fuzzer */ 
    if (iterations >= 0) {
        /* Deterministic seed - used for visual tests */
        seed = (Uint64)iterations;
    } else {
        /* Pseudo-random seed generated from the time */
        seed = (Uint64)time(NULL);
    }
    SDLTest_FuzzerInit(seed);
    for (i = 0; i < num_sprites; ++i) {
        positions[i].x = SDLTest_RandomIntegerInRange(0, state->window_w - sprite_w);
        positions[i].y = SDLTest_RandomIntegerInRange(0, state->window_h - sprite_h);
        positions[i].w = sprite_w;
        positions[i].h = sprite_h;
        velocities[i].x = 0;
        velocities[i].y = 0;
        while (!velocities[i].x && !velocities[i].y) {
            velocities[i].x = SDLTest_RandomIntegerInRange(-MAX_SPEED, MAX_SPEED);
            velocities[i].y = SDLTest_RandomIntegerInRange(-MAX_SPEED, MAX_SPEED);
        }
    }

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        ++frames;
        loop();
    }
#endif

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        double fps = ((double) frames * 1000) / (now - then);
        SDL_Log("%2.2f frames per second\n", fps);
    }
    quit(0);
    return 0;
}
コード例 #2
0
int main() {
  emscripten_set_main_loop(iter, 3, 0);
}
コード例 #3
0
ファイル: openal_buffers.c プロジェクト: AtomLaw/emscripten
int main(int argc, char* argv[]) {
  //
  // Setup the AL context.
  //
  device = alcOpenDevice(NULL);
  context = alcCreateContext(device, NULL);
  alcMakeContextCurrent(context);

  //
  // Read in the audio sample.
  //
#ifdef EMSCRIPTEN
  FILE* fp = fopen("the_entertainer.wav", "rb");
#else
  FILE* fp = fopen("sounds/the_entertainer.wav", "rb");
#endif
  fseek(fp, 0, SEEK_END);
  size = ftell(fp);
  fseek(fp, 0, SEEK_SET);

  data = (unsigned char*)malloc(size);
  fread(data, size, 1, fp);
  fclose(fp);

  offset = 12; // ignore the RIFF header
  offset += 8; // ignore the fmt header
  offset += 2; // ignore the format type

  channels = data[offset + 1] << 8;
  channels |= data[offset];
  offset += 2;
  printf("Channels: %u\n", channels);

  frequency = data[offset + 3] << 24;
  frequency |= data[offset + 2] << 16;
  frequency |= data[offset + 1] << 8;
  frequency |= data[offset];
  offset += 4;
  printf("Frequency: %u\n", frequency);

  offset += 6; // ignore block size and bps

  bits = data[offset + 1] << 8;
  bits |= data[offset];
  offset += 2;
  printf("Bits: %u\n", bits);

  format = 0;
  if (bits == 8) {
    if (channels == 1) {
      format = AL_FORMAT_MONO8;
    } else if (channels == 2) {
      format = AL_FORMAT_STEREO8;
    }
  } else if (bits == 16) {
    if (channels == 1) {
      format = AL_FORMAT_MONO16;
    } else if (channels == 2) {
      format = AL_FORMAT_STEREO16;
    }
  }
  offset += 8; // ignore the data chunk

  //
  // Seed the buffers with some initial data.
  //
  ALuint buffers[NUM_BUFFERS];
  alGenBuffers(NUM_BUFFERS, buffers);
  alGenSources(1, &source);

  ALint numBuffers = 0;
  while (numBuffers < NUM_BUFFERS && offset < size) {
    int len = size - offset;
    if (len > BUFFER_SIZE) {
      len = BUFFER_SIZE;
    }

    alBufferData(buffers[numBuffers], format, &data[offset], len, frequency);
    alSourceQueueBuffers(source, 1, &buffers[numBuffers]);
    assert(alGetError() == AL_NO_ERROR);

    offset += len;
    numBuffers++;
  }

  //
  // Start playing the source.
  //
  alSourcePlay(source);

  ALint state;
  alGetSourcei(source, AL_SOURCE_STATE, &state);
  assert(state == AL_PLAYING);

  alGetSourcei(source, AL_BUFFERS_QUEUED, &numBuffers);
  assert(numBuffers == NUM_BUFFERS);

  //
  // Cycle and refill the buffers until we're done.
  //
#if EMSCRIPTEN
  emscripten_set_main_loop(iter, 0, 0);
#else
  while (1) {
    iter(NULL);
    usleep(16);
  }
#endif
}
コード例 #4
0
ファイル: testrendercopyex.c プロジェクト: 03050903/Torque3D
int
main(int argc, char *argv[])
{
    int i;
    int frames;
    Uint32 then, now;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }
    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            SDL_Log("Usage: %s %s\n", argv[0], SDLTest_CommonUsage(state));
            return 1;
        }
        i += consumed;
    }
    if (!SDLTest_CommonInit(state)) {
        quit(2);
    }

    drawstates = SDL_stack_alloc(DrawState, state->num_windows);
    for (i = 0; i < state->num_windows; ++i) {
        DrawState *drawstate = &drawstates[i];

        drawstate->window = state->windows[i];
        drawstate->renderer = state->renderers[i];
        drawstate->sprite = LoadTexture(drawstate->renderer, "icon.bmp", SDL_TRUE);
        drawstate->background = LoadTexture(drawstate->renderer, "sample.bmp", SDL_FALSE);
        if (!drawstate->sprite || !drawstate->background) {
            quit(2);
        }
        SDL_QueryTexture(drawstate->sprite, NULL, NULL,
                         &drawstate->sprite_rect.w, &drawstate->sprite_rect.h);
        drawstate->scale_direction = 1;
    }

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        ++frames;
        loop();
        }
#endif
    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        double fps = ((double) frames * 1000) / (now - then);
        SDL_Log("%2.2f frames per second\n", fps);
    }

    SDL_stack_free(drawstates);

    quit(0);
    return 0;
}
コード例 #5
0
int main() {
  struct sockaddr_in addr;
  int res;

  memset(&server, 0, sizeof(server_t));
  server.state = MSG_WRITE;

  // setup the message we're going to echo
  memset(&echo_msg, 0, sizeof(msg_t));
  echo_msg.length = strlen(MESSAGE) + 1;
  echo_msg.buffer = malloc(echo_msg.length);
  strncpy(echo_msg.buffer, MESSAGE, echo_msg.length);

  echo_read = 0;
  echo_wrote = 0;

  // create the socket and set to non-blocking
#if !TEST_DGRAM
  server.fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  server.fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
#endif
  if (server.fd == -1) {
    perror("cannot create socket");
    finish(EXIT_FAILURE);
  }
  fcntl(server.fd, F_SETFL, O_NONBLOCK);

  // connect the socket
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(SOCKK);
  if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) != 1) {
    perror("inet_pton failed");
    finish(EXIT_FAILURE);
  }
  
  res = connect(server.fd, (struct sockaddr *)&addr, sizeof(addr));
  if (res == -1 && errno != EINPROGRESS) {
    perror("connect failed");
    finish(EXIT_FAILURE);
  }

  {
    int z;
    struct sockaddr_in adr_inet;
    socklen_t len_inet = sizeof adr_inet;
    z = getsockname(server.fd, (struct sockaddr *)&adr_inet, &len_inet);
    if (z != 0) {
      perror("getsockname");
      finish(EXIT_FAILURE);
    }
    char buffer[1000];
    sprintf(buffer, "%s:%u", inet_ntoa(adr_inet.sin_addr), (unsigned)ntohs(adr_inet.sin_port));
    // TODO: This is not the correct result: We should have a auto-bound address
    char *correct = "0.0.0.0:0";
    printf("got (expected) socket: %s (%s), size %d (%d)\n", buffer, correct, strlen(buffer), strlen(correct));
    assert(strlen(buffer) == strlen(correct));
    assert(strcmp(buffer, correct) == 0);
  }

  {
    int z;
    struct sockaddr_in adr_inet;
    socklen_t len_inet = sizeof adr_inet;
    z = getpeername(server.fd, (struct sockaddr *)&adr_inet, &len_inet);
    if (z != 0) {
      perror("getpeername");
      finish(EXIT_FAILURE);
    }
    char buffer[1000];
    sprintf(buffer, "%s:%u", inet_ntoa(adr_inet.sin_addr), (unsigned)ntohs(adr_inet.sin_port));
    char correct[1000];
    sprintf(correct, "127.0.0.1:%u", SOCKK);
    printf("got (expected) socket: %s (%s), size %d (%d)\n", buffer, correct, strlen(buffer), strlen(correct));
    assert(strlen(buffer) == strlen(correct));
    assert(strcmp(buffer, correct) == 0);
  }

#ifdef __EMSCRIPTEN__
#if TEST_ASYNC
  // The first parameter being passed is actually an arbitrary userData pointer
  // for simplicity this test just passes a basic char*
  emscripten_set_socket_error_callback("error", error_callback);
  emscripten_set_socket_open_callback("open", async_main_loop);
  emscripten_set_socket_message_callback("message", async_main_loop);
#else
  emscripten_set_main_loop(main_loop, 60, 0);
#endif
#else
  while (1) main_loop();
#endif

  return EXIT_SUCCESS;
}
コード例 #6
0
int main(int argc, char *argv[])
{
	Uint8  video_bpp;
	Uint32 videoflags;
	Uint8 *buffer;
	int i, k, done;
	Uint16 *buffer16;
        Uint16 color;
        Uint8  gradient;
	SDL_Color palette[256];


	/* Initialize SDL */
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(1);
	}

	video_bpp = 0;
	videoflags = SDL_SWSURFACE;
	while ( argc > 1 ) {
		--argc;
		if ( strcmp(argv[argc-1], "-bpp") == 0 ) {
			video_bpp = atoi(argv[argc]);
			--argc;
		} else
		if ( strcmp(argv[argc], "-warp") == 0 ) {
			videoflags |= SDL_HWPALETTE;
		} else
		if ( strcmp(argv[argc], "-hw") == 0 ) {
			videoflags |= SDL_HWSURFACE;
		} else
		if ( strcmp(argv[argc], "-fullscreen") == 0 ) {
			videoflags |= SDL_FULLSCREEN;
		} else {
			fprintf(stderr,
			"Usage: %s [-bpp N] [-warp] [-hw] [-fullscreen]\n",
								argv[0]);
			quit(1);
		}
	}

	/* Set 640x480 video mode */
	if ( (screen=SDL_SetVideoMode(640,480,video_bpp,videoflags)) == NULL ) {
		fprintf(stderr, "Couldn't set 640x480x%d video mode: %s\n",
						video_bpp, SDL_GetError());
		quit(2);
	}

	if (video_bpp==8) {
		/* Set a gray colormap, reverse order from white to black */
		for ( i=0; i<256; ++i ) {
			palette[i].r = 255-i;
			palette[i].g = 255-i;
			palette[i].b = 255-i;
		}
		SDL_SetColors(screen, palette, 0, 256);
	}

	/* Set the surface pixels and refresh! */
	if ( SDL_LockSurface(screen) < 0 ) {
		fprintf(stderr, "Couldn't lock the display surface: %s\n",
							SDL_GetError());
		quit(2);
	}
	buffer=(Uint8 *)screen->pixels;
	if (screen->format->BytesPerPixel!=2) {
        	for ( i=0; i<screen->h; ++i ) {
        		memset(buffer,(i*255)/screen->h, screen->pitch);
        		buffer += screen->pitch;
        	}
        }
        else
        {
		for ( i=0; i<screen->h; ++i ) {
			gradient=((i*255)/screen->h);
                        color = SDL_MapRGB(screen->format, gradient, gradient, gradient);
                        buffer16=(Uint16*)buffer;
                        for (k=0; k<screen->w; k++)
                        {
                            *(buffer16+k)=color;
                        }
			buffer += screen->pitch;
		}
        }
	SDL_UnlockSurface(screen);
	SDL_UpdateRect(screen, 0, 0, 0, 0);

	/* Load the bitmap */
	bitmap = LoadXBM(screen, picture_width, picture_height,
					(Uint8 *)picture_bits);
	if ( bitmap == NULL ) {
		quit(1);
	}
	
#ifndef EMSCRIPTEN
	SDL_Event event;
	/* Wait for a keystroke */
	done = 0;
	while ( !done ) {
#else
	emscripten_set_main_loop(&main_loop, 30, 1);
	return 0;
}

void main_loop()
{
	int done = 0;
	SDL_Event event;
	
	// Report success to the test framework to make this test work without user interaction.
	emscripten_run_script("report(true);");
#endif
		/* Check for events */
		while ( SDL_PollEvent(&event) ) {
			switch (event.type) {
				case SDL_MOUSEBUTTONDOWN: {
					SDL_Rect dst;

					dst.x = event.button.x - bitmap->w/2;
					dst.y = event.button.y - bitmap->h/2;
					dst.w = bitmap->w;
					dst.h = bitmap->h;
					SDL_BlitSurface(bitmap, NULL,
								screen, &dst);
					SDL_UpdateRects(screen,1,&dst);
					printf("User clicked at %d, %d!\n", dst.x, dst.y);
					}
					break;
				case SDL_KEYDOWN:
					/* Any key press quits the app... */
					done = 1;
					break;
				case SDL_QUIT:
					done = 1;
					break;
				default:
					break;
			}
		}
#ifndef EMSCRIPTEN
	}
コード例 #7
0
ファイル: mainloop_infloop.cpp プロジェクト: 4ian/emscripten
void inner() {
  inners++;
  printf("inner: mains, inners, nevers, loops: %d, %d, %d, %d\n", mains, inners, nevers, loops);
  emscripten_set_main_loop(loop, 1, 1);
  nevers++;
}
コード例 #8
0
ファイル: light_my_ritual.c プロジェクト: AdanBB/raylib
//----------------------------------------------------------------------------------
// Main entry point
//----------------------------------------------------------------------------------
int main(void)
{
	// Initialization
	//---------------------------------------------------------
    InitWindow(screenWidth, screenHeight, "GGJ16 - LIGHT MY RITUAL!");

    // Global data loading (assets that must be available in all screens, i.e. fonts)
    InitAudioDevice();

    Image image = LoadImage("resources/lights_map.png");  // Load image in CPU memory (RAM)
    
    lightsMap = GetImageData(image);            // Get image pixels data as an array of Color
    lightsMapWidth = image.width;
    lightsMapHeight = image.height;
    
    UnloadImage(image);                         // Unload image from CPU memory (RAM)
    
    //PlayMusicStream("resources/audio/come_play_with_me.ogg");
    
    font = LoadSpriteFont("resources/font_arcadian.png");
	//doors = LoadTexture("resources/textures/doors.png");
    //sndDoor = LoadSound("resources/audio/door.ogg");

    // Setup and Init first screen
    currentScreen = LOGO_RL;
    //InitTitleScreen();
    //InitGameplayScreen();
    rlInitLogoScreen();

#if defined(PLATFORM_WEB)
    emscripten_set_main_loop(UpdateDrawFrame, 0, 1);
#else
    SetTargetFPS(60);   // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        UpdateDrawFrame();
    }
#endif

    // De-Initialization
    //--------------------------------------------------------------------------------------
    switch (currentScreen)
    {
        case LOGO_RL: rlUnloadLogoScreen(); break;
        case TITLE: UnloadTitleScreen(); break;
        case GAMEPLAY: UnloadGameplayScreen(); break;
        default: break;
    }
    
    // Unload all global loaded data (i.e. fonts) here!
    UnloadSpriteFont(font);
    //UnloadSound(sndDoor);
    
    free(lightsMap);
    
    CloseAudioDevice();
    
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------
	
    return 0;
}
int main() {
  // Want to run at 2 fps, or 500msecs/frame.
  emscripten_set_main_loop(looper, 2, 0);
}
コード例 #10
0
ファイル: wave_collector.c プロジェクト: tws0002/raylib
//----------------------------------------------------------------------------------
// Main entry point
//----------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
	// Initialization
	//---------------------------------------------------------
#if defined(PLATFORM_DESKTOP)
    // TODO: Support for dropped files on the exe
    
    // Support command line argument for custom music file
    if (argc > 1)
    {
        // Just supporting an input argument parameter!!! o__O
        
        if ((IsFileExtension(argv[1], ".ogg")) ||
            (IsFileExtension(argv[1], ".wav")))
        {
            if (sampleFilename != NULL) free(sampleFilename);
            
            sampleFilename = (char *)malloc(256);
            strcpy(sampleFilename, argv[1]);
            
            printf("Custom audio file: %s", sampleFilename);
        }
    }
#endif

#ifndef PLATFORM_ANDROID
    SetConfigFlags(FLAG_MSAA_4X_HINT);
#endif
    // Note windowTitle is unused on Android
    InitWindow(screenWidth, screenHeight, "GGJ17 - WAVE COLLECTOR");

    // Global data loading (assets that must be available in all screens, i.e. fonts)
    InitAudioDevice();

    font = LoadFont("resources/font.fnt");
    music = LoadMusicStream("resources/audio/wave.ogg");
    
    SetMusicVolume(music, 1.0f);

    // Setup and Init first screen
    currentScreen = LOGO;
    InitLogoScreen();
    //InitTitleScreen();
    //InitGameplayScreen();
    //InitEndingScreen();

#if defined(PLATFORM_WEB)
    emscripten_set_main_loop(UpdateDrawFrame, 0, 1);
#else
    SetTargetFPS(60);   // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        UpdateDrawFrame();
    }
#endif

    // De-Initialization
    //--------------------------------------------------------------------------------------
    switch (currentScreen)
    {
        case LOGO: UnloadLogoScreen(); break;
        case TITLE: UnloadTitleScreen(); break;
        case GAMEPLAY: UnloadGameplayScreen(); break;
        case ENDING: UnloadEndingScreen(); break;
        default: break;
    }
    
    // Unload all global loaded data (i.e. fonts) here!
    UnloadFont(font);
    UnloadMusicStream(music);

    CloseAudioDevice();     // Close audio context
    
    CloseWindow();          // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
コード例 #11
0
ファイル: machine.c プロジェクト: fesh0r/old-mame
void js_set_main_loop(device_scheduler &sched) {
	scheduler = &sched;
	emscripten_set_main_loop(&js_main_loop, 0, 1);
}
コード例 #12
0
ファイル: main.cpp プロジェクト: zenogears/reicast-emulator
int main(int argc, wchar* argv[])
{
  if (setup_curses() < 0)
  {
    printf("failed to setup curses!\n");
  }
  #ifdef TARGET_PANDORA
    signal(SIGSEGV, clean_exit);
    signal(SIGKILL, clean_exit);
  #endif

  /* Set home dir */
  string home = ".";
  #if defined(USES_HOMEDIR)
    if(getenv("HOME") != NULL)
    {
      home = (string)getenv("HOME") + "/.reicast";
      mkdir(home.c_str(), 0755); // create the directory if missing
    }
  #endif
  SetHomeDir(home);
  printf("Home dir is: %s\n", GetPath("/").c_str());

  #if defined(SUPPORT_X11)
    x11_keymap[113] = DPad_Left;
    x11_keymap[114] = DPad_Right;

    x11_keymap[111] = DPad_Up;
    x11_keymap[116] = DPad_Down;

    x11_keymap[52] = Btn_Y;
    x11_keymap[53] = Btn_X;
    x11_keymap[54] = Btn_B;
    x11_keymap[55] = Btn_A;

    /*
      //TODO: Fix sliders
      x11_keymap[38] = DPad_Down;
      x11_keymap[39] = DPad_Down;
    */

    x11_keymap[36] = Btn_Start;
  #endif

  common_linux_setup();

  SetupInput();

  settings.profile.run_counts=0;

  dc_init(argc,argv);

  #if !defined(TARGET_EMSCRIPTEN)
    dc_run();
  #else
    emscripten_set_main_loop(&dc_run, 100, false);
  #endif


  #ifdef TARGET_PANDORA
    clean_exit(0);
  #endif

  return 0;
}
コード例 #13
0
void four(void *arg) {
  assert((int)arg == 43);
  printf("four!\n");
  emscripten_set_main_loop(mainey, 0, 0);
}
コード例 #14
0
ファイル: drawstress.cpp プロジェクト: deadalnix/bgfx
int _main_(int /*_argc*/, char** /*_argv*/)
{
	bgfx::init();
	bgfx::reset(width, height, reset);

	// Enable debug text.
	bgfx::setDebug(debug);

	// Set view 0 clear state.
	bgfx::setViewClear(0
			, BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
			, 0x303030ff
			, 1.0f
			, 0
			);

	// Create vertex stream declaration.
	PosColorVertex::init();

	const bgfx::Memory* vs_drawstress;
	const bgfx::Memory* fs_drawstress;

	switch (bgfx::getRendererType() )
	{
		case bgfx::RendererType::Direct3D9:
			vs_drawstress = bgfx::makeRef(vs_drawstress_dx9, sizeof(vs_drawstress_dx9) );
			fs_drawstress = bgfx::makeRef(fs_drawstress_dx9, sizeof(fs_drawstress_dx9) );
			break;

		case bgfx::RendererType::Direct3D11:
			vs_drawstress = bgfx::makeRef(vs_drawstress_dx11, sizeof(vs_drawstress_dx11) );
			fs_drawstress = bgfx::makeRef(fs_drawstress_dx11, sizeof(fs_drawstress_dx11) );
			break;

		default:
			vs_drawstress = bgfx::makeRef(vs_drawstress_glsl, sizeof(vs_drawstress_glsl) );
			fs_drawstress = bgfx::makeRef(fs_drawstress_glsl, sizeof(fs_drawstress_glsl) );
			break;
	}

	// Create program from shaders.
	program = bgfx::createProgram(
		  bgfx::createShader(vs_drawstress)
		, bgfx::createShader(fs_drawstress)
		, true /* destroy shaders when program is destroyed */
		);

	const bgfx::Memory* mem;

	// Create static vertex buffer.
	mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) );
	vbh = bgfx::createVertexBuffer(mem, PosColorVertex::ms_decl);

	// Create static index buffer.
	mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) );
	ibh = bgfx::createIndexBuffer(mem);

	imguiCreate(s_droidSansTtf);

#if BX_PLATFORM_EMSCRIPTEN
	emscripten_set_main_loop(&loop, -1, 1);
#else
	while (!mainloop() );
#endif // BX_PLATFORM_EMSCRIPTEN

	// Cleanup.
	imguiDestroy();
	bgfx::destroyIndexBuffer(ibh);
	bgfx::destroyVertexBuffer(vbh);
	bgfx::destroyProgram(program);

	// Shutdown bgfx.
	bgfx::shutdown();

	return 0;
}
コード例 #15
0
ファイル: loopwavequeue.c プロジェクト: Distrotech/SDL
int
main(int argc, char *argv[])
{
    char filename[4096];

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Load the SDL library */
    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    if (argc > 1) {
        SDL_strlcpy(filename, argv[1], sizeof(filename));
    } else {
        SDL_strlcpy(filename, "sample.wav", sizeof(filename));
    }
    /* Load the wave file into memory */
    if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
        quit(1);
    }

    wave.spec.callback = NULL;  /* we'll push audio. */

#if HAVE_SIGNAL_H
    /* Set the signals */
#ifdef SIGHUP
    signal(SIGHUP, poked);
#endif
    signal(SIGINT, poked);
#ifdef SIGQUIT
    signal(SIGQUIT, poked);
#endif
    signal(SIGTERM, poked);
#endif /* HAVE_SIGNAL_H */

    /* Initialize fillerup() variables */
    if (SDL_OpenAudio(&wave.spec, NULL) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
        SDL_FreeWAV(wave.sound);
        quit(2);
    }

    /*static x[99999]; SDL_QueueAudio(1, x, sizeof (x));*/

    /* Let the audio run */
    SDL_PauseAudio(0);

    done = 0;

    /* Note that we stuff the entire audio buffer into the queue in one
       shot. Most apps would want to feed it a little at a time, as it
       plays, but we're going for simplicity here. */
    
#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done && (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING))
    {
        loop();

        SDL_Delay(100);  /* let it play for awhile. */
    }
#endif

    /* Clean up on signal */
    SDL_CloseAudio();
    SDL_FreeWAV(wave.sound);
    SDL_Quit();
    return 0;
}
コード例 #16
0
int main(int argc, char *argv[])
{
	/* Check command line arguments */
	argv += get_video_args(argv, &w, &h, &bpp, &flags);

	/* Initialize SDL */
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr,
			"Couldn't initialize SDL: %s\n", SDL_GetError());
		return(1);
	}

	/* Initialize the display, always use hardware palette */
	screen = SDL_SetVideoMode(w, h, bpp, flags | SDL_HWPALETTE);
	if ( screen == NULL ) {
		fprintf(stderr, "Couldn't set %dx%d video mode: %s\n",
						w, h, SDL_GetError());
		quit(1);
	}

	/* Set the window manager title bar */
	SDL_WM_SetCaption("SDL gamma test", "testgamma");

	/* Set the desired gamma, if any */
	gamma = 1.0f;
	if ( *argv ) {
		gamma = (float)atof(*argv);
	}
	if ( SDL_SetGamma(gamma, gamma, gamma) < 0 ) {
		fprintf(stderr, "Unable to set gamma: %s\n", SDL_GetError());
		quit(1);
	}

#if 0 /* This isn't supported.  Integrating the gamma ramps isn't exact */
	/* See what gamma was actually set */
	float real[3];
	if ( SDL_GetGamma(&real[0], &real[1], &real[2]) < 0 ) {
		printf("Couldn't get gamma: %s\n", SDL_GetError());
	} else {
		printf("Set gamma values: R=%2.2f, G=%2.2f, B=%2.2f\n",
			real[0], real[1], real[2]);
	}
#endif

	/* Do all the drawing work */
	image = SDL_LoadBMP("sample.bmp");
	if ( image ) {
		SDL_Rect dst;

		dst.x = (screen->w - image->w)/2;
		dst.y = (screen->h - image->h)/2;
		dst.w = image->w;
		dst.h = image->h;
		SDL_BlitSurface(image, NULL, screen, &dst);
		SDL_UpdateRects(screen, 1, &dst);
	}

	/* Wait a bit, handling events */
	then = SDL_GetTicks();
	timeout = (5*1000);
#ifndef EMSCRIPTEN
	while ( (SDL_GetTicks()-then) < timeout ) {
#else
	
	emscripten_set_main_loop(&main_loop, 0, 1);
}

void main_loop() {
	if ( (SDL_GetTicks()-then) < timeout ) {
#endif
		SDL_Event event;

		while ( SDL_PollEvent(&event) ) {
			switch (event.type) {
			    case SDL_QUIT:	/* Quit now */
				timeout = 0;
				break;
			    case SDL_KEYDOWN:
				switch (event.key.keysym.sym) {
				    case SDLK_SPACE:	/* Go longer.. */
					timeout += (5*1000);
					break;
				    case SDLK_UP:
					gamma += 0.2f;
					SDL_SetGamma(gamma, gamma, gamma);
					break;
				    case SDLK_DOWN:
					gamma -= 0.2f;
					SDL_SetGamma(gamma, gamma, gamma);
					break;
				    case SDLK_ESCAPE:
					timeout = 0;
					break;
				    default:
					break;
				}
				break;
			}
		}
	}
#ifdef EMSCRIPTEN
	else {
#endif

	/* Perform a gamma flash to red using color ramps */
	while ( gamma < 10.0 ) {
		/* Increase the red gamma and decrease everything else... */
		gamma += 0.1f;
		CalculateGamma(gamma, red_ramp);
		CalculateGamma(1.0/gamma, ramp);
		SDL_SetGammaRamp(red_ramp, ramp, ramp);
	}
	/* Finish completely red */
	memset(red_ramp, 255, sizeof(red_ramp));
	memset(ramp, 0, sizeof(ramp));
	SDL_SetGammaRamp(red_ramp, ramp, ramp);

	/* Now fade out to black */
	for ( i=(red_ramp[0] >> 8); i >= 0; --i ) {
		memset(red_ramp, i, sizeof(red_ramp));
		SDL_SetGammaRamp(red_ramp, NULL, NULL);
	}

#ifndef EMSCRIPTEN
	SDL_Delay(1*1000);
#else
	emscripten_pause_main_loop();
	emscripten_async_call(&end_main, 0, 1*1000);
	}
}

void end_main() {
#endif
	SDL_Quit();

#ifndef EMSCRIPTEN
	return(0);
#else
	exit(0);
#endif
}
コード例 #17
0
ファイル: Main.cpp プロジェクト: Happy-Ferret/webkit.js
	int main(int argc, char** argv) {
		createWebKit(500,500,true);
		emscripten_set_main_loop(&tick, 0, false);
	}
コード例 #18
0
ファイル: Main.cpp プロジェクト: Jegp/dogfight
int main(int argc, char **argv) {
#if EMSCRIPTEN
  // include GL stuff, to check that we can compile hybrid 2d/GL apps
  extern void glBegin(int mode);
  extern void glBindBuffer(int target, int buffer);
  if (argc == 9876) {
    glBegin(0);
    glBindBuffer(0, 0);
  }

  // init main loop
  SDL_Init(SDL_INIT_VIDEO);
  screen = SDL_SetVideoMode(600, 450, 32, SDL_HWSURFACE);

  Environment * env;
  env->surface = screen;
  Game * game = new Game(env);

  printf("Init: %d\n", TTF_Init());

  emscripten_set_main_loop(main_loop, 30, 1);
#endif
  /*
  SDL_Init(SDL_INIT_VIDEO);
  SDL_Surface *screen = SDL_SetVideoMode(600, 450, 32, SDL_HWSURFACE);

  printf("Init: %d\n", TTF_Init());

  TTF_Font *font = TTF_OpenFont("sans-serif", 40);
  printf("Font: %p\n", font);

  SDL_Color color = { 0xff, 0x99, 0x00, 0xff };

  SDL_Surface *text = TTF_RenderText_Solid(font, "hello orange world", color);

  SDL_Color color2 = { 0xbb, 0, 0xff, 0xff };
  SDL_Surface *text2 = TTF_RenderText_Solid(font, "a second line, purple", color2);

  // render
  SDL_Rect dest = { 0, 50, 0, 0 };
  SDL_BlitSurface (text, NULL, screen, NULL);
  dest.y = 100;
  SDL_BlitSurface (text2, NULL, screen, &dest);

  // fill stuff
  SDL_Rect rect = { 200, 200, 175, 125 };
  SDL_FillRect(screen, &rect, SDL_MapRGBA(screen->format, 0x22, 0x22, 0xff, 0xff));

  SDL_Event event;
  while (SDL_PollEvent(&event)) {
      printf("Loop");
    switch (event.type) {
      case SDL_KEYDOWN:
        switch (event.key.keysym.sym) {
            case SDLK_RIGHT: printf("Right"); break;
            default: printf("Other key"); break;
        }
      default: printf("Event"); break;
    }
  }

  SDL_Flip(screen); 

  SDL_LockSurface(screen);

  int width, height, isFullscreen;
  emscripten_get_canvas_size(&width, &height, &isFullscreen);

  if (width != 600 && height != 450)
  {
    printf("error: wrong width/height\n");
    abort();
  }

  int sum = 0;
  for (int i = 0; i < screen->h; i++) {
    sum += *((char*)screen->pixels + i*screen->w*4 + i*4 + 0);
  }
  printf("Sum: %d\n", sum);

  printf("you should see two lines of text in different colors and a blue rectangle\n");

  SDL_UnlockSurface(screen);
  
  SDL_Quit();

  printf("done.\n");

  int result = sum > 3000 && sum < 5000; // varies a little on different browsers, font differences?
  REPORT_RESULT();
  */

  return 0;
}
コード例 #19
0
ファイル: webMain.cpp プロジェクト: LauriM/PropellerEngine
int main()
{
	setupKeys();// setup the HTML key mappings

	emscripten_set_canvas_size(800, 600);

	printf("hello world!\n");

	std::ifstream f;
	f.open( "./data/pyramid.PropellerModel", std::ifstream::binary );

	if(f.is_open())
		printf("file open ok!\n");
	else
		printf("file open not ok :< \n");

	engine::sys::addLogger(new game::sys::ConsoleLogger());


	printf("initting rendering\n");

	gameInstance.initializeRenderer(NULL);

	printf("starting init()\n");

	{
		engine::file::FileList files;
		gameInstance.getFileManager()->listFiles(files);

		engine::file::FileList::FileArray arr = files.getFiles();

		LOG_INFO("listing files, count: " << arr.size());
		for (unsigned i = 0; i < arr.size(); ++i)
			LOG_INFO(" * " << arr[i]);
	}

	gameInstance.getConsole()->execute("set defaultScene phys");

	gameInstance.init();

	{
		engine::file::FileList files;
		gameInstance.getFileManager()->listFiles(files);

		engine::file::FileList::FileArray arr = files.getFiles();

		LOG_INFO("listing files, count: " << arr.size());
		for (unsigned i = 0; i < arr.size(); ++i)
			LOG_INFO(" * " << arr[i]);
	}

	gameInstance.getConsole()->execute("echo OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
	gameInstance.getConsole()->execute("ls");
	gameInstance.getConsole()->execute("filemanagerlist");

	gameInstance.getConsole()->execute("listcommands");
	gameInstance.getConsole()->execute("listcvars");
	gameInstance.getConsole()->execute("systemlist");
	gameInstance.getConsole()->execute("ls");
	gameInstance.getConsole()->execute("setpos -2.8281 -1.2858 1.918");

	gameInstance.getConsole()->execute("bind KEY_W playerup");
	gameInstance.getConsole()->execute("bind KEY_S playerdown");
	gameInstance.getConsole()->execute("bind KEY_A playerleft");
	gameInstance.getConsole()->execute("bind KEY_D playerright");

	printf("init done\n");

	printf("total of %i systems registered.\n", gameInstance.getSystemManager()->getSystemList().size());

	gameInstance.update();

	emscripten_set_keydown_callback(NULL, NULL, true, &keyDown);
	emscripten_set_keyup_callback(NULL, NULL, true, &keyUp);

	emscripten_set_main_loop(loop, 60, 1);

	return 0;
}
コード例 #20
0
ファイル: testmultiaudio.c プロジェクト: Noughtceratops/SDL2
static void
test_multi_audio(int devcount)
{
    int keep_going = 1;
    int i;
    
#ifdef __ANDROID__  
    SDL_Event event;
  
    /* Create a Window to get fully initialized event processing for testing pause on Android. */
    SDL_CreateWindow("testmultiaudio", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, 0);
#endif

    if (devcount > 64) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Too many devices (%d), clamping to 64...\n",
                devcount);
        devcount = 64;
    }

    spec.callback = play_through_once;

    for (i = 0; i < devcount; i++) {
        const char *devname = SDL_GetAudioDeviceName(i, 0);
        SDL_Log("playing on device #%d: ('%s')...", i, devname);
        fflush(stdout);

        SDL_memset(&cbd[0], '\0', sizeof(callback_data));
        spec.userdata = &cbd[0];
        cbd[0].dev = SDL_OpenAudioDevice(devname, 0, &spec, NULL, 0);
        if (cbd[0].dev == 0) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Open device failed: %s\n", SDL_GetError());
        } else {
            SDL_PauseAudioDevice(cbd[0].dev, 0);
#ifdef __EMSCRIPTEN__
            emscripten_set_main_loop(loop, 0, 1);
#else
            while (!cbd[0].done)
            {
                #ifdef __ANDROID__                
                /* Empty queue, some application events would prevent pause. */
                while (SDL_PollEvent(&event)){}
                #endif                
                SDL_Delay(100);
            }
            SDL_PauseAudioDevice(cbd[0].dev, 1);
#endif
            SDL_Log("done.\n");
        }
    }

    SDL_memset(cbd, '\0', sizeof(cbd));

    SDL_Log("playing on all devices...\n");
    for (i = 0; i < devcount; i++) {
        const char *devname = SDL_GetAudioDeviceName(i, 0);
        spec.userdata = &cbd[i];
        cbd[i].dev = SDL_OpenAudioDevice(devname, 0, &spec, NULL, 0);
        if (cbd[i].dev == 0) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Open device %d failed: %s\n", i, SDL_GetError());
        }
    }

    for (i = 0; i < devcount; i++) {
        if (cbd[i].dev) {
            SDL_PauseAudioDevice(cbd[i].dev, 0);
        }
    }

    while (keep_going) {
        keep_going = 0;
        for (i = 0; i < devcount; i++) {
            if ((cbd[i].dev) && (!cbd[i].done)) {
                keep_going = 1;
            }
        }
        #ifdef __ANDROID__        
        /* Empty queue, some application events would prevent pause. */
        while (SDL_PollEvent(&event)){}
        #endif        

        SDL_Delay(100);
    }

#ifndef __EMSCRIPTEN__
    for (i = 0; i < devcount; i++) {
        if (cbd[i].dev) {
            SDL_PauseAudioDevice(cbd[i].dev, 1);
            SDL_CloseAudioDevice(cbd[i].dev);
        }
    }

    SDL_Log("All done!\n");
#endif
}
コード例 #21
0
int
main(int argc, char **argv)
{
    /* (argv[1] == NULL means "open default device.") */
    const char *devname = argv[1];
    SDL_AudioSpec wanted;
    int devcount;
    int i;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Load the SDL library */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    window = SDL_CreateWindow("testaudiocapture", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, 0);
    renderer = SDL_CreateRenderer(window, -1, 0);
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());

    devcount = SDL_GetNumAudioDevices(SDL_TRUE);
    for (i = 0; i < devcount; i++) {
        SDL_Log(" Capture device #%d: '%s'\n", i, SDL_GetAudioDeviceName(i, SDL_TRUE));
    }

    SDL_zero(wanted);
    wanted.freq = 44100;
    wanted.format = AUDIO_F32SYS;
    wanted.channels = 1;
    wanted.samples = 4096;
    wanted.callback = NULL;

    SDL_zero(spec);

    /* DirectSound can fail in some instances if you open the same hardware
       for both capture and output and didn't open the output end first,
       according to the docs, so if you're doing something like this, always
       open your capture devices second in case you land in those bizarre
       circumstances. */

    SDL_Log("Opening default playback device...\n");
    devid_out = SDL_OpenAudioDevice(NULL, SDL_FALSE, &wanted, &spec, SDL_AUDIO_ALLOW_ANY_CHANGE);
    if (!devid_out) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open an audio device for playback: %s!\n", SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    SDL_Log("Opening capture device %s%s%s...\n",
            devname ? "'" : "",
            devname ? devname : "[[default]]",
            devname ? "'" : "");

    devid_in = SDL_OpenAudioDevice(argv[1], SDL_TRUE, &spec, &spec, 0);
    if (!devid_in) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open an audio device for capture: %s!\n", SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    SDL_Log("Ready! Hold down mouse or finger to record!\n");

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (1) { loop(); SDL_Delay(16); }
#endif

    return 0;
}
コード例 #22
0
ファイル: raylib_demo.c プロジェクト: MarcMDE/raylib
//----------------------------------------------------------------------------------
// Main entry point
//----------------------------------------------------------------------------------
int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const char windowTitle[30] = "raylib functionality demo";
   
    //SetupFlags(FLAG_FULLSCREEN_MODE);
    InitWindow(screenWidth, screenHeight, windowTitle);
    
    InitAudioDevice();             // Initialize audio device

    // TITLE screen variables Initialization
    fontAlagard = LoadSpriteFont("resources/fonts/alagard.rbmf");        // rBMF font loading
    fontPixelplay = LoadSpriteFont("resources/fonts/pixelplay.rbmf");    // rBMF font loading
    fontMecha = LoadSpriteFont("resources/fonts/mecha.rbmf");            // rBMF font loading
    fontSetback = LoadSpriteFont("resources/fonts/setback.rbmf");        // rBMF font loading
    fontRomulus = LoadSpriteFont("resources/fonts/romulus.rbmf");        // rBMF font loading
    
    pongBallPosition = (Vector2){ screenWidth/2, screenHeight/2 + 20 };
    pongBallSpeed = (Vector2){ 6, 6 };
    pongPlayerRec = (Rectangle){ 20, screenHeight/2 - 50 + 40, 20, 100 };
    pongEnemyRec = (Rectangle){ screenWidth - 40, screenHeight/2 - 60, 20, 120 };

    // LOGO screen variables Initialization
    logoPositionX = screenWidth/2 - 128;
    logoPositionY = screenHeight/2 - 128;
    
    // MODULES screen variables Initialization
    raylibWindow = LoadTexture("resources/raylib_window.png");
    raylibWindow01 = LoadTexture("resources/raylib_window_01.png");
    raylibWindow02 = LoadTexture("resources/raylib_window_02.png");
    raylibWindow03 = LoadTexture("resources/raylib_window_03.png");
    platforms = LoadTexture("resources/platforms.png");
    raylibLogoB = LoadTexture("resources/raylib_logo128x128.png");
    lena = LoadTexture("resources/lena.png");
    mandrill = LoadTexture("resources/mandrill.png");
    texAlagard = LoadTexture("resources/fonts/custom_alagard.png");
    fontMechaC = LoadSpriteFont("resources/fonts/custom_mecha.png");
    fontAlagardC = LoadSpriteFont("resources/fonts/custom_alagard.png");
    fontJupiterC = LoadSpriteFont("resources/fonts/custom_jupiter_crash.png");
    
    ballPosition = (Vector2){ 520 + 656/2, 220 + 399/2 };
    
    camera = (Camera){{ 0.0, 12.0, 15.0 }, { 0.0, 3.0, 0.0 }, { 0.0, 1.0, 0.0 }};

    catTexture = LoadTexture("resources/catsham.png");   // Load model texture
    cat = LoadModel("resources/cat.obj");                 // Load OBJ model
    SetModelTexture(&cat, catTexture);
    
    fxWav = LoadSound("resources/audio/weird.wav");         // Load WAV audio file
    fxOgg = LoadSound("resources/audio/tanatana.ogg");      // Load OGG audio file
    
    for (int i = 0; i < MAX_BALLS; i++)
    {
        soundBallsPosition[i] = (Vector2){ 650 + 560/2 + GetRandomValue(-280, 280), 220 + 200 + GetRandomValue(-200, 200) };
        soundBallsColor[i] = (Color){ GetRandomValue(0, 255), GetRandomValue(0, 255), GetRandomValue(0, 255), 255 };
        soundBallsRadius[i] = GetRandomValue(2, 50);
        soundBallsAlpha[i] = 1.0f;
        
        soundBallsActive[i] = false;
    }
    
    // ENDING screen variables Initialization
    raylibLogoA = LoadTexture("resources/raylib_logo.png");

#ifndef PLATFORM_WEB
    SetTargetFPS(60);
#endif

#if defined(PLATFORM_WEB)
    emscripten_set_main_loop(UpdateDrawOneFrame, 0, 1);
#else
    //--------------------------------------------------------------------------------------
    
    // Main game loop
    while (!WindowShouldClose() && !closeWindow)    // Detect window close button or ESC key
    {
        UpdateDrawOneFrame();
    }
#endif

    // De-Initialization
    //--------------------------------------------------------------------------------------

    // Unload all loaded data (textures, fonts, audio)
    UnloadSpriteFont(fontAlagard);      // SpriteFont unloading
    UnloadSpriteFont(fontPixelplay);    // SpriteFont unloading
    UnloadSpriteFont(fontMecha);        // SpriteFont unloading
    UnloadSpriteFont(fontSetback);      // SpriteFont unloading
    UnloadSpriteFont(fontRomulus);      // SpriteFont unloading

    UnloadTexture(raylibWindow);
    UnloadTexture(raylibWindow01);
    UnloadTexture(raylibWindow02);
    UnloadTexture(raylibWindow03);
    UnloadTexture(platforms);
    UnloadTexture(raylibLogoA);
    UnloadTexture(raylibLogoB);
    UnloadTexture(lena);
    UnloadTexture(mandrill);
    UnloadTexture(texAlagard);

    UnloadSpriteFont(fontMechaC);
    UnloadSpriteFont(fontAlagardC);
    UnloadSpriteFont(fontJupiterC);

    UnloadTexture(catTexture);
    UnloadModel(cat);

    UnloadSound(fxWav);
    UnloadSound(fxOgg);

    CloseAudioDevice();
    
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
コード例 #23
0
ファイル: platform.cpp プロジェクト: actbinary/semimade_dev1
//Program entry point
int main(int argc, char *argv[])
{
	UNUSED(argc);
	UNUSED(argv);

	//paths required by platform code
	platform::app_code.app_dll_path = "App.dll";
	platform::app_state.record_file = "input.smi";

	//Load the application dll
	platform_load_app_code(&platform::app_code);

	//initialize sdl
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		std::cerr << ERROR_LINE << "SDL Error: Unable to initialize SDL" << std::endl;
	}
	else
	{
		std::cout << "SDL initialized"<<std::endl;
	}

	//SDL version
	{
		SDL_version ver;
		SDL_VERSION(&ver);
		std::cout << "SDL version " << (int)ver.major << "." << (int)ver.minor << "." << (int)ver.patch << std::endl;
		SDL_GetVersion(&ver);
		std::cout << "Linked version " << (int)ver.major << "." << (int)ver.minor << "." << (int)ver.patch << std::endl;
	}

	//init time
	platform_update_time(platform::app_time);

	//call app config to get settings
	platform::app_code.config(&platform::services.config);

	//Set Opengl attributes
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, PLATFORM_GL_VERSION_MAJOR);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, PLATFORM_GL_VERSION_MINOR);

	//Set buffer attributes
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, PLATFORM_GL_DOUBLEBUFFER);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, PLATFORM_GL_DEPTHBUFFER);


	//Create a window
	platform_create_window();

	if (!platform::services.config.sdl_window)
	{
		std::cerr << ERROR_LINE << "Error: Unable to create window" << std::endl;
		return -1;
	}
	else
	{
		platform::services.config.quit = false;
		std::cout << "SDL window " << platform::services.config.width << "x" << platform::services.config.height << " opened" << std::endl;
	}

	//set OpenGL context
	auto sdl_context = SDL_GL_CreateContext(platform::services.config.sdl_window);

	// Initialise GLEW
	glewExperimental = GL_TRUE;
	GLenum glewError = glewInit();

	if (glewError != GLEW_OK)
	{
		std::cerr << ERROR_LINE << "GLEW Error: Unable to initialise glew";
		return -1;
	}
	else
	{
		std::cout<<"GLEW "<<glewGetString(GLEW_VERSION)<<" Initialised";
	}

	//Allocate memory for the app
	auto base_address = Gigabytes(1);
	platform::services.memory = {};
	platform::services.memory.permanent_memory_size = Megabytes(8);
	platform::services.memory.permanent_memory = platform::os::get_memory(base_address,platform::services.memory.permanent_memory_size);

	if (!platform::services.memory.permanent_memory)
	{
		std::cerr << "\nUnable to allocate enough memory";
		return -1;
	}

	//link memory to app state
	platform::app_state.memory = &platform::services.memory;

	//call the application startup
	platform::app_code.startup(&platform::services);

	//run application
	#ifdef __EMSCRIPTEN__
	emscripten_set_main_loop(platform_update, 0, true);
	#else
	//run as long as quit is not set to true
	while(!platform::services.config.quit)
	{
		platform_update();
	}
	#endif

	//free resources
	SDL_GL_DeleteContext(sdl_context);
	SDL_DestroyWindow(platform::services.config.sdl_window);

	//exit
	return 0;
}
コード例 #24
0
ファイル: teststreaming.c プロジェクト: 03050903/Torque3D
int
main(int argc, char **argv)
{
    SDL_Window *window;
    SDL_RWops *handle;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    /* load the moose images */
    handle = SDL_RWFromFile("moose.dat", "rb");
    if (handle == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Can't find the file moose.dat !\n");
        quit(2);
    }
    SDL_RWread(handle, MooseFrames, MOOSEFRAME_SIZE, MOOSEFRAMES_COUNT);
    SDL_RWclose(handle);


    /* Create the window and renderer */
    window = SDL_CreateWindow("Happy Moose",
                              SDL_WINDOWPOS_UNDEFINED,
                              SDL_WINDOWPOS_UNDEFINED,
                              MOOSEPIC_W*4, MOOSEPIC_H*4,
                              SDL_WINDOW_RESIZABLE);
    if (!window) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create window: %s\n", SDL_GetError());
        quit(3);
    }

    renderer = SDL_CreateRenderer(window, -1, 0);
    if (!renderer) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create renderer: %s\n", SDL_GetError());
        quit(4);
    }

    MooseTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, MOOSEPIC_W, MOOSEPIC_H);
    if (!MooseTexture) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create texture: %s\n", SDL_GetError());
        quit(5);
    }

    /* Loop, waiting for QUIT or the escape key */
    frame = 0;

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        loop();
        }
#endif

    SDL_DestroyRenderer(renderer);

    quit(0);
    return 0;
}
コード例 #25
0
ファイル: geo_core_app.cpp プロジェクト: PhilCK/geo-core
int
main()
{
  // Tap into error messages (we won't get startup errors because sdl_wrappers are in anon namespace.
  {
    auto sdl_error_callback = [](const std::string &error_msg)
    {
      std::cout << error_msg << std::endl;
    };
    
    auto renderer_error_callback = [](const uint32_t id, const std::string &msg)
    {
      if(id > GL_NO_ERROR)
      {
        std::cout << "Renderer Error: " << id << " - " << msg << std::endl;
      }
      else
      {
        std::cout << "Renderer Info: " << msg << std::endl;
      }
    };
    
    sdl::set_error_callback(sdl_error_callback);
    renderer::set_log_callback(renderer_error_callback);
  }
  
  renderer::initialize();
  component::mesh_renderer::initialize();

  // Map Entity Setup
  {
    map_entity = object_factory::create_map();
    caff_math::transform set_transform;
    component::world_transform::set(map_entity, set_transform);
    component::mesh::set(map_entity, "assets/models/unit_plane.obj");
    component::material::set(map_entity, "assets/textures/test_web_mercator_03.png");
  }
  
  // Marker Entity Setup
  {
    marker_entity = object_factory::create_marker();
    caff_math::transform set_transform;
    set_transform.scale = caff_math::vector3_init(0.1f, 1.f, 0.1f);

    const float latitude  = -33.8650;
    const float longitude = 151.2094;
    
    float merc_x = 0.f;
    float merc_y = 0.f;
    
    projection::convert_lat_long_to_web_mercator(merc_x, merc_y, latitude, longitude, 256, 256);
    
    const float x = (merc_x - 0.5f); // Normalized (Unsure if this is right).
    const float y = (merc_y - 0.5f); // Normalized (Unsure if this is right).

    set_transform.position = caff_math::vector3_init(x, 0.f, y);

    component::world_transform::set(marker_entity, set_transform);
    
    component::mesh::set(marker_entity, "assets/models/unit_plane.obj");
    component::material::set(marker_entity, "assets/textures/dev_grid_red.png");
  }
  
  // Camera
  {
    camera_entity = object_factory::create_camera();
    caff_math::transform set_transform;
    set_transform.position = caff_math::vector3_init(0, 10, 0);
    set_transform.rotation = caff_math::quaternion_init_with_axis_angle(1, 0, 0, caff_math::quart_tau());
    component::world_transform::set(camera_entity, set_transform);
  }

  
  #ifndef __EMSCRIPTEN__
  while(!window.wants_to_quit())
  {
    frame_tick();
  }
  #else
    emscripten_set_main_loop(&frame_tick, 60, true);
  #endif
  
  return 0;
}
コード例 #26
0
ファイル: np2.c プロジェクト: utamaro/np2.js
int main(int argc, char **argv) {
//int SDL_main(int argc, char **argv) {

	int		pos;
	char	*p;
	int		id;

	pos = 1;
	while(pos < argc) {
		p = argv[pos++];
		if ((!milstr_cmp(p, "-h")) || (!milstr_cmp(p, "--help"))) {
			usage(argv[0]);
			goto np2main_err1;
		}
		else {
			printf("error command: %s\n", p);
			goto np2main_err1;
		}
	}

	SDL_Init(SDL_INIT_EVERYTHING);
	dosio_init();
	file_setcd(datadir);
	initload();

	TRACEINIT();

	if (fontmng_init() != SUCCESS) {
		goto np2main_err2;
	}
	sdlkbd_initialize();
	inputmng_init();
	keystat_initialize();

	if (sysmenu_create() != SUCCESS) {
		goto np2main_err3;
	}

	scrnmng_initialize();
	if (scrnmng_create(FULLSCREEN_WIDTH, FULLSCREEN_HEIGHT) != SUCCESS) {
		goto np2main_err4;
	}

	soundmng_initialize();
	commng_initialize();
	sysmng_initialize();
	taskmng_initialize();
	pccore_init();
	S98_init();

	scrndraw_redraw();
	pccore_reset();

	if (np2oscfg.resume) {
		id = flagload(str_sav, str_resume, FALSE);
		if (id == DID_CANCEL) {
			goto np2main_err5;
		}
	}

#ifdef EMSCRIPTEN
  emscripten_set_main_loop(main_loop,1000,1);
#else
	while(taskmng_isavail()) {
		taskmng_rol();
		if (np2oscfg.NOWAIT) {
			pccore_exec(framecnt == 0);
			if (np2oscfg.DRAW_SKIP) {			// nowait frame skip
				framecnt++;
				if (framecnt >= np2oscfg.DRAW_SKIP) {
					processwait(0);
				}
			}
			else {							// nowait auto skip
				framecnt = 1;
				if (timing_getcount()) {
					processwait(0);
				}
			}
		}
		else if (np2oscfg.DRAW_SKIP) {		// frame skip
			if (framecnt < np2oscfg.DRAW_SKIP) {
				pccore_exec(framecnt == 0);
				framecnt++;
			}
			else {
				processwait(np2oscfg.DRAW_SKIP);
			}
		}
		else {								// auto skip
			if (!waitcnt) {
				UINT cnt;
				pccore_exec(framecnt == 0);
				framecnt++;
				cnt = timing_getcount();
				if (framecnt > cnt) {
					waitcnt = framecnt;
					if (framemax > 1) {
						framemax--;
					}
				}
				else if (framecnt >= framemax) {
					if (framemax < 12) {
						framemax++;
					}
					if (cnt >= 12) {
						timing_reset();
					}
					else {
						timing_setcount(cnt - framecnt);
					}
					framereset(0);
				}
			}
			else {
				processwait(waitcnt);
				waitcnt = framecnt;
			}
		}
	}
#endif

	pccore_cfgupdate();
	if (np2oscfg.resume) {
		flagsave(str_sav);
	}
	else {
		flagdelete(str_sav);
	}
	pccore_term();
	S98_trash();
	soundmng_deinitialize();

	if (sys_updates	& (SYS_UPDATECFG | SYS_UPDATEOSCFG)) {
		initsave();
	}

	scrnmng_destroy();
	sysmenu_destroy();
	TRACETERM();
	SDL_Quit();
	dosio_term();
	return(SUCCESS);

np2main_err5:
	pccore_term();
	S98_trash();
	soundmng_deinitialize();

np2main_err4:
	scrnmng_destroy();

np2main_err3:
	sysmenu_destroy();

np2main_err2:
	TRACETERM();
	SDL_Quit();
	dosio_term();

np2main_err1:
	return(FAILURE);
}
コード例 #27
0
ファイル: testaudiohotplug.c プロジェクト: 03050903/Torque3D
int
main(int argc, char *argv[])
{
    int i;
    char filename[4096];

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Load the SDL library */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    /* Some targets (Mac CoreAudio) need an event queue for audio hotplug, so make and immediately hide a window. */
    SDL_MinimizeWindow(SDL_CreateWindow("testaudiohotplug", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0));

    if (argc > 1) {
        SDL_strlcpy(filename, argv[1], sizeof(filename));
    } else {
        SDL_strlcpy(filename, "sample.wav", sizeof(filename));
    }
    /* Load the wave file into memory */
    if (SDL_LoadWAV(filename, &spec, &sound, &soundlen) == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
        quit(1);
    }

#if HAVE_SIGNAL_H
    /* Set the signals */
#ifdef SIGHUP
    signal(SIGHUP, poked);
#endif
    signal(SIGINT, poked);
#ifdef SIGQUIT
    signal(SIGQUIT, poked);
#endif
    signal(SIGTERM, poked);
#endif /* HAVE_SIGNAL_H */

    /* Show the list of available drivers */
    SDL_Log("Available audio drivers:");
    for (i = 0; i < SDL_GetNumAudioDrivers(); ++i) {
        SDL_Log("%i: %s", i, SDL_GetAudioDriver(i));
    }

    SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        SDL_Delay(100);
        iteration();
    }
#endif

    /* Clean up on signal */
    SDL_FreeWAV(sound);
    SDL_Quit();
    return (0);
}
コード例 #28
0
int
main(int argc, char *argv[])
{
    int i;
    Uint32 then, now, frames;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize parameters */
    num_objects = NUM_OBJECTS;

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }
    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            consumed = -1;
            if (SDL_strcasecmp(argv[i], "--blend") == 0) {
                if (argv[i + 1]) {
                    if (SDL_strcasecmp(argv[i + 1], "none") == 0) {
                        blendMode = SDL_BLENDMODE_NONE;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "blend") == 0) {
                        blendMode = SDL_BLENDMODE_BLEND;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "add") == 0) {
                        blendMode = SDL_BLENDMODE_ADD;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
                        blendMode = SDL_BLENDMODE_MOD;
                        consumed = 2;
                    }
                }
            } else if (SDL_strcasecmp(argv[i], "--cyclecolor") == 0) {
                cycle_color = SDL_TRUE;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--cyclealpha") == 0) {
                cycle_alpha = SDL_TRUE;
                consumed = 1;
            } else if (SDL_isdigit(*argv[i])) {
                num_objects = SDL_atoi(argv[i]);
                consumed = 1;
            }
        }
        if (consumed < 0) {
            SDL_Log("Usage: %s %s [--blend none|blend|add|mod] [--cyclecolor] [--cyclealpha]\n",
                    argv[0], SDLTest_CommonUsage(state));
            return 1;
        }
        i += consumed;
    }
    if (!SDLTest_CommonInit(state)) {
        return 2;
    }

    /* Create the windows and initialize the renderers */
    for (i = 0; i < state->num_windows; ++i) {
        SDL_Renderer *renderer = state->renderers[i];
        SDL_SetRenderDrawBlendMode(renderer, blendMode);
        SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
        SDL_RenderClear(renderer);
    }

    srand((unsigned int)time(NULL));

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        ++frames;
        loop();
    }
#endif


    SDLTest_CommonQuit(state);

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        double fps = ((double) frames * 1000) / (now - then);
        SDL_Log("%2.2f frames per second\n", fps);
    }
    return 0;
}
コード例 #29
0
int
main(int argc, char *argv[])
{
    int i;
    const char *color_cursor = NULL;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }
    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            color_cursor = argv[i];
            break;
        }
        if (consumed < 0) {
            SDL_Log("Usage: %s %s\n", argv[0], SDLTest_CommonUsage(state));
            quit(1);
        }
        i += consumed;
    }

    if (!SDLTest_CommonInit(state)) {
        quit(2);
    }

    for (i = 0; i < state->num_windows; ++i) {
        SDL_Renderer *renderer = state->renderers[i];
        SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
        SDL_RenderClear(renderer);
    }

    if (color_cursor) {
        cursor = init_color_cursor(color_cursor);
    } else {
        cursor = init_system_cursor(arrow);
    }
    if (!cursor) {
        SDL_Log("Error, couldn't create cursor\n");
        quit(2);
    }
    SDL_SetCursor(cursor);

    /* Main render loop */
    done = 0;
#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        loop();
    }
#endif

    SDL_FreeCursor(cursor);
    quit(0);

    /* keep the compiler happy ... */
    return(0);
}
コード例 #30
0
ファイル: core.cpp プロジェクト: RichardRanft/LoomSDK
int
main(int argc, char *argv[])
{
#ifdef MSVC_DEBUG_HEAP
    // Get current flag
    int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

    tmpFlag |= _CRTDBG_ALLOC_MEM_DF;
    tmpFlag |= _CRTDBG_LEAK_CHECK_DF;

    // Set flag to the new value.
    _CrtSetDbgFlag(tmpFlag);
#endif

#ifdef WIN32
    // When on windows, do some workarounds so our console window
    // behaves properly.
    
    // put the program name into argv[0]
    char filename[_MAX_PATH];
    GetModuleFileNameA(NULL, filename, _MAX_PATH);
    argv[0] = filename;

    bool fromRuby = false;

    for (int i = 1; i < argc; i++)
    {
        if (!stricmp(argv[i], "ProcessID") && i + 1 < argc)
        {
            fromRuby = true;

            char *pEnd;  

            long int pid = strtol (argv[i + 1], &pEnd, 10);

            LS::Process::rubyProcessId = pid;

            memmove(argv + i, argv + i + 2, (argc - i - 2)*sizeof(char*));
            argc -= 2;
            i--;
            break;
        }
    }

    LS::Process::consoleAttached = false;
    if (!fromRuby && AttachConsole(ATTACH_PARENT_PROCESS))
    {
        HANDLE consoleHandleOut = GetStdHandle(STD_OUTPUT_HANDLE);
        int fdOut = _open_osfhandle((intptr_t)consoleHandleOut, _O_TEXT);
        FILE *fpOut = _fdopen(fdOut, "w");
        *stdout = *fpOut;
        setvbuf(stdout, NULL, _IONBF, 0);

        //redirect unbuffered STDERR to the console
        HANDLE consoleHandleError = GetStdHandle(STD_ERROR_HANDLE);
        int fdError = _open_osfhandle((intptr_t)consoleHandleError, _O_TEXT);
        FILE *fpError = _fdopen(fdError, "w");
        *stderr = *fpError;
        setvbuf(stderr, NULL, _IONBF, 0);

        LS::Process::consoleAttached = true;
    }
#endif

    // Initialize logging.
    loom_log_initialize();

    LSLuaState::initCommandLine(argc, (const char**) argv);

    /* Enable standard application logging */
    SDL_LogSetAllPriority(SDL_LOG_PRIORITY_INFO);
    SDL_LogSetOutputFunction(sdlLogOutput, NULL);

    SDL_Init(
        SDL_INIT_TIMER |
        SDL_INIT_VIDEO | 
        SDL_INIT_JOYSTICK |
        SDL_INIT_HAPTIC |
        SDL_INIT_GAMECONTROLLER |
        SDL_INIT_EVENTS
    );

    

    int ret;

    
#if LOOM_RENDERER_OPENGLES2
    ret = SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
    lmAssert(ret == 0, "SDL Error: %s", SDL_GetError());
    ret = SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    lmAssert(ret == 0, "SDL Error: %s", SDL_GetError());
#endif
    
    int stencilSize = 1;
    ret = SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencilSize);
    lmAssert(ret == 0, "SDL Error: %s", SDL_GetError());
    
    // Set up SDL window.
    if ((gSDLWindow = SDL_CreateWindow(
        "Loom",
        0, 0,
        100,
        100,
        SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN
#if LOOM_PLATFORM == LOOM_PLATFORM_IOS
        | SDL_WINDOW_BORDERLESS
#endif
        | SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI)) == NULL)
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateWindow(): %s\n", SDL_GetError());
        exit(0);
    }

    gContext = SDL_GL_CreateContext(gSDLWindow);
    if (!gContext) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GL_CreateContext(): %s\n", SDL_GetError());
        exit(2);
    }

    ret = SDL_GL_SetSwapInterval(-1);
    if (ret != 0) {
        lmLog(coreLogGroup, "Late swap tearing not supported, using vsync");
        SDL_GL_SetSwapInterval(1);
    }

    // And show the window with proper settings.
    SDL_SetWindowPosition(gSDLWindow, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);

    SDL_StopTextInput();

    // Initialize Loom!
    loom_appSetup();    
    supplyEmbeddedAssets();

    /* Main render loop */
    gLoomExecutionDone = 0;

    /* Display SDL version */
    SDL_version compiled;
    SDL_version linked;

    SDL_VERSION(&compiled);
    SDL_GetVersion(&linked);

    lmLogDebug(coreLogGroup, "Compiled with SDL version %d.%d.%d and linking against SDL version %d.%d.%d ...", compiled.major, compiled.minor, compiled.patch, linked.major, linked.minor, linked.patch);

    /* Game Controller */
    // Enable controller events
    SDL_GameControllerEventState(SDL_ENABLE);

    //Open all connected game controllers
    LoomGameController::openAll();
    
#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!gLoomExecutionDone) loop();
#endif

    //Close all opened game controllers before closing application
    LoomGameController::closeAll();
    loom_appShutdown();
    
#ifdef WIN32
    LS::Process::cleanupConsole();
#endif

    exit(0);
    return 0; /* to prevent compiler warning */
}