Example #1
0
job::job(std::shared_ptr<job_metadata> job_meta,
	std::shared_ptr<worker_config> worker_conf,
	fs::path working_directory,
	fs::path source_path,
	fs::path result_path,
	std::shared_ptr<task_factory_interface> factory,
	std::shared_ptr<progress_callback_interface> progr_callback)
	: job_meta_(job_meta), worker_config_(worker_conf), working_directory_(working_directory),
	  source_path_(source_path), result_path_(result_path), factory_(factory), progress_callback_(progr_callback)
{
	// check construction parameters if they are in right format
	if (job_meta_ == nullptr) {
		throw job_exception("Job configuration cannot be null");
	} else if (worker_config_ == nullptr) {
		throw job_exception("Worker configuration cannot be null");
	} else if (factory_ == nullptr) {
		throw job_exception("Task factory pointer cannot be null");
	}

	// if progress callback is null, we have to use default one
	init_progress_callback();

	// check injected directories
	check_job_dirs();

	// prepare variables which will be used in job config
	prepare_job_vars();

	// construct system logger for this job
	init_logger();

	// build job from given job configuration
	build_job();
}
Example #2
0
int main(int argc,  char *argv[])
{
	serverInputs inputs;
    int sd;
	logger * logg;
	

	parseArgs(&inputs, argc, argv);
	printf("Log File Path: %s\n", inputs.logPath);
	printf("Documents Path: %s\n", inputs.directory);
	logg = init_logger(inputs.logPath);

	sd = init_socket(&inputs);

	printf("Server up and  listening on port: %d\n", inputs.port);

	daemon(1,1);

	for(;;) {
		request* req = malloc(sizeof(request));
		pthread_t thread;
		memset(req, 0, sizeof(*req));
		req->l = logg;
		int *clientsd = malloc(sizeof(int));
		*clientsd = accept_connection(sd, &(req->client));
		req->inputsDIR = inputs.directory;
		
		req->requestSD = clientsd;
		pthread_create(&thread, NULL, thread_starter, (void*)req);
	}
	
}
Example #3
0
File: fibjs.cpp Project: fibx/fibjs
void init(int32_t argc, char *argv[])
{
    ::setlocale(LC_ALL, "");

    if (options(&argc, argv))
        _exit(0);

    int32_t cpus = 0;

    os_base::CPUs(cpus);
    if (cpus < 2)
        cpus = 2;

    exlib::Service::init(cpus + 1);

    init_prof();
    init_argv(argc, argv);
    init_date();
    init_rt();
    init_sandbox();
    init_acThread();
    init_logger();
    init_net();
    init_fiber();

    srand((unsigned int)time(0));

    v8::Platform *platform = v8::platform::CreateDefaultPlatform();
    v8::V8::InitializePlatform(platform);

    v8::V8::Initialize();
}
Example #4
0
int main(int argc, char** argv) {
    
    pthread_t threads[NUM_CONTROLLERS];
    
    if (argc != 3) 
    {
        fprintf(stderr, "Usage: parque <N_LUGARES> <T_ABERTURA>\n");
        exit(1);
    }
    
    
    if (convert_str_to_int(argv[1], &numLugares) != 0)
    {
        fprintf(stderr, "Invalid entry for N_LUGARES\n");
        exit(2);
    }
    
    if (convert_str_to_int(argv[2], &tAbertura) != 0)
    {
        fprintf(stderr, "Invalid entry for T_ABERTURA\n");
        exit(3);
    }
    
    if ( (fp_logger = init_logger(LOGGER_NAME)) == NULL )
    {
        fprintf(stderr, "Error opening %s\n", LOGGER_NAME);
        exit(4);
    }
    
    if ( (sem = init_sem(SEM_NAME)) == SEM_FAILED )
    {
        exit(5);
    }
    
    start = clock();
    
    int i;
    for (i = 0; i < NUM_CONTROLLERS; i++)
    {
        pthread_create(&threads[i], NULL, controlador, controller_name[i]);
    }
    
    sleep(tAbertura);
    
    /* Zona Critica */
    sem_wait(sem);
    
    notify_controllers(FINISH_STR);
    
    for (i = 0; i < NUM_CONTROLLERS; i++)
        pthread_join(threads[i], NULL);
    
    sem_post(sem);
    /***************/
    
    destroy_sem(sem, SEM_NAME);
    
    fclose(fp_logger);
    pthread_exit(0);
}
Example #5
0
File: main.c Project: Windeal/httpd
int main(int argc, char** argv)
{
	int sockfd, clientfd;
	struct client cli;
	FILE *logfile;
	struct sockaddr_in client_addr;
	socklen_t client_len;

	init_logger(LOG_FILE, logfile);
	Logger(LOG_INFO, 0, "httpd start...\n");

	httpd_get_option(argc, argv);
	httpd_process_option();

	init_httpd_socket(&sockfd);

	while (1)
	{
		client_len = sizeof (client_addr);
		clientfd = Accept(sockfd, (struct sockaddr*)&client_addr, &client_len);
		Logger(LOG_INFO, 0, "Accept a client connection\n");
		
		memset(&cli, 0, sizeof(struct client));
		cli.clientfd = clientfd;

		handle_request(&cli);

		close(clientfd);
		
	}

	close(sockfd);
	end_logger(logfile);
	return 0;
}
Example #6
0
int main(int argc, char *argv[])
{
	char *result;

	init_logger("dummy");
	result = process_cmnd_eventd("hb_config");
	printf("%s", result);
	return 0;
}
Example #7
0
int main(int argc, char *argv[]) {
    int s, s1; // Socket descriptors

    init_logger();
    init_thread_info();

    configuration_load(argc,argv);

    if (weborf_conf.is_inetd) inetd();

    print_start_disclaimer(argc,argv);

    s=net_create_server_socket();
    net_bind_and_listen(s);

    set_new_gid(weborf_conf.gid);
    set_new_uid(weborf_conf.uid);

    // init the queue for opened sockets
    if (q_init(&queue, MAXTHREAD + 1)!=0)
        exit(NOMEM);

    // Starts the 1st group of threads
    init_thread_attr();
    init_threads(INITIALTHREAD);
    init_thread_shaping();
    init_signals();

    // Infinite cycle, accept connections
    while (1) {
        s1=accept(s, NULL,NULL);

        if (s1 >= 0 && q_put(&queue, s1)!=0) { // Adds s1 to the queue
#ifdef REQUESTDBG
            syslog(LOG_ERR,"Not enough resources, dropping connection...");
#endif
            close(s1);
        }

        // Start new thread if needed
        if (thread_info.free <= LOWTHREAD && thread_info.free<MAXTHREAD) {
            // Need to start new thread
            if (thread_info.count + INITIALTHREAD < MAXTHREAD) {
                // Starts a group of threads
                init_threads(INITIALTHREAD);
            } else { // Can't start a group because the limit is close, starting less than a whole group
                init_threads(MAXTHREAD - thread_info.count);
            }
        }

    }
    return 0;

}
Example #8
0
/**
 * \brief Initializes the game.
 */
void tunnel::game::init()
{
  delete m_game;

  init_logger();

  claw::logger << claw::log_verbose << "Initializing game instance."
               << std::endl;

  init_game();
} // game::init()
Example #9
0
int main(int argc,  char *argv[])
{
	serverInputs inputs;
	struct sigaction sa;
    int sd;
	pid_t pid;
	logger * logg;
	/*Parse all Arguments*/
	memset(&inputs, 0, sizeof(serverInputs));

	parseArgs(&inputs, argc, argv);
	printf("Log File Path: %s\n", inputs.logPath);
	printf("Documents Path: %s\n", inputs.directory);
	logg = init_logger(inputs.logPath);

	sd = init_socket(&inputs);

	sa.sa_handler = kidhandler;
        sigemptyset(&sa.sa_mask);

        sa.sa_flags = SA_RESTART;
        if (sigaction(SIGCHLD, &sa, NULL) == -1)
                err(1, "sigaction failed");

    printf("Server up and  listening on port: %d\n", inputs.port);

    daemon(1,1);

	for(;;) {
		request req;
		memset(&req, 0, sizeof(req));
		req.l = logg;
		int clientsd = accept_connection(sd, &req.client);
		req.inputsDIR = inputs.directory;
		
		req.requestSD = &clientsd;

		pid = fork();
		if (pid == -1)
		     err(1, "fork failed");

		if(pid == 0) {
			handle_request(&req);
			exit(0);
		}
		close(clientsd);
	}
	
}
Example #10
0
/**
 * Main program entry point. Loop to see if restart is necessary
 * 
 * @return 0 upon successful exit
 */
int main(int argc, char **argv) {
    num_threads = NUM_RROBIN + NUM_FIFO;
    ops.sleep = 0;
    init_logger();

    /*initialize virtual shell*/
    vshell_pid = vshell_init();

    while (moses());

    kill(vshell_pid, SIGKILL);
    record("killed bash\n");


    return 0;

}
Example #11
0
int main(int argc, const char * argv[]) 
{
    try {
        init_logger();
        parse_options(argc, argv);
        Workflow workflow(options);
        workflow.run();
    }
    catch (const std::exception & ex) {
        std::cerr << "TealTree failed with exception:" << std::endl;
        std::cerr << ex.what() << std::endl;
        std::cerr.flush();
        destroy_logger();
        exit(1);
    }
    destroy_logger();
    return 0;
}
Example #12
0
int fs_quota_enable(){

        FILE *proc;
        char comm[200];
        int ret;
        int len = 0;
        ret = snprintf(comm, sizeof(comm), "/build/btrfs-progs/btrfs quota enable %s",backup_root);
	init_logger(CTX_FS);

        if ( len <= sizeof(comm)){
                proc = popen(comm, "r");
		pclose(proc);
		algolog(ALGO_INFO,"Filesystem quota enabled\n");
                printf("Filesystem quota enabled\n");
        }

        return ret;
}
Example #13
0
int
main(int argc, char **argv)
{
    int ret;
    ret = init_logger("./logtest", 0);
    if (ret) {
        printf("log initialization failed\n");
        return -1;
    }
    pthread_t tid;
    printf("creating child threads\n");
    pthread_create(&tid, NULL, logmsg, (void *)0);
    pthread_create(&tid, NULL, logmsg, (void *)1);
    pthread_create(&tid, NULL, logmsg, (void *)2);
    sleep(10);
    close_logger(3);
    
}
Example #14
0
int main(int argc, char *argv[])
{
	char *result = NULL;

	init_logger("tsa_cli");
	if ( argc < 2 ) {
		return 1;
	}

	if(cl_lock_pidfile(PID_FILE) < 0 ){
		exit(100);
	}

        init_mgmt_lib("tsa", ENABLE_LRM|ENABLE_CRM|ENABLE_HB|CACHE_CIB);
	result = process_command(argc, argv);
        final_mgmt_lib(); 
	if (result) {
		printf("%s\n", result);
	}
	return 0;
}
Example #15
0
File: lcs.c Project: morysky/lcs
int main(int argc, char *argv[]) {
    Logger* general_logger = malloc(sizeof(Logger));
    init_logger(general_logger, LOG_TYPE_FILE, "test.log");
    general_logger->warning(general_logger, "start", "");
    close_logger(general_logger);

    int ret = -1;
    // read conf
    // todo

    /* read opt */
    //todo

    init();

    int myerrno = 0;
    char* errmsg = (char *)malloc(1024);
    memset(errmsg, 0, 1024);
    
    create_server("8989", &myerrno, errmsg);
    return EXIT_SUCCESS;
}
Example #16
0
int
main(int argc, char **argv)
{
	int opts;

	init_logger();
	set_signal_handler();

	name = basename(argv[0]);
	opts = handle_args(argc, argv);

	argc -= opts;
	argv += opts;
	if (argc != 1) {
		ERR("too few/many arguments");
		usage();
		myabort();
	}

	run_cron(*argv);
	myexit(EXIT_SUCCESS);
	return (0);
}
Example #17
0
int main(int argc, char * argv[])
{
    /*variable declarations,
	remember, all v. decls. are at the beginning of each function in C*/
    int done = 0;
    const Uint8 * keys;
    
    int mx,my;
    float mf = 0;
	float guyFrame = 0;
	Sprite *thing;
	Sprite *thing2;
	Sprite *guyx;
	Sprite *galSprite;
	Sprite *mehSprite;
	int controllerConnected = 0;
	/*Sprite *myTileMap;
	const int level[] = 
	{ 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2, 
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3,
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3,
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2 };*/
	FILE *tilemapFile;
	int tileClicked = 0;
	int p = 0;

    Vector4D mouseColor = {100,255,255,200};
	Vector2D flipVert = { 0, 1 };
	Vector2D scaleDown = { 0.5, 0.5 };
	Vector2D scaleUp = { 2, 2 };
	Vector2D scaleHalfUp = { 1.5, 1.5 };
	//IntNode *myLL = IntNode_init(5);
	/*Student *person;*/
	/*Entity *guy, *testDude;
	Entity *en = NULL;
	Entity *biggo = NULL;
	FILE *infile;
	Entity *fileLoadedDude = NULL;
	Entity *fileLoadedDude2 = NULL;*/
	SDL_Event e;
	SDL_Surface *icon = SDL_LoadBMP("images/sprites/guy16x.bmp");

	FILE *bandFile;
	FILE *levelFile;

	Sound *NJITtheme = NULL;
	Sound *snareDrum = NULL;
	Sound *flute = NULL;
	Sound *trumpet = NULL;
	Sound *altoSax = NULL;
	Sound *tenorSax = NULL;
	Uint32 musicPlaying = 0;
	//Sound *clap = NULL;
	Sound *cdEject = NULL;

	/*TTF_Font *PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 24);
	if (!PencilFont)
	{
		slog("Error loading font");
	}
	SDL_Color colorBlack = { 255, 255, 255, 255 };
	SDL_Surface *surfaceMessage = TTF_RenderText_Solid(PencilFont, "placeholdha", colorBlack);
	SDL_Texture *message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer, surfaceMessage);
	Sprite *textBox;*/
	TTF_Font *PencilFont;
	SDL_Color colorBlack = { 0, 0, 0, 255 };
	SDL_Surface *surfaceMessage;
	SDL_Texture *message;
	Sprite *textBox;
	TextDisplay *nameText;
	int texW = 0, texH = 0;
	SDL_Rect rect = { 65, 630, 0, 0 };

	SDL_Surface *instrumentSurface;
	SDL_Texture *instrumentTexture;
	int instX = 0, instY = 0;
	SDL_Rect instrumentRect = { 65, 660, 0, 0 };

	Uint8 playButtonPressed = 0;

	srand(time(NULL));

    /*program initializtion*/
    init_logger("dmdwa.log");
    slog("---==== BEGIN ====---");
    gf2d_graphics_initialize(
        "Drum Majors Don't Wear Aussies",
        1200,
        720,
        1200,
        720,
        vector4d(0,0,0,255),
        0,
		icon);
	//SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0"); //This line makes images render crisp instead of blurry
    gf2d_graphics_set_frame_delay(16);
    gf2d_sprite_init(1024);
	entitySystemInit(1024);
	audioSystemInit(50, 10, 2, 0, 0, 0);
	soundSystemInit(25);
	text_system_init(50);
    SDL_ShowCursor(SDL_DISABLE);
	TTF_Init();
	//fileLoadedDude = entityNew();

	//derp
	//slog("%i", myLL->data);
    
    /*demo setup*/
    //backgroundSprite = gf2d_sprite_load_image("images/backgrounds/bg_flat.png");
	//textBox = gf2d_sprite_load_image("images/backgrounds/bg_flat.png");
    mouseSprite = gf2d_sprite_load_all("images/pointer.png",32,32,16);
	mouse = mouseSprite;
	//thing = gf2d_sprite_load_all("images/sprites/test_dude.png", 32, 32, 1);
	//thing2 = gf2d_sprite_load_all("images/sprites/test_dude3.png", 64, 64, 1);
	//guyx = gf2d_sprite_load_all("images/sprites/guy32x.png", 32, 32, 2);
	//galSprite = gf2d_sprite_load_all("images/sprites/gal32x.png", 32, 32, 2);
	//mehSprite = gf2d_sprite_load_all("images/sprites/meh32x.png", 32, 32, 2);
	//musicSheet = gf2d_sprite_load_image("images/gui/music_sheet.png");
	controllerIcon = gf2d_sprite_load_all("images/gui/controller64x.png", 64, 64, 1);
	//myTileMap = gf2d_sprite_load_all("images/field_tiles.png", 64, 64, 2);
	//person = student("Test", "Sex", thing2);
	//slog("Initializing student %s", person->name);
	/*guy = entityNew();
	strncpy(guy->name, "McBandgeek", 32);
	guy->mySprite = guyx;
	guy->scale = scaleUp;
	guy->currentFrame = 0;
	guy->minFrame = 0;
	guy->maxFrame = 2;
	guy->position = vector2d(300, 100);
	guy->update = move;
	guy->myInstrument = Instrument_Tenor_Saxophone;
	guy->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tenor_sax.png", 32, 32, 1);
	guy->boundingBox = rect_new(guy->position.x, guy->position.y, 64, 64);
	testDude = NULL;
	//SDL_SetTextureColorMod(thing2->texture, 100, 60, 0);
	infile = fopen("def/dude.dude", "r");
	fileLoadedDude = entityNew();
	fileLoadedDude = entityLoadFromFile(infile, fileLoadedDude);
	fclose(infile);
	//fileLoadedDude->mySprite = mehSprite;
	fileLoadedDude->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude->instrumentSpriteFilePath, 32, 32, 1);
	fileLoadedDude->position = vector2d(64, 64);
	fileLoadedDude->boundingBox = rect_new(fileLoadedDude->position.x, fileLoadedDude->position.y, 64, 64);
	fileLoadedDude->scale = vector2d(2, 2);
	fileLoadedDude->currentFrame = 0;
	fileLoadedDude->minFrame = 0;
	fileLoadedDude->maxFrame = 2;
	fileLoadedDude->currentPosition = 19;
	slog("the thing made has name: %s", &fileLoadedDude->name);

	infile = fopen("def/dude2.dude", "r");
	fileLoadedDude2 = entityNew();
	fileLoadedDude2 = entityLoadFromFile(infile, fileLoadedDude2);
	fclose(infile);
	fileLoadedDude2->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude2->instrumentSpriteFilePath, 32, 32, 1);
	fileLoadedDude2->position = vector2d(128, 64);
	fileLoadedDude2->boundingBox = rect_new(fileLoadedDude2->position.x, fileLoadedDude2->position.y, 64, 64);
	fileLoadedDude2->scale = vector2d(2, 2);
	fileLoadedDude2->currentFrame = 0;
	fileLoadedDude2->minFrame = 0;
	fileLoadedDude2->maxFrame = 2;
	fileLoadedDude2->currentPosition = 20;*/

	tile_map = tilemap_init();
	load_level("def/level/mainMenu.txt", 0);

	//textBox->texture = message;

	//Trying to load a tilemap from file
	//tilemapFile = fopen("def/level/field_0.tilemap", "r");
	//tilemap_load_from_file(tilemapFile, tile_map);
	//fclose(tilemapFile);
	//slog("tilewidth: (%i) tileheight: (%i) tperline: (%i) filepath: (...) width: (%i) height: (%i) xPos: (%i) yPos: (%i)", tile_map->tileWidth,	tile_map->tileHeight, tile_map->tilesPerLine, tile_map->width, tile_map->height, tile_map->xPos, tile_map->yPos);
	//slog("do i have a sprite? %i", tile_map->tilemapSprite != NULL);
	//tile_map->space[19] = 1;
	//tile_map->space[20] = 1;
	/*slog("tile pq start");
	while (tile_map->tiles_head != NULL)
	{
		p = pq_delete(tile_map->tiles_head, tile_map->tiles_tail);
		if (p == NULL)
		{
			break;
		}
		slog("Removing (%d) from pq", p);
	}
	slog("tile pq end");*/
	/*slog("start array");
	for (p = 0; p < tile_map->width * tile_map->height; p++)
	{
		if (p == 512)
		{
			slog("end of array");
		}
		else if (tile_map->tiles[p] == -1)
		{
			slog("found a -1");
		}
		else
		{
			slog("tiles at index (%i) is (%i)", p, tile_map->tiles[p]);
		}
	}
	slog("end array");*/

	//Trying to load all entities from a file
	//bandFile = fopen("def/_myBand.band", "r");
	//entityLoadAllFromFile(bandFile);
	//fclose(bandFile);

	//Load sounds
	//NJITtheme = soundNew("music/bg/NJIT.ogg");
	//NJITtheme = soundLoad("music/bg/NJIT.ogg", 12.0f, 3);
	//slog("do i have a sound? %i", NJITtheme->sound != NULL);
	//soundPlay(NJITtheme, 1, 0, 0, 0);
	//Mix_VolumeChunk(NJITtheme->sound, MIX_MAX_VOLUME); //Use this to change volume on the fly!
	//clap = soundLoad("music/sfx/clap.ogg", 5.0f, 1);
	cdEject = soundNew();
	cdEject = soundLoad("music/sfx/cd_play.ogg", 18.0f, 0);

	snareDrum = soundNew("music/bg/meeeeh-Snare_Drum.ogg");
	snareDrum = soundLoad("music/bg/meeeeh-Snare_Drum.ogg", 12.0f, Instrument_Snare_Drum);
	flute = soundNew("music/bg/meeeeh-Flute.ogg");
	flute = soundLoad("music/bg/meeeeh-Flute.ogg", 12.0f, Instrument_Flute);
	trumpet = soundNew("music/bg/meeeeh-Bb_Trumpet.ogg");
	trumpet = soundLoad("music/bg/meeeeh-Bb_Trumpet.ogg", 12.0f, Instrument_Trumpet);
	altoSax = soundNew("music/bg/meeeeh-Alto_Saxophone.ogg");
	altoSax = soundLoad("music/bg/meeeeh-Alto_Saxophone.ogg", 12.0f, Instrument_Alto_Saxophone);
	tenorSax = soundNew("music/bg/meeeeh-Tenor_Saxophone.ogg");
	tenorSax = soundLoad("music/bg/meeeeh-Tenor_Saxophone.ogg", 12.0f, Instrument_Tenor_Saxophone);

	//soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
	//soundPlay(flute, -1, 1, flute->defaultChannel, 0);
	//soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
	//soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
	//soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);

	//text testing stuff
	PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 36);
	if (!PencilFont)
	{
		slog("Error loading font");
	}
	surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack);
	message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
	SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
	rect.w = texW;
	rect.h = texH;
	nameText = text_new(PencilFont, "placeholda", colorBlack);
	//slog("nameText inuse (%i)", nameText->inUse);

	instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack);
	instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
	SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
	instrumentRect.w = instX;
	instrumentRect.h = instY;

	cd = entityNew();
	cd->mySprite = gf2d_sprite_load_all("images/gui/cd.png", 128, 128, 1);
	cd->position = vector2d(0, 0);
	cd->scale = vector2d(2, 2);
	cd->boundingBox = rect_new(cd->position.x, cd->position.y, 128, 128);

	playButton = entityNew();
	playButton->mySprite = gf2d_sprite_load_image("images/gui/play.png");
	playButton->position = vector2d(64, 256);
	strncpy(playButton->name, "playButton", MAX_CHARS);
	playButton->boundingBox = rect_new(playButton->position.x, playButton->position.y, playButton->mySprite->frame_w, playButton->mySprite->frame_h);
	

    /*main game loop*/
    while(!done)
    {
        SDL_PumpEvents();   // update SDL's internal event structures
        keys = SDL_GetKeyboardState(NULL); // get the keyboard state for this frame
        /*update things here*/
        SDL_GetMouseState(&mx,&my);
		SDL_PollEvent(&e);
        mf+=0.1;
        if (mf >= 16.0)mf = 0;        
		guyFrame += 0.05;
		if (guyFrame >= 2.0)guyFrame = 0;
        
        gf2d_graphics_clear_screen();// clears drawing buffers
        // all drawing should happen betweem clear_screen and next_frame
		//backgrounds drawn first
		if (backgroundSprite)
		{
			gf2d_sprite_draw_image(backgroundSprite, vector2d(0, 0));
		}

		//Me! trying to add a sprite
		/*tilemap_draw(
			myTileMap,
			level,
			18,
			10,
			0,
			0);*/
		if (tile_map)
		{
			tilemap_draw_from_data(tile_map);
		}

		//gf2d_sprite_draw(thing, vector2d(100, 10), &scaleUp, NULL, NULL, NULL, NULL, 0);
		//gf2d_sprite_draw(thing, vector2d(100, 10), NULL, NULL, NULL, NULL, NULL, 0);
		//gf2d_sprite_draw(guy->mySprite, guy->position, &(guy->scale), NULL, NULL, NULL, NULL, 0);

		/*if (keys[SDL_SCANCODE_W])
		{
			(*guy->update)(guy, vector2d(0, -2));
		}
		if (keys[SDL_SCANCODE_A])
		{
			(*guy->update)(guy, vector2d(-2, 0));
		}
		if (keys[SDL_SCANCODE_S])
		{
			(*guy->update)(guy, vector2d(0, 2));
		}
		if (keys[SDL_SCANCODE_D])
		{
			(*guy->update)(guy, vector2d(2, 0));
		}*/
		//guy->currentFrame = guyFrame;
		//fileLoadedDude->currentFrame = guyFrame;

		/*
		//create an entity if it doesn't exist
		if (keys[SDL_SCANCODE_O] && testDude == NULL)
		{
			testDude = entityNew();
			testDude->mySprite = thing;
			testDude->position = vector2d(500, 500);
			testDude->update = move;
		}
		//if it exists, call its update function
		//slog("%i", testDude != NULL);
		if (testDude != NULL)
		{
			//(*testDude->update)(testDude, vector2d(1, 1));
			gf2d_sprite_draw(testDude->mySprite, testDude->position, NULL, NULL, NULL, NULL, NULL, 0);
		}
		//delete it from memory
		if (keys[SDL_SCANCODE_P] && testDude != NULL)
		{
			entityDelete(testDude);
		}*/
		/*if (keys[SDL_SCANCODE_L] && biggo == NULL)
		{
			biggo = entityNew();
			biggo->mySprite = guyx;
			biggo->position = vector2d(10, 10);
			biggo->scale = vector2d(25, 25);
			biggo->inUse = 1;
			biggo->currentFrame = 0;
			biggo->minFrame = 0;
			biggo->maxFrame = 2;
			biggo->update = move;
			biggo->velocity = vector2d(0.5f, 0.5f);
			biggo->acceleration = vector2d(0.5f, 0.5f);
			biggo->myInstrument = Instrument_Flute;
			biggo->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_flute.png", 32, 32, 1);
		}
		if (biggo != NULL)
		{
			//entityDraw(biggo);
			(*biggo->update)(biggo, vector2d(0.5f, 0.5f));
			//biggo->currentFrame = guyFrame;
		}
		if (biggo != NULL && biggo->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			biggo->inUse = 0;
			entityDelete(biggo);
			biggo = NULL;
		}
		if (keys[SDL_SCANCODE_O] && testDude == NULL)
		{
			//slog("Let's make a new thing!");
			testDude = entityNew();
			testDude->mySprite = mehSprite;
			testDude->position = vector2d(200, 200);
			testDude->scale = scaleUp;
			testDude->inUse = 1;
			testDude->currentFrame = 0;
			testDude->minFrame = 1;
			testDude->maxFrame = 3;
			testDude->update = move;
			testDude->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tuba.png", 32, 32, 1);
		}
		if (testDude != NULL)
		{
			//gf2d_sprite_draw(testDude->mySprite, testDude->position, &(testDude->scale), NULL, NULL, NULL, NULL, 0);
			//entityDraw(testDude);
			(*testDude->update)(testDude, vector2d(1, 1));
			//testDude->currentFrame = guyFrame;
		}
		if (testDude != NULL && testDude->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			testDude->inUse = 0;
			entityDelete(testDude);
			testDude = NULL;
		}
		if (keys[SDL_SCANCODE_M] && en == NULL)
		{
			en = entityNew();
			en->mySprite = galSprite;
			en->position = vector2d(300, 500);
			en->scale = vector2d(1,1);
			en->inUse = 1;
			en->currentFrame = 0;
			en->minFrame = 0;
			en->maxFrame = 4;
			en->update = move;
			en->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_clarinet.png", 32, 32, 1);
			//soundPlay(clap, 0, clap->volume, clap->defaultChannel, 0);
		}
		if (en != NULL && en->inUse == 1)
		{
			//entityDraw(en);
			(*en->update)(en, vector2d(1, -1));
			//en->currentFrame = guyFrame;
		}
		if (en != NULL && en->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			en->inUse = 0;
			entityDelete(en);
			en = NULL;
		}
		if (en != NULL && en->inUse == 1 && en->position.x >= 400)
		{
			en->inUse = 0;
			entityDelete(en);
			en = NULL;
		}*/

		/*gf2d_sprite_draw(
			guyx,
			vector2d(64, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);
		gf2d_sprite_draw(
			galSprite,
			vector2d(128, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);
		gf2d_sprite_draw(
			mehSprite,
			vector2d(192, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);*/

		//entityDraw(fileLoadedDude);

		entityDrawAll();
		entityUpdateAll();
		entityIncrementCurrentFrameAll();

		if (pickedUp != NULL)
		{
			draw_line(vector2d(pickedUp->position.x + pickedUp->mySprite->frame_w, pickedUp->position.y + pickedUp->mySprite->frame_h),
						vector2d(mx, my), COLOR_RED);
		}

		switch (e.type)
		{
		case SDL_QUIT:
			done = 1;
			break;
		case SDL_MOUSEBUTTONDOWN:
			if (e.button.button == SDL_BUTTON_RIGHT)
			{
				tileClicked = tilemap_find_tile(mx, my, tile_map);
				if (tileClicked >= 0 && pickedUp != NULL)
				{
					if (tile_map->space[tileClicked] == 0)
					{
						slog("poop");
						tile_map->space[pickedUp->currentPosition] = 0;
						tile_map->space[tileClicked] = 1;
						pickedUp->currentPosition = tileClicked;
						mouse = mouseSprite;
						pickedUp->position.x = (mx - tile_map->xPos) / tile_map->tileWidth * (tile_map->tileWidth);
						pickedUp->position.y = (my - tile_map->yPos) / tile_map->tileHeight * (tile_map->tileHeight);
						pickedUp = NULL;
						surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack);
						message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
						SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
						rect.w = texW;
						rect.h = texH;

						instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack);
						instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
						SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
						instrumentRect.w = instX;
						instrumentRect.h = instY;
					}
				}
			}
			else if (e.button.button == SDL_BUTTON_LEFT)
			{
				if (playButton != NULL)
				{
					if (point_in_rect(mx, my, playButton->boundingBox))
					{
						//slog("hit da BUTT");
						playButtonPressed = 1;
						soundPlay(cdEject, 0, 5.0f, -1, 0);
					}
				}
			}
			break;
		case SDL_MOUSEBUTTONUP:
			if (e.button.button == SDL_BUTTON_LEFT)
			//if (mousePress(&e.button))
			{
				/*if (point_in_rect(mx, my, guy->boundingBox))
				{
					slog("collision with guy (%s)", guy->name);
				}
				if (point_in_rect(mx, my, fileLoadedDude->boundingBox))
				{
					slog("collision with guy (%s)", &fileLoadedDude->name);
					if (pickedUp == NULL)
					{
						pickedUp = fileLoadedDude;
						mouse = fileLoadedDude->mySprite;
					}
				}
				if (point_in_rect(mx, my, fileLoadedDude2->boundingBox))
				{
					slog("collision with guy (%s)", &fileLoadedDude2->name);
					if (pickedUp == NULL)
					{
						pickedUp = fileLoadedDude2;
						mouse = fileLoadedDude2->mySprite;
					}
				}*/

				collision = entityCheckCollisionInAll(mx, my);
				if (collision != NULL && collision->myInstrument != Instrument_Unassigned)
				{
					slog("collision with guy (%s)", &collision->name);
					if (pickedUp == NULL)
					{
						pickedUp = collision;
						mouse = collision->mySprite;
						surfaceMessage = TTF_RenderText_Solid(PencilFont, &pickedUp->name, colorBlack);
						message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
						SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
						rect.w = texW;
						rect.h = texH;

						instrumentSurface = TTF_RenderText_Solid(PencilFont, entityGetInstrumentName(pickedUp), colorBlack);
						instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
						SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
						instrumentRect.w = instX;
						instrumentRect.h = instY;
					}
				}

				//if (point_in_rect(mx, my, tile_map->boundingBox))
				tileClicked = tilemap_find_tile(mx, my, tile_map);
				if (tileClicked >= 0)
				{
					//slog("collided with tilemap on tile (%i), occupied (%i)", tileClicked, tile_map->space[tileClicked]);
				}
			}
			break;
		case SDL_CONTROLLERDEVICEADDED:
			slog("Connected a controller");
			controllerConnected = 1;
			break;
		case SDL_CONTROLLERDEVICEREMOVED:
			slog("Removed a controller");
			controllerConnected = 0;
			break;
		}

		if (playButtonPressed && cd != NULL)
		{
			cd->position.x += 5;
		}

		if (cd != NULL)
		{
			if (point_in_rect(1000, 10, cd->boundingBox))
			{
				load_level("def/level/myLevel.txt", 1);
				if (musicPlaying > 0)
				{
					//Mix_RewindMusic();
					Mix_HaltChannel(-1);
				}
				soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
				soundPlay(flute, -1, 1, flute->defaultChannel, 0);
				soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
				soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
				soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);
				musicPlaying = 1;
			}
		}
		//slog("ds %i %i %i %i", cd->boundingBox->x, cd->boundingBox->y, cd->boundingBox->w, cd->boundingBox->h);

		//UI elements last
		if (musicSheet)
			gf2d_sprite_draw(musicSheet, vector2d(0, 592), &scaleUp, NULL, NULL, NULL, NULL, 0);
		if (gui)
			gf2d_sprite_draw(gui, vector2d(0, 0), &scaleUp, NULL, NULL, NULL, NULL, 0);
		//text_draw_all();
		//text_draw(nameText);
		if (message && musicSheet)
		{
			SDL_RenderCopy(gf2d_graphics_get_renderer(), message, NULL, &rect);
			SDL_RenderCopy(gf2d_graphics_get_renderer(), instrumentTexture, NULL, &instrumentRect);
		}
		//SDL_RenderPresent(renderer);
		//gf2d_sprite_draw_image(textBox, vector2d(50, 50));
		if (controllerConnected && controllerIcon)
			gf2d_sprite_draw(controllerIcon, vector2d(700, 600), &scaleUp, NULL, NULL, NULL, NULL, 0);
		if (pickedUp == NULL)
		{
			gf2d_sprite_draw(
				mouse,				//Sprite to load
				vector2d(mx, my),	//Position to draw it at
				NULL,				//If you want to scale the sprite
				NULL,				//Scale the sprite from a certain position
				NULL,				//Rotation
				NULL,				//Flip
				&mouseColor,		//Color shift
				(int)mf);			//Which frame to draw at
		}
		else
		{
			gf2d_sprite_draw(
				mouse,				//Sprite to load
				vector2d(mx, my),	//Position to draw it at
				&scaleHalfUp,		//If you want to scale the sprite
				NULL,				//Scale the sprite from a certain position
				NULL,				//Rotation
				NULL,				//Flip
				&mouseColor,		//Color shift
				0);			//Which frame to draw at
		}
		gf2d_grahics_next_frame();// render current draw frame and skip to the next frame
        
		if (keys[SDL_SCANCODE_Q])
		{
			//close_level(tile_map);
			load_level("def/level/myLevel.txt", 1);
			if (musicPlaying > 0)
			{
				//Mix_RewindMusic();
				Mix_HaltChannel(-1);
			}
			soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
			soundPlay(flute, -1, 1, flute->defaultChannel, 0);
			soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
			soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
			soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);
			musicPlaying = 1;
		}

        if (keys[SDL_SCANCODE_ESCAPE])done = 1; // exit condition
        //slog("Rendering at %f FPS",gf2d_graphics_get_frames_per_second());
    }
    slog("---==== END ====---");
	TTF_Quit();
	SDL_DestroyTexture(message);
	SDL_FreeSurface(surfaceMessage);
    return 0;
}
Example #18
0
void StockManager::init(
        const Parameter& baseInfoParam,
        const Parameter& blockParam,
        const Parameter& kdataParam,
        const Parameter& preloadParam,
        const Parameter& hikyuuParam) {

    m_baseInfoDriverParam = baseInfoParam;
    m_blockDriverParam = blockParam;
    m_kdataDriverParam = kdataParam;
    m_preloadParam = preloadParam;
    m_hikyuuParam = hikyuuParam;

    //获取临时路径信息
    try {
        m_tmpdir = hikyuuParam.get<string>("tmpdir");
    } catch (...) {
        m_tmpdir = "";
    }

    try {
        m_datadir = hikyuuParam.get<string>("datadir");
    } catch (...) {
        m_datadir = "";
    }

    //获取log配置文件信息
    init_logger("");
    
    m_stockDict.clear();
    m_marketInfoDict.clear();
    m_stockTypeInfo.clear();

    string funcname(" [StockManager::init]");

    //初始化注册默认支持的数据驱动
    DataDriverFactory::regBaseInfoDriver(make_shared<SQLiteBaseInfoDriver>());

    DataDriverFactory::regBaseInfoDriver(make_shared<MySQLBaseInfoDriver>());

    DataDriverFactory::regBlockDriver(make_shared<QLBlockInfoDriver>());
    DataDriverFactory::regKDataDriver(make_shared<TdxKDataDriver>());
    DataDriverFactory::regKDataDriver(make_shared<H5KDataDriver>());
    DataDriverFactory::regKDataDriver(make_shared<MySQLKDataDriver>());

    //加载证券基本信息
    BaseInfoDriverPtr base_info = DataDriverFactory::getBaseInfoDriver(baseInfoParam);
    base_info->loadBaseInfo();

    //获取板块驱动
    m_blockDriver = DataDriverFactory::getBlockDriver(blockParam);

    //获取K线数据驱动并预加载指定的数据
    HKU_INFO("Loading KData...");
    std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();

    KDataDriverPtr kdata_driver = DataDriverFactory::getKDataDriver(kdataParam);

    setKDataDriver(kdata_driver);

    //add special Market, for temp csv file
    m_marketInfoDict["TMP"] = MarketInfo("TMP", "Temp Csv file",
                                         "temp load from csv file",
                                         "000001", Null<Datetime>());

    std::chrono::duration<double> sec = std::chrono::system_clock::now() - start_time;
    HKU_INFO(sec.count() << "s Loaded Data.");
}
Example #19
0
int main() {
	int res, try, retries;
	char *query_string, *abf_api_url, *api_token;

	char *log_level = getenv("LOG_LEVEL");
	if (init_logger(log_level == NULL ? "INFO" : log_level) < 0) {
		return 2;
	}
	register_thread("Main");

	log_printf(LOG_INFO, "Starting DNS check...\n");
	res = check_dns();
	if (res < 0) {
		log_printf(LOG_FATAL, "Check DNS failed, can't resolve github.com. Exiting...\n");
		return 6;
	} else {
		log_printf(LOG_INFO, "Successfuly resolved github. Continuing.\n");
	}

	usergroup omv_mock = get_omv_uid_mock_gid();
	if(omv_mock.omv_uid == 0) {
		log_printf(LOG_FATAL, "User omv doesn't exist. Exiting...\n");
		return 7;
	}
	if(omv_mock.mock_gid == 0) {
		log_printf(LOG_FATAL, "Group mock doesn't exist. Exiting...\n");
		return 8;
	}

	res = process_config(&abf_api_url, &api_token, &query_string);
	if (res < 0) {
		log_printf(LOG_FATAL, "Failed to process config, exiting.\n");
		return 1;
	}

	init_strings(api_token);

	init_api(abf_api_url, api_token);

	if(start_statistics_thread(query_string)) {
		log_printf(LOG_FATAL, "Failed to initialize statistics thread. Exiting...\n");
		return 5;
	}

	while(1) {
		char *job;
		if(api_jobs_shift(&job, query_string)) {
			sleep(10);
			continue;
		}

		char *build_id, *distrib_type;
		char **env;
		int ttl;

		res = parse_job_description(job, &build_id, &ttl, &distrib_type, &env);
		free(job);
		if(res < 0) {
			sleep(10);
			continue;
		}

		log_printf(LOG_INFO, "Starting build with build_id %s.\n", build_id);
		log_printf(LOG_INFO, "Sending build start notification to ABF.\n");
		retries = 5;
		try = 0;
		set_busy_status(1, build_id);
		int build_start_success = 0;
		while(retries) {
			log_printf(LOG_INFO, "Try #%d: Sending data to ABF.\n", try + 1);
			if(!api_jobs_feedback(build_id, BUILD_STARTED, hostname_payload)) {
				log_printf(LOG_INFO, "Try #%d: Data sent.\n", try + 1);
				build_start_success = 1;
				break;
			} else {
				log_printf(LOG_ERROR, "Try #%d: Failed to send data to ABF. Sleeping for %d seconds and retrying...\n", try + 1, 1 << try);
			}
			retries--;
			sleep(1 << try);
			try++;
		}

		if (!build_start_success) {
			log_printf(LOG_ERROR, "Failed to send build start to ABF, aborting build.\n");
			free(build_id);
			free(distrib_type);
			for(int i = 0; i < res; i++) {
				free(env[i]);
			}
			free(env);
			set_busy_status(0, NULL);
			continue;
		}

		child script = exec_build(distrib_type, (char * const *)env, omv_mock);

		int live_inspector_started = 1;
		log_printf(LOG_INFO, "Starting live inspector, build's time to live is %d seconds.\n", ttl);
		if(start_live_inspector(ttl, script.pid, build_id) < 0) {
			live_inspector_started = 0;
			log_printf(LOG_WARN, "Live inspector failed to start. Job canceling and timeout will be unavailable.\n");
		}

		int live_logger_started = 1;
		log_printf(LOG_INFO, "Starting live logger.\n");
		if(start_live_logger(build_id, script.read_fd) < 0) {
			live_logger_started = 0;
			log_printf(LOG_WARN, "Live logger failed to start. Live log will be unavailable.\n");
		}

		int status, build_status = BUILD_COMPLETED;
		waitpid(script.pid, &status, 0);
		int canceled = 0;
		if (live_inspector_started) {
			canceled = stop_live_inspector();
		}
		if (live_logger_started) {
			stop_live_logger();
		}

		int exit_code = 0;
		if (canceled) {
			build_status = BUILD_CANCELED;
		}
		else if(WIFEXITED(status)) {
			exit_code = WEXITSTATUS(status);
			switch(exit_code) {
				case 0:
					build_status = BUILD_COMPLETED;
					break;
				case 5:
					build_status = TESTS_FAILED;
					break;
				default:
					build_status = BUILD_FAILED;
			}
		}
		else if(WIFSIGNALED(status)) {
			exit_code = 255;
			build_status = BUILD_FAILED;
		}

		for(int i = 0; i < res; i++) {
			free(env[i]);
		}
		free(env);
		free(distrib_type);

		log_printf(LOG_INFO, "Build is over with status %s.\n", build_statuses_str[build_status]);

		mkdir(home_output, 0666);
		system(move_output_cmd);


		system(upload_cmd);

		char *container_data = read_file(container_data_path);
		char *results = read_file("/tmp/results.json");
		char *commit_hash = read_file(commit_hash_path);
		if(commit_hash != NULL) {
			commit_hash[40] = '\0';
		}

		char *fail_reason = NULL;
		if (build_status == BUILD_FAILED) {
			fail_reason = read_file(fail_reason_path);
			if (fail_reason != NULL) {
				for (unsigned int i = 0; i < strlen(fail_reason); i++) {
					if (!isprint(fail_reason[i]) || fail_reason[i] == '"') {
						fail_reason[i] = ' ';
					}
				}
			}
		}

		char *args = xmalloc((container_data ? strlen(container_data) : 0) + (results ? strlen(results) : 0) + 2048);
		sprintf(args, build_completed_args_fmt, (results ? results : "[]"), \
				(container_data ? container_data : "{}"), exit_code, (commit_hash ? commit_hash : ""),
				(fail_reason ? fail_reason : ""));

		retries = 5;
		try = 0;
		while(retries) {
			log_printf(LOG_INFO, "Try #%d: Sending data to ABF\n", try + 1);
			if(!api_jobs_feedback(build_id, build_status, args)) {
				log_printf(LOG_INFO, "Data sent.\n");
				break;
			} else {
				log_printf(LOG_ERROR, "Failed to send data to ABF. Sleeping for %d seconds and retrying...\n", 1 << try);
			}
			retries--;
			sleep(1 << try);
			try++;
		}

		set_busy_status(0, NULL);
		free(args);
		free(build_id);

		if(commit_hash) {
			free(commit_hash);
		}
		if(results) {
			free(results);
		}
		if(container_data) {
			free(container_data);
		}
		if(fail_reason) {
			free(fail_reason);
		}
	}

	return 0;
}
Example #20
0
 logger_initialized()   {
     init_logger();
 }
Example #21
0
/*
 * main application method
 */
int main( int argc, char** argv )
{
	// catch process signals
	ibrcommon::SignalHandler sighandler(sighandler_func);
	sighandler.handle(SIGINT);
	sighandler.handle(SIGTERM);
#ifndef __WIN32__
	sighandler.handle(SIGUSR1);
#endif

	// configration object
	config_t conf;

	// read the configuration
	read_configuration(argc, argv, conf);

	init_logger(conf);

	// initialize sighandler after possible exit call
	sighandler.initialize();

	// init working directory
	if (conf.workdir.length() > 0)
	{
		ibrcommon::File blob_path(conf.workdir);

		if (blob_path.exists())
		{
			ibrcommon::BLOB::changeProvider(new ibrcommon::FileBLOBProvider(blob_path), true);
		}
	}

	// backoff for reconnect
	unsigned int backoff = 2;

	ibrcommon::File outbox_file(conf.outbox);

	// create new file lists
	fileset new_files, prev_files, deleted_files, files_to_send;
	filelist observed_files;
	hashlist sent_hashes;

	// observed root file
	io::ObservedFile root(ibrcommon::File("/"));

#ifdef HAVE_LIBTFFS
	io::FatImageReader *imagereader = NULL;
#endif

	if (outbox_file.exists() && !outbox_file.isDirectory())
	{
#ifdef HAVE_LIBTFFS
		conf.fat = true;
		imagereader = new io::FatImageReader(conf.outbox);
		const io::FATFile fat_root(*imagereader, conf.path);
		root = io::ObservedFile(fat_root);
#else
		IBRCOMMON_LOGGER_TAG(TAG,error) << "ERROR: image-file provided, but this tool has been compiled without libtffs support!" << IBRCOMMON_LOGGER_ENDL;
		return -1;
#endif
	}
	else
	{
		if (!outbox_file.exists()) {
			ibrcommon::File::createDirectory(outbox_file);
		}
		root = io::ObservedFile(outbox_file);
	}

	IBRCOMMON_LOGGER_TAG(TAG,info) << "-- dtnoutbox --" << IBRCOMMON_LOGGER_ENDL;

	// loop, if no stop if requested
	while (_running)
	{
		try
		{
			// Create a stream to the server using TCP.
			ibrcommon::vaddress addr("localhost", 4550);
			ibrcommon::socketstream conn(new ibrcommon::tcpsocket(addr));

			// Initiate a client for synchronous receiving
			dtn::api::Client client(conf.name, conn, dtn::api::Client::MODE_SENDONLY);

			// Connect to the server. Actually, this function initiate the
			// stream protocol by starting the thread and sending the contact header.
			client.connect();

			// reset backoff if connected
			backoff = 2;

			// check the connection
			while (_running)
			{
				// get all files
				fileset current_files;
				root.findFiles(current_files);

				// determine deleted files
				fileset deleted_files;
				std::set_difference(prev_files.begin(), prev_files.end(), current_files.begin(), current_files.end(), std::inserter(deleted_files, deleted_files.begin()));

				// remove deleted files from observation
				for (fileset::const_iterator iter = deleted_files.begin(); iter != deleted_files.end(); ++iter)
				{
					const io::ObservedFile &deletedFile = (*iter);

					// remove references in the sent_hashes
					for (hashlist::iterator hash_it = sent_hashes.begin(); hash_it != sent_hashes.end(); /* blank */) {
						if ((*hash_it).getPath() == deletedFile.getFile().getPath()) {
							sent_hashes.erase(hash_it++);
						} else {
							++hash_it;
						}
					}

					// remove from observed files
					observed_files.remove(deletedFile);

					// output
					IBRCOMMON_LOGGER_TAG(TAG,info) << "file removed: " << deletedFile.getFile().getBasename() << IBRCOMMON_LOGGER_ENDL;
				}

				// determine new files
				fileset new_files;
				std::set_difference(current_files.begin(), current_files.end(), prev_files.begin(), prev_files.end(), std::inserter(new_files, new_files.begin()));

				// add new files to observation
				for (fileset::const_iterator iter = new_files.begin(); iter != new_files.end(); ++iter)
				{
					const io::ObservedFile &of = (*iter);

					int reg_ret = regexec(&conf.regex, of.getFile().getBasename().c_str(), 0, NULL, 0);
					if (!reg_ret && !conf.invert)
						continue;
					if (reg_ret && conf.invert)
						continue;

					// print error message, if regex error occurs
					if (reg_ret && reg_ret != REG_NOMATCH)
					{
							char msgbuf[100];
							regerror(reg_ret,&conf.regex,msgbuf,sizeof(msgbuf));
							IBRCOMMON_LOGGER_TAG(TAG,info) << "ERROR: regex match failed : " << std::string(msgbuf) << IBRCOMMON_LOGGER_ENDL;
					}

					// add new file to the observed set
					observed_files.push_back(of);

					// log output
					IBRCOMMON_LOGGER_TAG(TAG, info) << "file found: " << of.getFile().getBasename() << IBRCOMMON_LOGGER_ENDL;
				}

				// store current files for the next round
				prev_files.clear();
				prev_files.insert(current_files.begin(), current_files.end());

				IBRCOMMON_LOGGER_TAG(TAG, notice)
						<< "file statistics: "
						<< observed_files.size() << " observed, "
						<< deleted_files.size() << " deleted, "
						<< new_files.size() << " new"
						<< IBRCOMMON_LOGGER_ENDL;

				// find files to send, create std::list
				files_to_send.clear();


				IBRCOMMON_LOGGER_TAG(TAG, notice) << "updating observed files:" << IBRCOMMON_LOGGER_ENDL;
				for (filelist::iterator iter = observed_files.begin(); iter != observed_files.end(); ++iter)
				{
					io::ObservedFile &of = (*iter);

					// tick and update all files
					of.update();

					if (of.getStableCounter() > conf.rounds)
					{
						if (sent_hashes.find(of.getHash()) == sent_hashes.end())
						{
							sent_hashes.insert(of.getHash());
							files_to_send.insert(*iter);
						}
					}

					IBRCOMMON_LOGGER_TAG(TAG, notice)
						<< "\t"
						<< of.getFile().getBasename() << ": "
						<< of.getStableCounter()
						<< IBRCOMMON_LOGGER_ENDL;
				}

				if (!files_to_send.empty())
				{
					std::stringstream ss;
					for (fileset::const_iterator it = files_to_send.begin(); it != files_to_send.end(); ++it) {
						ss << (*it).getFile().getBasename() << " ";
					}
					IBRCOMMON_LOGGER_TAG("dtnoutbox",info) << "files sent: " << ss.str() << IBRCOMMON_LOGGER_ENDL;

					try {
						// create a blob
						ibrcommon::BLOB::Reference blob = ibrcommon::BLOB::create();

						// write files into BLOB while it is locked
						{
							ibrcommon::BLOB::iostream stream = blob.iostream();
							io::TarUtils::write(*stream, root, files_to_send);
						}

						// create a new bundle
						dtn::data::EID destination = EID(conf.destination);

						// create a new bundle
						dtn::data::Bundle b;

						// set destination
						b.destination = destination;

						// add payload block using the blob
						b.push_back(blob);

						// set destination address to non-singleton, if configured
						if (conf.bundle_group)
							b.set(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON, false);

						// send the bundle
						client << b;
						client.flush();
					} catch (const ibrcommon::IOException &e) {
						IBRCOMMON_LOGGER_TAG(TAG,error) << "send failed: " << e.what() << IBRCOMMON_LOGGER_ENDL;
					}
				}

				// wait defined seconds
				ibrcommon::MutexLock l(_wait_cond);
				IBRCOMMON_LOGGER_TAG(TAG, notice) << conf.interval <<" ms wait" << IBRCOMMON_LOGGER_ENDL;
				while (!_wait_abort && _running) {
					_wait_cond.wait(conf.interval);
				}
				_wait_abort = false;
			}

			// clean up regex
			regfree(&conf.regex);

			// close the client connection
			client.close();

			// close the connection
			conn.close();

		}
		catch (const ibrcommon::socket_exception&)
		{
			if (_running)
			{
				IBRCOMMON_LOGGER_TAG(TAG,error) << "Connection to bundle daemon failed. Retry in " << backoff << " seconds." << IBRCOMMON_LOGGER_ENDL;
				ibrcommon::Thread::sleep(backoff * 1000);

				// if backoff < 10 minutes
				if (backoff < 600)
				{
					// set a new backoff
					backoff = backoff * 2;
				}
			}
		}
		catch (const ibrcommon::IOException&)
		{
			if (_running)
			{
				IBRCOMMON_LOGGER_TAG(TAG,error) << "Connection to bundle daemon failed. Retry in " << backoff << " seconds." << IBRCOMMON_LOGGER_ENDL;
				ibrcommon::Thread::sleep(backoff * 1000);

				// if backoff < 10 minutes
				if (backoff < 600)
				{
					// set a new backoff
					backoff = backoff * 2;
				}
			}
		}
		catch (const std::exception&) { };
	}

	// clear observed files
	observed_files.clear();

#ifdef HAVE_LIBTFFS
	// clean-up
	if (imagereader != NULL) delete imagereader;
#endif

	return (EXIT_SUCCESS);
}
Example #22
0
int main(int argc, char *argv[])
{
    int i;
    float r = 0;
    Space *space;
    Entity *cube1,*cube2;
    char bGameLoopRunning = 1;
    Vec3D cameraPosition = {-10,3,0};
    Vec3D cameraRotation = {180,0,180};
    SDL_Event e;
    Obj *bgobj;
    Sprite *bgtext;

	//my variables
	Ship *playerShip;
	int specMode;
    
    init_logger("gametest3d.log");
    if (graphics3d_init(1024,768,1,"gametest3d",33) != 0)
    {
        return -1;
    }
    model_init();
    obj_init();
    entity_init(255);
	initShips();
    
    bgobj = obj_load("models/mountainvillage.obj");
    bgtext = LoadSprite("models/mountain_text.png",1024,1024);
    
    //cube1 = newCube(vec3d(0,0,0),"Cubert");
    //cube2 = newCube(vec3d(10,0,0),"Hobbes");
    
    //cube1->body.velocity.x = 0.1;
    
    space = space_new();
    space_set_steps(space,100);
    
    space_add_body(space,&cube1->body);
    space_add_body(space,&cube2->body);

	//my variables
	specMode = 0;
	numShips = 0;
	shipVel = 0;
	shipRot = 0;
	turretRot = 0;
	gunElev = 0;
	realTurrRot = 0;

	playerShip = spawnShip(space, vec3d(-10,0,0), 1);

    while (bGameLoopRunning)
    {
		updateAllShipPos();
		for (i = 0; i < 100;i++)
        {
			space_do_step(space);
        }
		updateAllShipComp();
		applyGrav();
		if(specMode == 0)
		{
			cameraPosition.x = playerShip->hull->body.position.x;
			cameraPosition.y = (playerShip->hull->body.position.y + 5);
			cameraPosition.z = playerShip->hull->body.position.z;
		}

        while ( SDL_PollEvent(&e) ) 
        {
            if (e.type == SDL_QUIT)
            {
                bGameLoopRunning = 0;
            }
            else if (e.type == SDL_KEYDOWN)
            {
                if (e.key.keysym.sym == SDLK_ESCAPE)
                {
                    bGameLoopRunning = 0;
                }
                else if (e.key.keysym.sym == SDLK_SPACE)
                {
                    cameraPosition.z++;
                }
                else if (e.key.keysym.sym == SDLK_z)
                {
                    cameraPosition.z--;
                }
                else if (e.key.keysym.sym == SDLK_w)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            -sin(cameraRotation.z * DEGTORAD),
                            cos(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_s)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            sin(cameraRotation.z * DEGTORAD),
                            -cos(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_d)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            cos(cameraRotation.z * DEGTORAD),
                            sin(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_a)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            -cos(cameraRotation.z * DEGTORAD),
                            -sin(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_LEFT)
                {
                    cameraRotation.y -= 1;
                }
                else if (e.key.keysym.sym == SDLK_RIGHT)
                {
                    cameraRotation.y += 1;
                }
                else if (e.key.keysym.sym == SDLK_UP)
                {
                    cameraRotation.x += 1;
                }
                else if (e.key.keysym.sym == SDLK_DOWN)
                {
                    cameraRotation.x -= 1;
                }
				

				
				else if (e.key.keysym.sym == SDLK_y && shipVel < 0.4)
                {
                    shipVel += 0.1;
                }
				else if (e.key.keysym.sym == SDLK_h && shipVel > 0.05)
                {
                    shipVel -= 0.1;
                }
				else if (e.key.keysym.sym == SDLK_j)
                {
                    shipRot += 0.5;
					if(shipRot >= 360){shipRot -= 360;}
                }
				else if (e.key.keysym.sym == SDLK_g)
                {
                    shipRot -= 0.5;
					if(shipRot < 0){shipRot += 360;}
                }
				else if (e.key.keysym.sym == SDLK_m && turretRot < 135)
                {
                    turretRot += 1;
                }
				else if (e.key.keysym.sym == SDLK_b && turretRot > -135)
                {
                    turretRot -= 1;
                }
				else if (e.key.keysym.sym == SDLK_o && gunElev < 50)
                {
                    gunElev += 0.5;
                }
				else if (e.key.keysym.sym == SDLK_l && gunElev > -5)
                {
                    gunElev -= 0.5;
                }
				else if (e.key.keysym.sym == SDLK_q)
                {
					if(specMode == 0){specMode = 1;}
					else {specMode = 0;}
                }
				else if (e.key.keysym.sym == SDLK_p)
                {
					fireBullet(space, playerShip->gun->body.position, realTurrRot, gunElev, 0.5, -1);
				}
				else if (e.key.keysym.sym == SDLK_x)
                {
					fireBullet(space, playerShip->hull->body.position, shipRot, 0, 0, -2);
				}
				else if (e.key.keysym.sym == SDLK_1)
                {
					startLevel(space, 1);
				}
				else if (e.key.keysym.sym == SDLK_2)
                {
					startLevel(space, 2);
				}
				else if (e.key.keysym.sym == SDLK_3)
                {
					startLevel(space, 3);
				}
            }
        }
		 
        graphics3d_frame_begin();
        
        glPushMatrix();
        set_camera(
            cameraPosition,
            cameraRotation);
        
        entity_draw_all();
		//updateAllShipModels();
        obj_draw(
            bgobj,
            vec3d(0,0,2),
            vec3d(90,90,0),
            vec3d(5,5,5),
            vec4d(1,1,1,1),
            bgtext
        );
        
        if (r > 360)r -= 360;
        glPopMatrix();
        /* drawing code above here! */
        graphics3d_next_frame();
    } 
    return 0;
}
Example #23
0
int
main(int argc, char *argv[])
{
	/* TODO: refactor main() function */

	char dir[PATH_MAX];
	char lwin_path[PATH_MAX] = "";
	char rwin_path[PATH_MAX] = "";
	int lwin_handle = 0, rwin_handle = 0;
	int old_config;
	int no_configs;

	init_config();

	if(is_in_string_array(argv + 1, argc - 1, "--logging"))
	{
		init_logger(1);
	}

	(void)setlocale(LC_ALL, "");
	if(getcwd(dir, sizeof(dir)) == NULL)
	{
		perror("getcwd");
		return -1;
	}
#ifdef _WIN32
	to_forward_slash(dir);
#endif

	init_filelists();
	init_registers();
	set_config_paths();
	reinit_logger();

	init_commands();
	init_builtin_functions();
	update_path_env(1);

	if(init_status() != 0)
	{
		puts("Error during session status initialization.");
		return -1;
	}

	no_configs = is_in_string_array(argv + 1, argc - 1, "--no-configs");

	/* Tell file type module what function to use to check availability of
	 * external programs. */
	config_filetypes(&external_command_exists);
	/* This should be called before loading any configuration file. */
	reset_all_file_associations(curr_stats.env_type == ENVTYPE_EMULATOR_WITH_X);

	init_option_handlers();

	old_config = is_old_config();
	if(!old_config && !no_configs)
		read_info_file(0);

	ipc_pre_init();

	parse_args(argc, argv, dir, lwin_path, rwin_path, &lwin_handle, &rwin_handle);

	ipc_init(&parse_recieved_arguments);

	init_background();

	set_view_path(&lwin, lwin_path);
	set_view_path(&rwin, rwin_path);

	/* Force view switch when path is specified for invisible pane. */
	if(lwin_path[0] != '\0' && rwin_path[0] == '\0' && curr_view != &lwin)
	{
		change_window();
	}

	load_initial_directory(&lwin, dir);
	load_initial_directory(&rwin, dir);

	/* Force split view when two paths are specified on command-line. */
	if(lwin_path[0] != '\0' && rwin_path[0] != '\0')
	{
		curr_stats.number_of_windows = 2;
	}

	/* Setup the ncurses interface. */
	if(!setup_ncurses_interface())
		return -1;

	colmgr_init(COLOR_PAIRS);
	init_modes();
	init_undo_list(&perform_operation, NULL, &cfg.undo_levels);
	load_local_options(curr_view);

	curr_stats.load_stage = 1;

	if(!old_config && !no_configs)
	{
		load_scheme();
		source_config();
	}

	write_color_scheme_file();
	setup_signals();

	if(old_config && !no_configs)
	{
		convert_configs();

		curr_stats.load_stage = 0;
		read_info_file(0);
		curr_stats.load_stage = 1;

		set_view_path(&lwin, lwin_path);
		set_view_path(&rwin, rwin_path);

		load_initial_directory(&lwin, dir);
		load_initial_directory(&rwin, dir);

		source_config();
	}

	(void)create_trash_dir(cfg.trash_dir);

	check_path_for_file(&lwin, lwin_path, lwin_handle);
	check_path_for_file(&rwin, rwin_path, rwin_handle);

	curr_stats.load_stage = 2;

	exec_startup_commands(argc, argv);
	update_screen(UT_FULL);
	modes_update();

	/* Update histories of the views to ensure that their current directories,
	 * which might have been set using command-line parameters, are stored in the
	 * history.  This is not done automatically as history manipulation should be
	 * postponed until views are fully loaded, otherwise there is no correct
	 * information about current file and relative cursor position. */
	save_view_history(&lwin, NULL, NULL, -1);
	save_view_history(&rwin, NULL, NULL, -1);

	curr_stats.load_stage = 3;

	main_loop();

	return 0;
}
Example #24
0
int main(int argc, char **argv) {
	int ncmds, i;
	const char *tmp;
	pgm_error_t *pgm_err = NULL;

	/* FIXME */
	signal(SIGPIPE, SIG_IGN);
	setup_signal_handlers();
	cmds = table_new(cmpstr, hashmurmur2, NULL, NULL);
	ncmds = sizeof commands / sizeof (struct cmd);
	for (i = 0; i < ncmds; ++i) {
		struct cmd *cmd = commands + i;

		table_insert(cmds, cmd->name, cmd);
	}
	if (argc != 2 && argc != 3)
		usage();
	else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))
		usage();
	else if (argc == 3 && strcmp(argv[1], "-f"))
		usage();
	if (argc == 2 && daemon(1, 0) == -1)
		fprintf(stderr, "Error daemonizing: %s\n", strerror(errno));
	/* FIXME */
	if (init_logger("/var/log/xcb/xcb-dp2.log", __LOG_DEBUG) == -1) {
		fprintf(stderr, "Error initializing logger\n");
		exit(1);
	}
	cfg_path = argc == 2 ? argv[1] : argv[2];
	if ((cfg = config_load(cfg_path)) == NULL)
		exit(1);
	if ((tmp = variable_retrieve(cfg, "general", "log_level"))) {
		if (!strcasecmp(tmp, "info"))
			set_logger_level(__LOG_INFO);
		else if (!strcasecmp(tmp, "notice"))
			set_logger_level(__LOG_NOTICE);
		else if (!strcasecmp(tmp, "warning"))
			set_logger_level(__LOG_WARNING);
	}
	/* FIXME */
	if (addms)
		times = table_new(cmpstr, hashmurmur2, kfree, vfree);
	clients_to_close = dlist_new(NULL, NULL);
	clients = dlist_new(NULL, NULL);
	monitors = dlist_new(NULL, NULL);
	tp = thrpool_new(16, 512, 200, NULL);
	if (!pgm_init(&pgm_err)) {
		xcb_log(XCB_LOG_ERROR, "Error starting PGM engine: %s", pgm_err->message);
		pgm_error_free(pgm_err);
		goto err;
	}
	/* FIXME */
	if (NEW(pgm_send_cfg) == NULL) {
		xcb_log(XCB_LOG_ERROR, "Error allocating memory for PGM cfg");
		goto err;
	}
	pgm_send_cfg->network = NULL;
	pgm_send_cfg->port    = 0;
	init_pgm_send_cfg(pgm_send_cfg);
	if (pgm_send_cfg->network == NULL) {
		xcb_log(XCB_LOG_ERROR, "PGM network can't be NULL");
		goto err;
	}
	if (pgm_send_cfg->port == 0) {
		xcb_log(XCB_LOG_ERROR, "PGM port can't be zero");
		goto err;
	}
	if ((pgm_sender = pgmsock_create(pgm_send_cfg->network, pgm_send_cfg->port, PGMSOCK_SENDER)) == NULL)
		goto err;
	/* FIXME */
	if ((el = create_event_loop(1024 + 1000)) == NULL) {
		xcb_log(XCB_LOG_ERROR, "Error creating event loop");
		goto err;
	}
	create_time_event(el, 1, server_cron, NULL, NULL);
	if ((tmp = variable_retrieve(cfg, "general", "udp_port")) && strcmp(tmp, "")) {
		if ((udpsock = net_udp_server(NULL, atoi(tmp), neterr, sizeof neterr)) == -1) {
			xcb_log(XCB_LOG_ERROR, "Opening port '%s': %s", tmp, neterr);
			goto err;
		}
		if (net_nonblock(udpsock, neterr, sizeof neterr) == -1) {
			xcb_log(XCB_LOG_ERROR, "Setting port '%s' nonblocking: %s", tmp, neterr);
			goto err;
		}
	}
	if ((tmp = variable_retrieve(cfg, "general", "tcp_port")) && strcmp(tmp, ""))
		if ((tcpsock = net_tcp_server(NULL, atoi(tmp), neterr, sizeof neterr)) == -1) {
			xcb_log(XCB_LOG_ERROR, "Opening port '%s': %s", tmp, neterr);
			goto err;
		}
	if (udpsock > 0 && create_file_event(el, udpsock, EVENT_READABLE, read_quote, NULL) == -1) {
		xcb_log(XCB_LOG_ERROR, "Unrecoverable error creating udpsock '%d' file event", udpsock);
		goto err;
	}
	if (tcpsock > 0 && create_file_event(el, tcpsock, EVENT_READABLE, tcp_accept_handler, NULL) == -1) {
		xcb_log(XCB_LOG_ERROR, "Unrecoverable error creating tcpsock '%d' file event", tcpsock);
		goto err;
	}
	xcb_log(XCB_LOG_NOTICE, "Server dispatcher started");
	start_event_loop(el, ALL_EVENTS);
	delete_event_loop(el);
	pgm_shutdown();
	return 0;

err:
	close_logger();
	exit(1);
}
Example #25
0
int main(int argc, char* argv[])
{
	signal(SIGINT, &signalHandler);
	signal(SIGABRT, &signalHandler);

	exit_time = 0;
	
	init_list(&peer_array, NULL, RED_BLACK);
	init_list(&server_array, NULL, RED_BLACK);
	
	init_logger(&logger, 8);
	init_logger(&chatlog, 8);

	init_list(&downloads, NULL, LINEAR);
	
	pthread_mutex_init(&display_lock, NULL);

	/* Menu: Connect to register: nlClientEnterRegister */

	nlClientSetFuncs(&exit_state,
					 NULL, 		/* What to do when we connected to game server with success */
					 &getInfo,
					 &newPlayer, /* What to do by a new player */
					 NULL,
					 &deletePlayer, /* And when one leaves. */
					 NULL,
					 &newServer,
					 &deleteServer,
					 NULL,
					 &dlAlloc,
					 &dlInit,
					 &dlSet,
					 &dlDestroy,
					 logger,  /* Log for error/information messages */
					 chatlog, /* Chat log from users. */
					 &loggerNewMessage); /* The function to add messages 
										  * in either the log or the chat.*/

	nlClientInit();

	pthread_mutex_init(&lock, NULL);
	pthread_cond_init(&condition, NULL);
	
	initscr(); /* Init ncurses.h */
	
	/* And the main loop. */
	while(1)
	{
		char c;
		p = 1;
		
		redraw(0);

		c = getch();
		
		if(state == DISCONNECTED)
		{
			if(c == '1')
			{
				pthread_mutex_lock(&lock);
				nlClientEnterRegister(&register_status);
				pthread_cond_wait(&condition, &lock);
				pthread_mutex_unlock(&lock);
			}
			else if(c == '2')
			{
				pthread_mutex_lock(&lock);
				nlClientConnectToIP(&server_status);
				pthread_cond_wait(&condition, &lock);
				pthread_mutex_unlock(&lock);
			}
			else if(c == '0')
			{
				quit();
			}
		}
		else if(state == REGISTER)
		{
			if(c >= '1' && c <= '9')
			{
				if(server_array->length > (unsigned int)(c - '1'))
				{
					unsigned int i = c - '1';
					server_game* g;

					void* (*get)(void*, int) = server_array->get_func;
					void* instance = server_array->instance;
	
					pthread_mutex_lock(&lock);

					if((g = (server_game*)get(instance, FIRST)) != NULL)
					{
						do
						{
							if(i-- == 0)
								nlClientEnterServer(g, &server_status);
						}
						while((g = (server_game*)get(instance, NEXT)) != NULL);
					}
					
					pthread_cond_wait(&condition, &lock);
					pthread_mutex_unlock(&lock);
				}
			}
			else if(c == '0')
			{
				nlClientLeaveRegister();
				state = DISCONNECTED;
			}
		}
		else if(state == SERVER)
		{
			
		}
			/*if(c >= '1' && c <= '9')
			{
				if(peer_array->length > (unsigned int)(c - '1'))
				{
					if((currentPeer = nlClientConnectToPeer(get_n(peer_array, c - '1'), my_name)) != NULL)
					{
						state = PEER;
					}
				}
			}
			else if(c == '0')
			{
				nlClientLeaveServer();
				state = DISCONNECTED;				
			}
		}
		else if(state == PEER)
		{
			if(c == '1')
			{
				pthread_mutex_lock(&lock);
				nlClientSendMessageToPeer(currentPeer);
				pthread_mutex_unlock(&lock);
			}
			else if(c == '2')
			{
				pthread_mutex_lock(&lock);
				nlClientSendFileToPeer(currentPeer);
				pthread_mutex_unlock(&lock);
			}
		}*/
	}

	return 0;
}
Example #26
0
static int server_cron(event_loop el, unsigned long id, void *data) {
	dlist_iter_t iter;
	dlist_node_t node;
	NOT_USED(el);
	NOT_USED(id);
	NOT_USED(data);

	if (log_reload) {
		close_logger();
		if (init_logger("/var/log/xcb/xcb-dp2.log", __LOG_DEBUG) == 0) {
			const char *tmp;

			pthread_mutex_lock(&cfg_lock);
			if ((tmp = variable_retrieve(cfg, "general", "log_level"))) {
				if (!strcasecmp(tmp, "debug"))
					set_logger_level(__LOG_DEBUG);
				else if (!strcasecmp(tmp, "info"))
					set_logger_level(__LOG_INFO);
				else if (!strcasecmp(tmp, "notice"))
					set_logger_level(__LOG_NOTICE);
				else if (!strcasecmp(tmp, "warning"))
					set_logger_level(__LOG_WARNING);
			}
			pthread_mutex_unlock(&cfg_lock);
			log_reload = 0;
		}
		/* FIXME */
		if (addms)
			table_clear(times);
	}
	if (shut_down) {
		if (prepare_for_shutdown() == 0)
			exit(0);
		xcb_log(XCB_LOG_WARNING, "SIGTERM received, but errors trying to shutdown the server");
	}
	/* FIXME */
	iter = dlist_iter_new(clients_to_close, DLIST_START_HEAD);
	while ((node = dlist_next(iter))) {
		client c = (client)dlist_node_value(node);

		if (c->refcount == 0)
			client_free(c);
	}
	dlist_iter_free(&iter);
	/* FIXME */
	if (cronloops % 200 == 0) {
		char meme[] = "SU OT GNOLEB ERA ESAB RUOY LLA";
		int status;

		/* heartbeat */
		dlist_lock(clients);
		if (dlist_length(clients) > 0) {
			dstr res = dstr_new("HEARTBEAT|");
			dstr ip = getipv4();

			res = dstr_cat(res, ip);
			res = dstr_cat(res, "\r\n");
			iter = dlist_iter_new(clients, DLIST_START_HEAD);
			while ((node = dlist_next(iter))) {
				client c = (client)dlist_node_value(node);

				pthread_spin_lock(&c->lock);
				if (net_try_write(c->fd, res, dstr_length(res), 100, NET_NONBLOCK) == -1)
					xcb_log(XCB_LOG_WARNING, "Writing to client '%p': %s",
						c, strerror(errno));
				pthread_spin_unlock(&c->lock);
			}
			dlist_iter_free(&iter);
			dstr_free(ip);
			dstr_free(res);
		}
		dlist_unlock(clients);
		/* FIXME: trying to lower the high CPU load while idle */
		if ((status = pgm_send(pgm_sender, meme, sizeof meme, NULL)) != PGM_IO_STATUS_NORMAL)
			xcb_log(XCB_LOG_WARNING, "Communication test failed");
	}
	++cronloops;
	return 100;
}
Example #27
0
/*
 * Daemonize and persist pid
 */
int
daemon_start()
{
    struct sigaction sig_action;
    sigset_t sig_set;
    pid_t otherpid;
    int curPID;
    pthread_t tcp4_thread, udp4_thread;
    pthread_t tcp6_thread, udp6_thread;

    /* Check if we can acquire the pid file */
    pfh = pidfile_open(NULL, 0600, &otherpid);

    if (pfh == NULL) {
        if (errno == EEXIST) {
            errx(EXIT_FAILURE, "Daemon already running, pid: %jd.", (intmax_t)otherpid);
        }
        err(EXIT_FAILURE, "Cannot open or create pidfile");
    }
    init_logger();

    /* Initialize TCP46 and UDP46 sockets */
    if (init_tcp() == EXIT_FAILURE)
        return (EXIT_FAILURE);
    if (init_udp() == EXIT_FAILURE)
        return (EXIT_FAILURE);

    /* start daemonizing */
    curPID = fork();

    switch (curPID) {
    case 0:			/* This process is the child */
        break;
    case -1:			/* fork() failed, should exit */
        perror("fork");
        return (EXIT_FAILURE);
    default:			/* fork() successful, should exit
					 * (parent) */
        return (EXIT_SUCCESS);
    }

    /* we are the child, complete the daemonization */

    /* Close standard IO */
    fclose(stdin);
    fclose(stdout);
    fclose(stderr);

    /* Block unnecessary signals */
    sigemptyset(&sig_set);
    sigaddset(&sig_set, SIGCHLD);	/* ignore child - i.e. we don't need
					 * to wait for it */
    sigaddset(&sig_set, SIGTSTP);	/* ignore tty stop signals */
    sigaddset(&sig_set, SIGTTOU);	/* ignore tty background writes */
    sigaddset(&sig_set, SIGTTIN);	/* ignore tty background reads */
    sigprocmask(SIG_BLOCK, &sig_set, NULL);	/* Block the above specified
						 * signals */

    /* Catch necessary signals */
    sig_action.sa_handler = signal_handler;
    sigemptyset(&sig_action.sa_mask);
    sig_action.sa_flags = 0;

    sigaction(SIGTERM, &sig_action, NULL);
    sigaction(SIGHUP, &sig_action, NULL);
    sigaction(SIGINT, &sig_action, NULL);

    /* create new session and process group */
    setsid();

    /* persist pid */
    pidfile_write(pfh);

    /* Create TCP and UDP listener threads */
    pthread_create(&tcp4_thread, NULL, tcp4_handler, NULL);
    pthread_create(&udp4_thread, NULL, udp4_handler, NULL);
#ifdef PF_INET6
    pthread_create(&tcp6_thread, NULL, tcp6_handler, NULL);
    pthread_create(&udp6_thread, NULL, udp6_handler, NULL);
#endif

    /*
     * Wait for threads to terminate, which normally shouldn't ever
     * happen
     */
    pthread_join(tcp4_thread, NULL);
    pthread_join(udp4_thread, NULL);
#ifdef PF_INET6
    pthread_join(tcp6_thread, NULL);
    pthread_join(udp6_thread, NULL);
#endif

    return (EXIT_SUCCESS);
}
Example #28
0
int main(int argc, char *argv[])
{
    int i;
    float r = 0;
	int f = -15;
	int g = 0;
	int l = 0;
	int y = 0;
	int u = 15;
	int q = 0;
	int gamestate=0;
	int PlayerHP=15, Bosshealth=30, enemy1health=5, enemy2health=5, Bigtimer=600, CD;
	int SpawnLemon1=0, SpawnLemon2=0, SpawnLemon3=0, SpawnBigLemon=0, enemybullet=0;
	float Lemonx1=0, Lemonx2=0, Lemonx3=0, LemonxBig=0, enemybulletx=0;
	int Lemony1=0, Lemony2=0, Lemony3=0, LemonyBig=0, enemybullety=0;
	int a=0, b=0, c=0, d=0, count, Goomba_attack1=0, Goomba_attack2=0, Goomba_move1, Goomba_move2;
    Space *space;
    Entity *cube1,*cube2, *Actor;
    char bGameLoopRunning = 1;
	Vec3D Bosspos = {u, y, 2};
	Vec3D enemy1pos = {5, 10, 2};
	Vec3D enemy2pos = {5, -10, 2};
    Vec3D cameraPosition = {0,0,70.3};
    Vec3D cameraRotation = {0,0,360};
    SDL_Event e;
    Obj *megaman,*boss, *mapp, *mape, *lemon, *BossHPBar, *PlayerHPBar, *Goomba;
    Sprite *megamantexture, *bosstexture, *maptexture1, *maptexture2, *lemontexture, *BosstextureHP, *PlayertextureHP, *Goombatexture;
    
    init_logger("gametest3d.log");
    if (graphics3d_init(1024,768,1,"gametest3d",33) != 0)
    {
        return -1;
    }
    model_init();
    obj_init();
    entity_init(255);
    
   //load objects, models here, replace cube with megaman
    megaman = obj_load("models/MPU.obj");
	//load his uv map "texture file"
    megamantexture = LoadSprite("models/MegaManBody1.png",1024,1024);

	PlayerHPBar = obj_load("models/cube.obj");
	PlayertextureHP = NULL;


	boss = obj_load("models/Fireman.obj");
	bosstexture = LoadSprite("models/FireManBody1.png",1024,1024);

	BossHPBar = obj_load("models/cube.obj");
	BosstextureHP = NULL;

	Goomba = obj_load("models/goomba.obj");
	Goombatexture = LoadSprite("models/goomba_tex.png",1024,1024);

    mapp = obj_load("models/MidtermMapSingle.obj");
	maptexture1 = LoadSprite("models/PlayerTile(Red).png",1024,1024);

	mape = obj_load("models/MidtermMapSingle.obj");
	maptexture2 = LoadSprite("models/BossTile(Blue).png",1024,1024);
    
    lemon = obj_load("models/cube.obj");
	lemontexture = NULL;//LoadSprite("models/cube_text.png",1024,1024);
    
	    
    while (bGameLoopRunning)
    {
        entity_think_all();

        while ( SDL_PollEvent(&e) ) 
        {
            if (e.type == SDL_QUIT)
            {
                bGameLoopRunning = 0;
            }
            else if (e.type == SDL_KEYDOWN)
            {
                if (e.key.keysym.sym == SDLK_ESCAPE)
                {
                    bGameLoopRunning = 0;
                }
                else if (e.key.keysym.sym == SDLK_x)
                {
                    cameraPosition.z++;
                }
                else if (e.key.keysym.sym == SDLK_z)
                {
                    cameraPosition.z--;
                }
                else if (e.key.keysym.sym == SDLK_h)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            -sin(cameraRotation.z * DEGTORAD),
                            cos(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_y)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            sin(cameraRotation.z * DEGTORAD),
                            -cos(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_j)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            cos(cameraRotation.z * DEGTORAD),
                            sin(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
                else if (e.key.keysym.sym == SDLK_g)
                {
                    vec3d_add(
                        cameraPosition,
                        cameraPosition,
                        vec3d(
                            -cos(cameraRotation.z * DEGTORAD),
                            -sin(cameraRotation.z * DEGTORAD),
                            0
                        ));
                }
				else if (e.key.keysym.sym == SDLK_d)
                {
                   
				   
				   if(f >= -5)
				   {
					   f = -5;
				   }
				   else
				   {
					   f += 10;
				   }
                }
				else if (e.key.keysym.sym == SDLK_a)
                {
                   
				   
				   if(f <= -20)
				   {
					   f = -25;
				   }
				   else
				   {
					   f -= 10;
				   }
				  			
                }
				else if (e.key.keysym.sym == SDLK_w)
                {
                   
				   if(g >= 5)
				   {
					   g = 10;
				   }
				   else
				   {
					   g += 10;
				   }
			
                }
				else if (e.key.keysym.sym == SDLK_s)
                {
                   
				   g -= 10;
				    if(g <= -5)
				   {
					   g = -10;
				   }
			
                }
                else if (e.key.keysym.sym == SDLK_LEFT)
                {
                    cameraRotation.z += 1;
                }
                else if (e.key.keysym.sym == SDLK_RIGHT)
                {
                    cameraRotation.z -= 1;
                }
                else if (e.key.keysym.sym == SDLK_UP)
                {
                    cameraRotation.x += 1;
                }
                else if (e.key.keysym.sym == SDLK_DOWN)
                {
                    cameraRotation.x -= 1;
                }
                else if (e.key.keysym.sym == SDLK_SPACE)
                {
                    
					CD = TIME + Bigtimer;					
					
                }
				else if (e.key.keysym.sym == SDLK_n)
                {
                   
				   if (enemy1health <= 0 && enemy2health <= 0)
				   {
					   gamestate=1;
				   }
			
                }
				else if (e.key.keysym.sym == SDLK_n)
                {
                   
				   if (enemy1health <= 0 && enemy2health <= 0)
				   {
					   gamestate=1;
				   }
			
                }
            }
			else if (e.type == SDL_KEYUP)
			{
				if (e.key.keysym.sym == SDLK_SPACE)
				{
					
					if (TIME >= CD && SpawnBigLemon !=1)
					{
						SpawnBigLemon = 1;
						LemonxBig = f;
						LemonyBig = g;
					}
					else if (SpawnLemon1 != 1)
					{
						SpawnLemon1 = 1;
						Lemonx1 = f;
						Lemony1 = g;
					}
					else if (SpawnLemon2 != 1)
					{
						SpawnLemon2 = 1;
						Lemonx2 = f;
						Lemony2 = g;
					}
					else if (SpawnLemon3 != 1)
					{
						SpawnLemon3 = 1;
						Lemonx3 = f;
						Lemony3 = g;
					}
					
				}
			}
				
        }

                
        graphics3d_frame_begin();
        
        glPushMatrix();
        set_camera(
            cameraPosition,
            cameraRotation);
        
        //entity_draw_all();
      
		if (PlayerHP > 0 )
		{
		//Megaman
        obj_draw(
            megaman,
            vec3d(f, g, 2),
            vec3d(90,90,0),
            vec3d(0.5,0.5,0.5),
            vec4d(1,1,1,1),
            megamantexture
        );

		//Megaman HP BAR
		obj_draw(
            PlayerHPBar,
            vec3d(-30+PlayerHP/(2),20,2),
            vec3d(90,-90,0),
            vec3d(.9,.9,PlayerHP/(2)),
            vec4d(0,1,0,1),
			PlayertextureHP
        );
		}

		//Megaman Projectiles
		//Lemon1
		if (SpawnLemon1 != 0)
		{
			obj_draw(
			lemon,
            vec3d(Lemonx1 + a*(.4), Lemony1, 4),
            vec3d(90,90,0),
            vec3d(1,1,2),
            vec4d(.95,.89,0,1),
		    lemontexture
		);
			a++;
				if (Lemonx1 + a*(.4) >=30)
				{
					SpawnLemon1 = 0;
					a=0;
				}
				else if (Lemonx1 + a*(.4) == enemy1pos.x && Lemony1 == enemy1pos.y)
				{
					SpawnLemon1 = 0;
					a=0;
					enemy1health -= 1;
					//slog("Enemy Health %d",enemy1health);
				}
				else if (Lemonx1 + a*(.4) == enemy2pos.x && Lemony1 == enemy2pos.y)
				{
					SpawnLemon1 = 0;
					a=0;
					enemy2health -= 1;
					//slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && Lemonx1 + a*(.4) == Bosspos.x && Lemony1 == Bosspos.y)
				{
				SpawnLemon1 = 0;
				a=0;
				Bosshealth -= 1;
				//slog("Boss Health %d",Bosshealth);
				}
		}
		//Lemon2
		if (SpawnLemon2 != 0)
		{
			obj_draw(
			lemon,
            vec3d(Lemonx2 + b*(.4), Lemony2, 4),
            vec3d(90,90,0),
            vec3d(1,1,2),
            vec4d(.95,.89,0,1),
		    lemontexture
		);
			b++;
				if (Lemonx2 + b*(.4) >=30)
				{
					SpawnLemon2 = 0;
					b=0;
				}
				else if (Lemonx2 + b*(.4) == enemy1pos.x && Lemony2 == enemy1pos.y)
				{
					SpawnLemon2 = 0;
					b=0;
					enemy1health -= 1;
					//slog("Enemy Health %d",enemy1health);
				}
				else if (Lemonx2 + b*(.4) == enemy2pos.x && Lemony2 == enemy2pos.y)
				{
					SpawnLemon2 = 0;
					b=0;
					enemy2health -= 1;
					//slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && Lemonx2 + b*(.4) == Bosspos.x && Lemony2 == Bosspos.y)
				{
					SpawnLemon2 = 0;
					b=0;
					Bosshealth -= 1;
					//slog("Boss Health %d",Bosshealth);
				}
		}
		if (SpawnLemon3 != 0)
		{
			obj_draw(
			lemon,
            vec3d(Lemonx3 + c*(.4), Lemony3, 4),
            vec3d(90,90,0),
            vec3d(1,1,2),
            vec4d(.95,.89,0,1),
		    lemontexture
		);
			c++;
				//lemons fly off staege
				if (Lemonx3 + c*(.4) >=30)
				{
					SpawnLemon3 = 0;
					c=0;
				}
				//lemons collide with enemies
				else if (Lemonx3 + c*(.4) == enemy1pos.x && Lemony3 == enemy1pos.y)
				{
					SpawnLemon3 = 0;
					c=0;
					enemy1health -= 1;
					slog("Enemy Health %d",enemy1health);
				}
				else if (Lemonx3 + c*(.4) == enemy2pos.x && Lemony3 == enemy2pos.y)
				{
					SpawnLemon3 = 0;
					c=0;
					enemy2health -= 1;
					slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && Lemonx3 + c*(.4) == Bosspos.x && Lemony3 == Bosspos.y)
				{
					SpawnLemon3 = 0;
					c=0;
					Bosshealth -= 1;
					//slog("Boss Health %d",Bosshealth);
				}
		}
		if (SpawnBigLemon != 0)
		{
			obj_draw(
			lemon,
            vec3d(LemonxBig + d*(.4), LemonyBig, 4),
            vec3d(90,90,0),
            vec3d(2,2,4),
            vec4d(.9,.3,.1,1),
		    lemontexture
		);
			d++;
				if (LemonxBig + d*(.4) >=30)
				{
					SpawnBigLemon = 0;
					d=0;
				}
				else if (LemonxBig + d*(.4) == enemy1pos.x && LemonyBig == enemy1pos.y)
				{
					SpawnBigLemon = 0;
					d=0;
					enemy1health -= 5;
					//slog("Enemy Health %d",enemy1health);
				}
				else if (LemonxBig + d*(.4) == enemy2pos.x && LemonyBig == enemy2pos.y)
				{
					SpawnBigLemon = 0;
					d=0;
					enemy2health -= 5;
					//slog("Enemy Health %d",enemy2health);
				}
				else if (gamestate == 1 && LemonxBig + d*(.4) == Bosspos.x && LemonyBig == Bosspos.y)
				{
					SpawnBigLemon = 0;
					d=0;
					Bosshealth -= 5;
					slog("Boss Health %d",Bosshealth);
				}
		}

		
		//MAP
		obj_draw(
            mapp,
            vec3d(-15,0,2),
            vec3d(90,90,0),
            vec3d(5,5,5),
            vec4d(1,1,1,1),
		    maptexture1
		);
		obj_draw(
            mape,
            vec3d(15,0,2),
            vec3d(90,90,0),
            vec3d(5,5,5),
            vec4d(1,1,1,1),
		    maptexture2
		);
		

		//Enemies
		if (gamestate == 0)
		{

			if (enemy1health > 0)
			{
			//enemy_move(enemypos.x,enemypos.y, &enemypos);
			//enemy_attack1(Goomba_attack1, &enemy1pos);

			obj_draw(
            Goomba,
            vec3d(enemy1pos.x,enemy1pos.y,2),
            vec3d(90,-90,0),
            vec3d(0.1,0.1,0.1),
            vec4d(1,1,1,1),
            Goombatexture
			);
						
			if (Goomba_attack1 == 0)
			{
				Goomba_attack1 = rand_ranged( 1, 5); //start to (end - 1)
				if (Goomba_attack1 == 2)
				{
					Goomba_attack1 = 1;
				}
		
			};

			if (Goomba_attack1 == 1)
			{
				enemy1pos.x -=.1;
				if (enemy1pos.x <= -30)
				{
					Goomba_attack1 = 0;
					enemy1pos.x = 5;
				}
			}

			}
			else
			{
				enemy1pos.x = 50;
				enemy1pos.y = 50;
			}

			if (enemy2health > 0)
			{
			//enemy_move(enemypos.x,enemypos.y, &enemypos);
			//enemy_attack2(Goomba_attack2, &enemy2pos);
			obj_draw(
            Goomba,
            vec3d(enemy2pos.x,enemy2pos.y,2),
            vec3d(90,-90,0),
            vec3d(0.1,0.1,0.1),
            vec4d(1,1,1,1),
            Goombatexture
			);

			//bottom Goomba won't attack

			if (Goomba_attack2 == 0)
			{
				Goomba_attack2 = rand_ranged( 1, 5); //start to (end - 1)
				if (Goomba_attack2 == 2)
				{
					Goomba_attack2 = 1;
				}
		
			};

			if (Goomba_attack2 == 1)
			{
				enemy2pos.x -=.1;
				if (enemy2pos.x <= -30)
				{
					Goomba_attack2 = 0;
					enemy2pos.x = 5;
				}
			}

			
			}
			else
			{
				enemy2pos.x = 50;
				enemy2pos.y = 50;
			}
			
		}
		if (gamestate != 0)
		{
		if (Bosshealth > 0)
		{
			Boss_move(Bosspos.x,Bosspos.y, &Bosspos);      	    
			//Fire man
			obj_draw(
				boss,
				vec3d(Bosspos.x,Bosspos.y,2),
				vec3d(90,-90,0),
				vec3d(0.5,0.5,0.5),
				vec4d(1,1,1,1),
				bosstexture
				);

				obj_draw(
				BossHPBar,
				vec3d(30-Bosshealth/(2.5),20,2),
				vec3d(90,-90,0),
				vec3d(.9,.9,Bosshealth/(2.5)),
				vec4d(1,0,0,1),
				BosstextureHP
			);

		}
		else
		{
			obj_free(boss);

			Bosspos.x = 50;
			Bosspos.y = 50;
			slog("You WIN!");
		}
		

		}
        
        if (r > 360)r -= 360;
        glPopMatrix();
        /* drawing code above here! */
        graphics3d_next_frame();
	} 
	return 0;
	}
Example #29
0
/**
 * void run(int argc, char **argv)
 * 
 * Starts the server, processes command line arguments, initiates all necessary
 * functions and threads and enters infinite loop accepting user input.
 */
void run(int argc, char **argv) {
    char user_input_buffer[250];
    char addr_buffer[INET_ADDRSTRLEN] = {0};
    char *buff;
    struct in_addr tmp_addr;
    int port;
    int tmp_num;
    
    /* Get start timestamp */
    gettimeofday(&ts_start, NULL);
    
    /* Init logger first */
    if(argc >= 4) {
        init_logger(argv[3]);
    }
    else {
        init_logger(STRINGIFY(DEFAULT_LOGFILE));
    }
    
    /* Validate input */
    if(argc >= 3) {
        
        /* Validate ip address */
        if(inet_pton(AF_INET, argv[1], (void *) &tmp_addr) <= 0 &&
                !hostname_to_ip(argv[1], addr_buffer)) {
            
            help();
            raise_error("Error validating server adress.\n");
            
        }
        
        if(!addr_buffer[0]) {
            strcpy(addr_buffer, argv[1]);
        }
        
        /* Validate port */
        port = (int) strtoul(argv[2], NULL, 10);
        
        if(port <= 0 || port >= 65536) {
            help();
            raise_error("Port number is out of range.\n");
        }
        
        if(port <= 1024 && port != 0) {
            log_line("Trying to bind to a port number lower than 1024, this "
                    "might required administrator privileges.", LOG_ALWAYS);
        }
        
        /* Got log severity */
        if(argc >= 5) {
            log_level = (int) strtol(argv[4], NULL, 10);
        }
        
        sprintf(log_buffer,
                "Setting logging level to %d",
                log_level
                );
        
        log_line(log_buffer, LOG_ALWAYS);
        
        /* Got verbose */
        if(argc == 6) {
            verbose_level = (int) strtol(argv[5], NULL, 10);
        }
        
        sprintf(log_buffer,
                "Setting verbose level to %d",
                verbose_level
                );
        
        log_line(log_buffer, LOG_ALWAYS);
    }
    else {
        help();
        raise_error("Invalid arguments.\n");
    }
    
    /* Initiate server */
    init_server(addr_buffer, port);
    
    /* Start watchdog */
    pthread_mutex_init(&mtx_thr_watchdog, NULL);
    pthread_mutex_lock(&mtx_thr_watchdog);
    
    if(pthread_create(&thr_watchdog, NULL, start_watchdog, (void *) &mtx_thr_watchdog) != 0) {
        raise_error("Error starting watchdog thread.");
    }
    
    /* Start receiver */
    pthread_mutex_init(&mtx_thr_receiver, NULL);
    pthread_mutex_lock(&mtx_thr_receiver);
    
    if(pthread_create(&thr_receiver, NULL, start_receiving, (void *) &mtx_thr_receiver) != 0) {
        raise_error("Error starting receiving thread.");
    }
    
    /* Start sender */
    pthread_mutex_init(&mtx_thr_sender, NULL);
    pthread_mutex_lock(&mtx_thr_sender);
    
    if(pthread_create(&thr_sender, NULL, start_sending, (void *) &mtx_thr_sender) != 0) {
        raise_error("Error starting sender thread.");
    }
    
    /* Initiate server command line loop */
    while(1) {
        printf("CMD: ");
        
        if(fgets(user_input_buffer, 250, stdin) != NULL) {
            /* Exit server with exit, shutdown, halt or close commands */
            if( (strncmp(user_input_buffer, "exit", 4) == 0) ||
                    (strncmp(user_input_buffer, "shutdown", 8) == 0) ||
                    (strncmp(user_input_buffer, "halt", 4) == 0) ||
                    (strncmp(user_input_buffer, "close", 5) == 0)) {
                
                _shutdown();
                
                break;                
            }
            
            /* Set number that will be rolled */
            else if (strncmp(user_input_buffer, "force_roll", 10) == 0) {
                /* Strip header */
                if(strtok(user_input_buffer, " ") != NULL) {
                    buff = strtok(NULL, " ");
                    
                    if(buff != NULL) {
                        /* Get number */
                        force_roll = (int) strtoul(buff, NULL, 10);

                        if(force_roll >= 1 && force_roll <= 6) {
                            sprintf(log_buffer,
                                    "CMD: Forcing roll on all consequent rolls to %d",
                                    force_roll
                                    );
                            
                            log_line(log_buffer, LOG_ALWAYS);
                        }
                        else {
                            log_line("CMD: Rolling will be random now.", LOG_ALWAYS);
                        }
                    }
                }
            }
            
            /* Set log level */
            else if(strncmp(user_input_buffer, "set_log", 7) == 0) {
                if(strtok(user_input_buffer, " ") != NULL) {
                    buff = strtok(NULL, " ");
                    
                    if(buff) {
                        tmp_num = (int) strtoul(buff, NULL, 10);
                        
                        if(tmp_num >= LOG_NONE || tmp_num <= LOG_ALWAYS) {
                            log_level = tmp_num;
                            
                            sprintf(log_buffer,
                                    "CMD: Setting log level to %d",
                                    log_level
                                    );
                            
                            log_line(log_buffer, LOG_ALWAYS);
                        }
                    }
                }
            }
            
            /* Set log level */
            else if(strncmp(user_input_buffer, "set_verbose", 11) == 0) {
                if(strtok(user_input_buffer, " ") != NULL) {
                    buff = strtok(NULL, " ");
                    
                    if(buff) {
                        tmp_num = (int) strtoul(buff, NULL, 10);
                        
                        if(tmp_num >= LOG_NONE || tmp_num <= LOG_ALWAYS) {
                            verbose_level = tmp_num;
                            
                            sprintf(log_buffer,
                                    "CMD: Setting verbose level to %d",
                                    verbose_level
                                    );
                            
                            log_line(log_buffer, LOG_ALWAYS);
                        }
                    }
                }
            }
            
            /* Get server uptime */
            else if(strncmp(user_input_buffer, "uptime", 6) == 0) {
                display_uptime();
            }
            
            /* Get current number of clients (event timeouted) */
            else if(strncmp(user_input_buffer, "playercount", 11) == 0) {
                sprintf(log_buffer,
                        "Current number of clients (including timeouted) is %d",
                        client_num
                        );
                
                log_line(log_buffer, LOG_ALWAYS);
            }

	    /* Force sound on to all clients */
	    else if(strncmp(user_input_buffer, "sound_on", 8) == 0) {
		broadcast_clients("FORCE_SOUND;1", 1);

		strcpy(log_buffer, "Forcing sound ON to all clients!");

		log_line(log_buffer, LOG_ALWAYS);
	    }
	    
	    /* Force sound off to all clients */
	    else if(strncmp(user_input_buffer, "sound_off", 9) == 0) {
		broadcast_clients("FORCE_SOUND;0", 1);

		strcpy(log_buffer, "Forcing sound ON to all clients!");

		log_line(log_buffer, LOG_ALWAYS);
	    }
        }
    }
}
Example #30
0
/* Entry-point.  Has same semantics as main(). */
static int
vifm_main(int argc, char *argv[])
{
	/* TODO: refactor vifm_main() function */

	static const int quit = 0;

	char **files = NULL;
	int nfiles = 0;
	int lwin_cv, rwin_cv;

	char dir[PATH_MAX + 1];
	if(get_start_cwd(dir, sizeof(dir)) != 0)
	{
		return -1;
	}

	args_parse(&vifm_args, argc, argv, dir);
	args_process(&vifm_args, 1);

	lwin_cv = (strcmp(vifm_args.lwin_path, "-") == 0 && vifm_args.lwin_handle);
	rwin_cv = (strcmp(vifm_args.rwin_path, "-") == 0 && vifm_args.rwin_handle);
	if(lwin_cv || rwin_cv)
	{
		files = read_stream_lines(stdin, &nfiles, 1, NULL, NULL);
		if(reopen_term_stdin() != 0)
		{
			free_string_array(files, nfiles);
			return EXIT_FAILURE;
		}
	}

	(void)setlocale(LC_ALL, "");
	srand(time(NULL));

	cfg_init();

	if(vifm_args.logging)
	{
		init_logger(1, vifm_args.startup_log_path);
	}

	init_filelists();
	tabs_init();
	regs_init();
	cfg_discover_paths();
	reinit_logger(cfg.log_file);

	/* Commands module also initializes bracket notation and variables. */
	init_commands();

	init_builtin_functions();
	update_path_env(1);

	if(stats_init(&cfg) != 0)
	{
		free_string_array(files, nfiles);

		puts("Error during session status initialization.");
		return -1;
	}

	/* Tell file type module what function to use to check availability of
	 * external programs. */
	ft_init(&external_command_exists);
	/* This should be called before loading any configuration file. */
	ft_reset(curr_stats.exec_env_type == EET_EMULATOR_WITH_X);

	init_option_handlers();

	if(!vifm_args.no_configs)
	{
		/* vifminfo must be processed this early so that it can restore last visited
		 * directory. */
		read_info_file(0);
	}

	curr_stats.ipc = ipc_init(vifm_args.server_name, &parse_received_arguments,
			&eval_received_expression);
	if(ipc_enabled() && curr_stats.ipc == NULL)
	{
		fputs("Failed to initialize IPC unit", stderr);
		return -1;
	}
	/* Export chosen server name to parsing unit. */
	{
		var_t var = var_from_str(ipc_get_name(curr_stats.ipc));
		setvar("v:servername", var);
		var_free(var);
	}

	args_process(&vifm_args, 0);

	bg_init();

	fops_init(&enter_prompt_mode, &prompt_msg_custom);

	set_view_path(&lwin, vifm_args.lwin_path);
	set_view_path(&rwin, vifm_args.rwin_path);

	if(need_to_switch_active_pane(vifm_args.lwin_path, vifm_args.rwin_path))
	{
		swap_view_roles();
	}

	load_initial_directory(&lwin, dir);
	load_initial_directory(&rwin, dir);

	/* Force split view when two paths are specified on command-line. */
	if(vifm_args.lwin_path[0] != '\0' && vifm_args.rwin_path[0] != '\0')
	{
		curr_stats.number_of_windows = 2;
	}

	/* Prepare terminal for further operations. */
	curr_stats.original_stdout = reopen_term_stdout();
	if(curr_stats.original_stdout == NULL)
	{
		free_string_array(files, nfiles);
		return -1;
	}

	if(!setup_ncurses_interface())
	{
		free_string_array(files, nfiles);
		return -1;
	}

	init_modes();
	un_init(&undo_perform_func, NULL, &ui_cancellation_requested,
			&cfg.undo_levels);
	load_view_options(curr_view);

	curr_stats.load_stage = 1;

	/* Make v:count exist during processing configuration. */
	set_count_vars(0);

	if(!vifm_args.no_configs)
	{
		load_scheme();
		cfg_load();
	}

	if(lwin_cv || rwin_cv)
	{
		flist_custom_set(lwin_cv ? &lwin : &rwin, "-", dir, files, nfiles);
	}
	free_string_array(files, nfiles);

	cs_load_pairs();
	cs_write();
	setup_signals();

	/* Ensure trash directories exist, it might not have been called during
	 * configuration file sourcing if there is no `set trashdir=...` command. */
	(void)set_trash_dir(cfg.trash_dir);

	check_path_for_file(&lwin, vifm_args.lwin_path, vifm_args.lwin_handle);
	check_path_for_file(&rwin, vifm_args.rwin_path, vifm_args.rwin_handle);

	curr_stats.load_stage = 2;

	/* Update histories of the views to ensure that their current directories,
	 * which might have been set using command-line parameters, are stored in the
	 * history.  This is not done automatically as history manipulation should be
	 * postponed until views are fully loaded, otherwise there is no correct
	 * information about current file and relative cursor position. */
	flist_hist_save(&lwin, NULL, NULL, -1);
	flist_hist_save(&rwin, NULL, NULL, -1);

	/* Trigger auto-commands for initial directories. */
	if(!lwin_cv)
	{
		(void)vifm_chdir(flist_get_dir(&lwin));
		vle_aucmd_execute("DirEnter", flist_get_dir(&lwin), &lwin);
	}
	if(!rwin_cv)
	{
		(void)vifm_chdir(flist_get_dir(&rwin));
		vle_aucmd_execute("DirEnter", flist_get_dir(&rwin), &rwin);
	}

	update_screen(UT_FULL);
	modes_update();

	/* Run startup commands after loading file lists into views, so that commands
	 * like +1 work. */
	exec_startup_commands(&vifm_args);

	curr_stats.load_stage = 3;

	event_loop(&quit);

	return 0;
}