void templateAppInit(int width, int height)
{
    GFX_start();
    glViewport(0.0f, 0.0f, width, height);
    GFX_set_matrix_mode(PROJECTION_MATRIX);
    {
	float half_width = (float)width * 0.5f, half_height = (float)height *0.5f;
	GFX_load_identity();
	GFX_set_orthographic_2d(-half_width, half_width, -half_height, half_height);
	GFX_translate(-half_width, -half_height, 0.0f);
	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);
    }
    program = PROGRAM_init((char *)"default");
    program->vertex_shader = SHADER_init(VERTEX_SHADER, GL_VERTEX_SHADER);
    program->fragment_shader = SHADER_init(FRAGMENT_SHADER, GL_FRAGMENT_SHADER);
    m = mopen(VERTEX_SHADER, 1);
    if (m) {
	if (!SHADER_compile(program->vertex_shader, (char *)m->buffer, DEBUG_SHADERS))
	    exit(1);
    }
    m = mclose(m);
    m = mopen(FRAGMENT_SHADER, 1);
    if (m) {
	if (!SHADER_compile(program->fragment_shader, (char *)m->buffer, DEBUG_SHADERS))
	    exit(2);
    }
    m = mclose(m);
    if (!PROGRAM_link(program, DEBUG_SHADERS))
	exit(3);
}
void templateAppInit( int width, int height )
{
	atexit( templateAppExit );

	GFX_start();

	glViewport( 0.0f, 0.0f, width, height );

	GFX_set_matrix_mode( PROJECTION_MATRIX );
	{
		GFX_load_identity();
		//设置为透视投影
		GFX_set_perspective( 45.0f,
							 ( float )width / ( float )height,
							 0.01f,
							 100.0f,
							 0.0f );
		//角度越大,视角范围越宽广,相反,角度越小媒,投影也越窄
        glDisable( GL_CULL_FACE );
	}
	
	program = PROGRAM_init( ( char * )"default" );
	
	program->vertex_shader = SHADER_init( VERTEX_SHADER, GL_VERTEX_SHADER );
   
	program->fragment_shader = SHADER_init( FRAGMENT_SHADER, GL_FRAGMENT_SHADER );	
	
	m = mopen( VERTEX_SHADER, 1 );
	
	if( m ) {
	
		if( !SHADER_compile( program->vertex_shader,
						     ( char * )m->buffer,
							 DEBUG_SHADERS ) ) exit( 1 );
	}
	m = mclose( m );

	m = mopen( FRAGMENT_SHADER, 1 );
	
	if( m ) {
	
		if( !SHADER_compile( program->fragment_shader,
						     ( char * )m->buffer,
						     DEBUG_SHADERS ) ) exit( 2 ); 
	}
	  
	m = mclose( m );

   if( !PROGRAM_link( program, DEBUG_SHADERS ) ) exit( 3 );
}
void templateAppInit(int width, int height)
{
    GFX_start();
    glViewport(0.0f, 0.0f, width, height);
    GFX_set_matrix_mode(PROJECTION_MATRIX);
    GFX_load_identity();
    GFX_set_perspective(45.0f, (float)width / (float)height, 0.1f, 100.0f, -90.0f);
    obj = OBJ_load(OBJ_FILE, 1);
    unsigned int i = 0;
    while (i != obj->n_objmesh) {
	OBJ_build_mesh(obj, i);
	OBJ_free_mesh_vertex_data(obj, i);
	++i;
    }
    i = 0;
    while (i != obj->n_texture) {
	OBJ_build_texture(obj, i, obj->texture_path, TEXTURE_MIPMAP, TEXTURE_FILTER_2X, 0.0f);
	++i;
    }
    i = 0;
    while (i != obj->n_objmaterial) {
	MEMORY *fragment_shader = mopen((char *)"fragment.glsl", 1);
	MEMORY *vertex_shader = mopen((char *)"vertex.glsl", 1);
	OBJMATERIAL *objmaterial = &obj->objmaterial[i];
	OBJ_build_material(obj, i, NULL);
	if (objmaterial->dissolve == 1.0f)
	    minsert(fragment_shader, (char *)"#define SOLID_OBJECT\n", 0);
	else if (!objmaterial->dissolve)
	    minsert(fragment_shader, (char *)"#define ALPHA_TESTED_OBJECT\n", 0);
	else
	    minsert(fragment_shader, (char *)"#define TRANSPARENT_OBJECT\n", 0);
	if (objmaterial->illumination_model) {
	    minsert(vertex_shader, (char *)"#define LIGHTING_SHADER\n", 0);
	    minsert(fragment_shader, (char *)"#define LIGHTING_SHADER\n", 0);
	}
	objmaterial->program = PROGRAM_init(objmaterial->name);
	objmaterial->program->vertex_shader = SHADER_init((char *)"vertex", GL_VERTEX_SHADER);
	objmaterial->program->fragment_shader = SHADER_init((char *)"fragment", GL_FRAGMENT_SHADER);
	SHADER_compile(objmaterial->program->vertex_shader, (char *)vertex_shader->buffer, 1);
	SHADER_compile(objmaterial->program->fragment_shader, (char *)fragment_shader->buffer, 1);
	PROGRAM_set_bind_attrib_location_callback(objmaterial->program, program_bind_attrib_location);
	PROGRAM_link(objmaterial->program, 1);
	OBJ_set_draw_callback_material(obj, i, material_draw_callback);
	mclose(fragment_shader);
	mclose(vertex_shader);
	++i;
    }
}
int main(int argc, char *argv[])
{
	int do_restore = argc > 1 && strcmp("-r", argv[1]) == 0;
	const char *mode = (do_restore) ? "r+" : "w+";

	/* call perm() and open() before malloc() */
	perm(PERM_START, PERM_SIZE);
	mopen(MMAP_FILE, mode, MMAP_SIZE);
	bopen(BACK_FILE, mode);
	if (do_restore) {
		restore();
	} else {
		home = (home_st *)malloc(sizeof(home_st));
		/* initialize home struct... */
		mflush(); backup();
	}

	for (;/* each step */;) {
		/* Application_Step(); */
		backup();
	}

	free(home);
	mclose();
	bclose();
	return(0);
}
Exemple #5
0
void load_physic_world( void )
{
	btBulletWorldImporter *btbulletworldimporter = new btBulletWorldImporter( dynamicsworld );

	MEMORY *memory = mopen( PHYSIC_FILE, 1 );

	btbulletworldimporter->loadFileFromMemory( ( char * )memory->buffer, memory->size );

	mclose( memory );

	unsigned int i = 0;

	while( i != btbulletworldimporter->getNumRigidBodies() ) { 

		OBJMESH *objmesh = OBJ_get_mesh( obj,
										 btbulletworldimporter->getNameForPointer(
										 btbulletworldimporter->getRigidBodyByIndex( i ) ), 0 ); 

		if( objmesh ) { 

			objmesh->btrigidbody = ( btRigidBody * )btbulletworldimporter->getRigidBodyByIndex( i );
			
			objmesh->btrigidbody->setUserPointer( objmesh );
		} 

		++i; 
	} 

	delete btbulletworldimporter;
}
int main(){
	Color black = make_color(0, 0, 0);
	MMC mmc, *mp;
	IMG img, *ip;

	while(1){
		mmc = mopen(), mp = &mmc;
		mseek(mp, PROGRAM_SIZE, SEEK_CUR);
		
		img = iopen(mp), ip = &img;
		
		draw_clear(&black);
		draw_img(ip);

		while(1){
			if(check_switch(SWITCH1, ON)){

				if(seek_next_img(ip)){
					mclose(mp);
					break;
				}

				draw_img(ip);
			}
		}
	}
}
Exemple #7
0
void *safe_mopen (char *filename)
{
	void
		*ptr;

	ASSERT (filename);

	ptr = mopen (filename);

	if ( !ptr )
	{

		if ( file_exist ( filename ) )
		{

			debug_fatal ( "Unable to map file %s\n\nThis may be due to lack of virtual memory", filename );
		}
		else
		{

			debug_fatal ( "Unable to load file %s", filename );
		}
	}

	safe_memory_mapped_file_counter++;

	return (ptr);
}
Exemple #8
0
void Pause(bool pause)
{
	if(pause)
	{
		game_state=3;
		console_print("paused");
		SOUND_stop( water_sound );
		SOUND_stop( lava_sound );
		SOUND_stop( toxic_sound );
		SOUND_stop( background_sound );


	}
	else
	{
		game_state=0;
		console_print("unpaused");
		SOUND_play( water_sound, 1 );
		SOUND_play( lava_sound, 1 );
		SOUND_play( toxic_sound, 1 );
		MEMORY *memory;
		memory = mopen( ( char * )"background.ogg", 1 );

		background_soundbuffer = SOUNDBUFFER_load_stream( ( char * )"background", memory );

		background_sound = SOUND_add( ( char * )"background", background_soundbuffer );

		SOUND_set_volume( background_sound, 0.5f );

		SOUND_play( background_sound, 1 );


	}

}
Exemple #9
0
void load_terrain_3d_tree_database ( char *sector_filename, char *data_filename )
{

	FILE
		*fp;

	int
		x_sector,
		z_sector;

	terrain_tree_data
		*tree_data;

	//
	// Memory map the tree data file
	//

	terrain_tree_database = mopen ( data_filename );

	if ( !terrain_tree_database )
	{

		debug_fatal ( "Unable to memory-map %s", data_filename );
	}

	//
	// Open the sector file
	//

	fp = safe_fopen ( sector_filename, "rb" );

	//
	// Go through all the sectors, setting the number of trees and the relevant pointer
	//

	tree_data = terrain_tree_database;

	for ( z_sector = 0; z_sector < terrain_3d_sector_z_max; z_sector++ )
	{

		for ( x_sector = 0; x_sector < terrain_3d_sector_z_max; x_sector++ )
		{

			fread ( &terrain_tree_sectors[z_sector][x_sector].number_of_trees, sizeof ( int ), 1, fp );

			if ( terrain_tree_sectors[z_sector][x_sector].number_of_trees )
			{

				terrain_tree_sectors[z_sector][x_sector].data = tree_data;

				tree_data += terrain_tree_sectors[z_sector][x_sector].number_of_trees;
			}
			else
			{

				terrain_tree_sectors[z_sector][x_sector].data = NULL;
			}
		}
	}
}
Exemple #10
0
void			startup ()
{
	trap_signals ();

	if (mopen() == -1)
		scheduler_active = 0;
	else
		scheduler_active = 1;

	return;
}
Exemple #11
0
HIO_HANDLE *hio_open_mem(void *ptr, long size)
{
	HIO_HANDLE *h;

	h = (HIO_HANDLE *)malloc(sizeof (HIO_HANDLE));
	if (h == NULL)
		return NULL;
	
	h->type = HIO_HANDLE_TYPE_MEMORY;
	h->handle.mem = mopen(ptr, size);
	h->size = size;

	return h;
}
Exemple #12
0
int main() {
	mount("volume2.vfs");
	ls();
	touch("ppg");
	ls();
	int fd;
	fd = mopen("ppg");
	char *out = mread(fd);
	printf(out);
	mclose(fd);

	fd = mopen("ppg");
	mwrite(fd, "spider man!");
	mclose(fd);
	
	fd = mopen("ppg");
	out = mread(fd);
	printf(out);
	mclose(fd);

	ls();
	touch("hello.c");
	ls();

	fd = mopen("hello.c");
	out = mread(fd);
	printf(out);
	mclose(fd);

	fd = mopen("hello.c");
	mwrite(fd, "hello\nworld!\n");
	mclose(fd);

	fd = mopen("hello.c");
	out = mread(fd);
	mclose(fd);


	fd = mopen("ppg");
	out = mread(fd);
	printf(out);
	mclose(fd);


	umount();
	return 0;
}
/*--------------------------------------------------------------------------*/
types::Function::ReturnValue sci_mgetl(types::typed_list &in, int _iRetCount, types::typed_list &out)
{
    int iFileID                 = 0;
    int iErr                    = 0;
    bool bCloseFile             = false;
    int iLinesExcepted          = -1;
    int iLinesRead              = -1;
    wchar_t** wcReadedStrings   = NULL;

    if (in.size() < 1 || in.size() > 2)
    {
        Scierror(77, _("%s: Wrong number of input arguments: %d to %d expected.\n"), "mgetl" , 1, 2);
        return types::Function::OK;
    }

    if (in.size() == 2)
    {
        //number of lines
        if (in[1]->isDouble() == false)
        {
            Scierror(999, _("%s: Wrong type for input argument #%d: An integer value expected.\n"), "mgetl", 2);
            return types::Function::Error;
        }

        if (in[1]->getAs<types::Double>()->isScalar() == false)
        {
            Scierror(999, _("%s: Wrong size for input argument #%d: An integer value expected.\n"), "mgetl", 2);
            return types::Function::Error;
        }

        if (in[1]->getAs<types::Double>()->get(0) != (int)in[1]->getAs<types::Double>()->get(0))
        {
            Scierror(999, _("%s: Wrong value for input argument #%d: An integer value expected.\n"), "mgetl", 2);
            return types::Function::Error;
        }

        iLinesExcepted = static_cast<int>(in[1]->getAs<types::Double>()->get(0));
    }

    if (in[0]->isDouble() && in[0]->getAs<types::Double>()->getSize() == 1)
    {
        iFileID = static_cast<int>(in[0]->getAs<types::Double>()->get(0));
    }
    else if (in[0]->isString() && in[0]->getAs<types::String>()->getSize() == 1)
    {
        wchar_t *expandedFileName = expandPathVariableW(in[0]->getAs<types::String>()->get(0));

        iErr = mopen(expandedFileName, L"rt", 0, &iFileID);

        if (iErr)
        {
            char* pst = wide_string_to_UTF8(expandedFileName);
            switch (iErr)
            {
                case MOPEN_NO_MORE_LOGICAL_UNIT:
                    Scierror(66, _("%s: Too many files opened!\n"), "mgetl");
                    break;
                case MOPEN_CAN_NOT_OPEN_FILE:
                    Scierror(999, _("%s: Cannot open file %s.\n"), "mgetl", pst);
                    break;
                case MOPEN_NO_MORE_MEMORY:
                    Scierror(999, _("%s: No more memory.\n"), "mgetl");
                    break;
                case MOPEN_INVALID_FILENAME:
                    Scierror(999, _("%s: invalid filename %s.\n"), "mgetl", pst);
                    break;
                default: //MOPEN_INVALID_STATUS
                    Scierror(999, _("%s: invalid status.\n"), "mgetl");
                    break;
            }

            FREE(pst);
            FREE(expandedFileName);
            return types::Function::Error;
        }
        FREE(expandedFileName);
        bCloseFile = true;
    }
    else
    {
        //Error
        Scierror(999, _("%s: Wrong type for input argument #%d: a String or Integer expected.\n"), "mgetl", 1);
        return types::Function::Error;
    }

    switch (iFileID)
    {
        case 0: // stderr
        case 6: // stdout
            Scierror(999, _("%s: Wrong file descriptor: %d.\n"), "mgetl", iFileID);
            return types::Function::Error;
        default :
        {
            types::File* pFile = FileManager::getFile(iFileID);
            // file opened with fortran open function
            if (pFile == NULL || pFile->getFileType() == 1)
            {
                Scierror(999, _("%s: Wrong file descriptor: %d.\n"), "mgetl", iFileID);
                return types::Function::Error;
            }

            wcReadedStrings = mgetl(iFileID, iLinesExcepted, &iLinesRead, &iErr);

            switch (iErr)
            {
                case MGETL_MEMORY_ALLOCATION_ERROR :
                    break;

            }
        }
    }

    if (wcReadedStrings && iLinesRead > 0)
    {
        types::String *pS = new types::String(iLinesRead, 1);
        pS->set(wcReadedStrings);
        out.push_back(pS);
        freeArrayOfWideString(wcReadedStrings, iLinesRead);
    }
    else
    {
        out.push_back(types::Double::Empty());
        if (wcReadedStrings)
        {
            FREE(wcReadedStrings);
        }
    }

    if (bCloseFile)
    {
        mclose(iFileID);
    }

    return types::Function::OK;
}
Exemple #14
0
int main(int argc, char **argv)
{
	liao_log("liao_server", LOG_PID|LOG_NDELAY, LOG_MAIL);

	if (argc != 3) {
		usage(argv[0]);
		exit(0);
	}

	if (chdir(LIAO_HOME) == -1) {
		log_alert("cannot start: unable to switch to home directory");	
		exit(0);
	}

	snprintf(msg_id, sizeof(msg_id), "00000000");
	
	char cfg_file[MAX_LINE] = CFG_FILE;
	
	int c;
	const char *args = "c:h";
	while ((c = getopt(argc, argv, args)) != -1) {
		switch (c) {
			case 'c':
				snprintf(cfg_file, sizeof(cfg_file), "%s", optarg);
				break;
				
			case 'h':
			default:
				usage(argv[0]);
				exit(0);
		}
	}

	// 处理配置文件 
	if (conf_init(cfg_file)) {
		fprintf(stderr, "Unable to read control files:%s\n", cfg_file);
		log_error("Unable to read control files:%s", cfg_file);
		exit(1);
	}

	/*	
	// 检查队列目录
	if (strlen(config_st.queue_path) <= 0) {
		fprintf(stderr, "Unable to read queue path.\n");
		log_error("Unable to read queue path.");
		exit(1);
	}
	if ( access(config_st.queue_path, F_OK) ) {
		fprintf(stderr, "Queue path:%s not exists:%s, so create it.\n", config_st.queue_path, strerror(errno));	
		log_error("Queue path:%s not exists:%s, so create it.", config_st.queue_path, strerror(errno));	

		umask(0);
		mkdir(config_st.queue_path, 0777);
	}*/
	

	online_d = dictionary_new(atoi(config_st.max_works) + 1);
	

	child_st = (struct childs *)malloc((atoi(config_st.max_works) + 1) * sizeof(struct childs));
	if (!child_st) {
		log_error("malloc childs [%d] failed:[%d]%s", (atoi(config_st.max_works) + 1), errno, strerror(errno));
		exit(1);
	}
	
	int i = 0;
	for (i=0; i<(atoi(config_st.max_works) + 1); i++) {
		child_st[i].used = 0;
		child_st[i].pid = -1;
		child_st[i].client_fd = -1;
		child_st[i].pipe_r_in = -1;
		child_st[i].pipe_r_out = -1;
		child_st[i].pipe_w_in = -1;
		child_st[i].pipe_w_out = -1;
		memset(child_st[i].mid, 0, sizeof(child_st[i].mid));
		child_st[i].mfp_out = NULL;
	}

	// 开始服务
	int connfd, epfd, sockfd, n, nread;
	struct sockaddr_in local, remote;
	socklen_t addrlen;

	// 初始化buffer
	char buf[BUF_SIZE];

	size_t pbuf_len = 0;
	size_t pbuf_size = BUF_SIZE + 1;
	char *pbuf = (char *)calloc(1, pbuf_size);
	if (pbuf == NULL) {
		log_error("calloc fail: size[%d]", pbuf_size);
		exit(1);
	}

	// 创建listen socket
	int bind_port = atoi(config_st.bind_port);
	if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		log_error("socket failed:[%d]:%s", errno, strerror(errno));
		exit(1);
	}
	if (setnonblocking(listenfd) > 0) {
		exit(1);
	}

	bzero(&local, sizeof(local));
	local.sin_family = AF_INET;
	local.sin_addr.s_addr = htonl(INADDR_ANY);
	local.sin_port = htons(bind_port);
	if (bind(listenfd, (struct sockaddr *)&local, sizeof(local)) < 0) {
		log_error("bind local %d failed:[%d]%s", bind_port, errno, strerror(errno));
		exit(1);
	}
	log_info("bind local %d succ", bind_port);

	if (listen(listenfd, atoi(config_st.max_works)) != 0) {
		log_error("listen fd[%d] max_number[%d] failed:[%d]%s", listenfd, atoi(config_st.max_works), errno, strerror(errno));
		exit(1);
	}
	
	// 忽略pipe信号 
	sig_pipeignore();
	// 捕抓子进程退出信号
	sig_catch(SIGCHLD, sigchld);

	// epoll create fd
	epoll_event_num = atoi(config_st.max_works) + 1;
	epoll_evts = NULL;
	epoll_fd = -1;
	epoll_nfds = -1;

	int epoll_i = 0;

	epoll_evts = (struct epoll_event *)malloc(epoll_event_num * sizeof(struct epoll_event));
	if (epoll_evts == NULL) {
		log_error("alloc epoll event failed");
    	_exit(111);
    }

	epoll_fd = epoll_create(epoll_event_num);
	if (epoll_fd == -1) {
		log_error("epoll_create max_number[%d] failed:[%d]%s", epoll_event_num, errno, strerror(errno));
		exit(1);
	}

	struct epoll_event ev;
	ev.events = EPOLLIN;
	ev.data.fd = listenfd;
	if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, ev.data.fd, &ev) == -1) {
		log_error("epoll_ctl: listen_socket failed:[%d]%s", errno, strerror(errno));
		exit(1);
	}
	epoll_num_running = 1;

	for (;;) {

		epoll_nfds = epoll_wait(epoll_fd, epoll_evts, epoll_event_num, -1);
		
		if (epoll_nfds == -1) {
			if (errno == EINTR)	{
				// 收到中断信号
				log_info("epoll_wait recive EINTR signal, continue");
				continue;
			}

			_exit(111);
		}

		log_debug("epoll_num_running:%d nfds:%d", epoll_num_running, epoll_nfds);
		for (epoll_i = 0; epoll_i < epoll_nfds; epoll_i++) {
			sig_childblock();

			int evt_fd = epoll_evts[epoll_i].data.fd;
			if (evt_fd == listenfd) {
				if ((connfd = accept(listenfd, (struct sockaddr *) &remote, &addrlen)) > 0) {
					char *ipaddr = inet_ntoa(remote.sin_addr);
					log_info("accept client:%s", ipaddr);
					
					char greetting[512] = {0};
					char hostname[1024] = {0};
					if (gethostname(hostname, sizeof(hostname)) != 0) {
						snprintf(hostname, sizeof(hostname), "unknown");
					}

					// 取客户端IP,Port
					char client_ip[20] = {0};
					char client_port[20] = {0};
					struct sockaddr_in sa;
					int len = sizeof(sa);
					if (!getpeername(connfd, (struct sockaddr *)&sa, &len)) {
						snprintf(client_ip, sizeof(client_ip), "%s", inet_ntoa(sa.sin_addr));
						snprintf(client_port, sizeof(client_port), "%d", ntohs(sa.sin_port));
					}

					
					// 取一个新的client
					int i = new_idx_from_child_st();
					if (i == -1) {
						log_error("new_idx_from_client_st fail: maybe client queue is full.");

						// send error
						snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
						write(connfd, greetting, strlen(greetting));
						log_debug("send fd[%d]:%s", connfd, greetting);

						continue;		
					}
					child_st[i].used = 1;
					
					int pir[2];
					int piw[2];
					if (pipe(pir) == -1) {
						log_error("unable to create pipe:%s", strerror(errno));
					
						// send error
						snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
						write(connfd, greetting, strlen(greetting));
						log_debug("send fd[%d]:%s", connfd, greetting);
						
						continue;
					}
					if (pipe(piw) == -1) {
						log_error("unable to create pipe:%s", strerror(errno));

						close(pir[0]);
						close(pir[1]);
						pir[0] = -1;
						pir[1] = -1;

						// send error
                        snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
                        write(connfd, greetting, strlen(greetting));
                        log_debug("send fd[%d]:%s", connfd, greetting);

                        continue;
					}
					log_debug("create pir[0]:%d pir[1]:%d", pir[0], pir[1]);
					log_debug("create piw[0]:%d piw[1]:%d", piw[0], piw[1]);
					
					
					// 当程序执行exec函数时本fd将被系统自动关闭,表示不传递给exec创建的新进程
					//fcntl(pir[0], F_SETFD, FD_CLOEXEC);			
					//fcntl(piw[1], F_SETFD, FD_CLOEXEC);			

					int f = fork();
					if (f < 0) {
						log_error("fork fail:%s", strerror(errno));

						close(pir[0]);
						close(pir[1]);
						pir[0] = -1;
						pir[1] = -1;

						close(piw[0]);
						close(piw[1]);
						piw[0] = -1;
						piw[1] = -1;
						
						child_st[i].used = 0;

						// send error
                        snprintf(greetting, sizeof(greetting), "%s ERR %s%s", TAG_GREET, hostname, DATA_END);
                        write(connfd, greetting, strlen(greetting));
                        log_debug("send fd[%d]:%s", connfd, greetting);

                        continue;
					}

					struct timeval tm;
					gettimeofday(&tm, NULL);
					snprintf(child_st[i].mid, sizeof(child_st[i].mid), "%05u%u", (uint32_t)tm.tv_usec, (uint32_t)f);
					snprintf(msg_id, sizeof(msg_id), "%s", child_st[i].mid);

					if (f == 0) {
						// 子进程
						close(pir[0]);
						close(piw[1]);
						close(listenfd);

						char _cmid[512] = {0};
						char _cchild_st[512] = {0};
						char _ccip[20] = {0};
						char _ccport[20] = {0};

						snprintf(_cmid, sizeof(_cmid), "-m%s", child_st[i].mid);
						snprintf(_cchild_st, sizeof(_cchild_st), "-c%s", config_st.child_cf);
						snprintf(_ccip, sizeof(_ccip), "-i%s", client_ip);
						snprintf(_ccport, sizeof(_ccport), "-p%s", client_port);

						char *args[6];
						args[0] = "./liao_command";
						args[1] = _cmid;
						args[2] = _cchild_st;
						args[3] = _ccip;
						args[4] = _ccport;
						args[5] = 0;

						if (fd_move(0, connfd) == -1) {
							log_info("%s fd_move(0, %d) failed:%d %s", child_st[i].mid, connfd, errno, strerror(errno));
							_exit(111);
						}

						if (fd_move(1, pir[1]) == -1) {
							log_info("%s fd_move(pipe_w, %d) failed:%d %s", child_st[i].mid, pir[1], errno, strerror(errno));
							_exit(111);
						}
						if (fd_move(2, piw[0]) == -1) {
							log_info("%s fd_move(pipe_r, %d) failed:%d %s", child_st[i].mid, piw[0], errno, strerror(errno));
							_exit(111);
						}

						if (execvp(*args, args) == -1) {
							log_error("execp fail:%s", strerror(errno));
							_exit(111);
						}
						//if (error_temp(errno))
						//	_exit(111);
						log_debug("execp succ");
						_exit(100);							

					}

					close(connfd);
			
					child_st[i].pipe_r_in = pir[0];
					close(pir[1]);
					pir[1] = -1;
					child_st[i].pipe_r_out = -1;

					child_st[i].pipe_w_out = piw[1];
					close(piw[0]);
					piw[0] = -1;
					child_st[i].pipe_w_in = -1;


					child_st[i].pid = f;

					
					if (setnonblocking(child_st[i].pipe_r_in) != 0) {
						log_error("setnonblocking fd[%d] failed", child_st[i].pipe_r_in);
					}

					
					struct epoll_event pipe_in_ev;
					pipe_in_ev.events = EPOLLIN | EPOLLET;	
					pipe_in_ev.data.fd = child_st[i].pipe_r_in;
					if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, pipe_in_ev.data.fd, &pipe_in_ev) == -1) {
						log_error("epoll_ctl client fd[%d] EPOLL_CTL_ADD failed:[%d]%s", pipe_in_ev.data.fd, errno, strerror(errno));
					}
					log_debug("epoll_add fd[%d]", pipe_in_ev.data.fd);

					

				} else if (connfd == -1) {
					if (errno != EAGAIN && errno != ECONNABORTED && errno != EPROTO && errno != EINTR) {
						log_error("accept failed:[%d]%s", errno, strerror(errno));
					}

					continue;
				}

			} else if (epoll_evts[epoll_i].events & EPOLLIN) {
				
				int ci = get_idx_with_sockfd(evt_fd);
				if (ci < 0) {
					log_error("socket fd[%d] get_idx_with_sockfd fail", evt_fd);
					continue;
				}	
				log_debug("%s get event EPOLLIN: epoll_i[%d] fd[%d] get d_i[%d] fd[%d], used[%d]", child_st[ci].mid, epoll_i, epoll_evts[epoll_i].data.fd, child_st[ci].pipe_r_in, child_st[ci].used);

				// 读取内容 ----------------------
				char inbuf[BUF_SIZE] = {0};
				char *pinbuf = inbuf;
				int inbuf_size = BUF_SIZE;
				int inbuf_len = 0;
				char ch;
				
				
				do {
					i = 0;
					nread = read(child_st[ci].pipe_r_in, inbuf, inbuf_size);
					log_debug("%s read from liao_command:[%d]", child_st[ci].mid, nread);

					if (nread == -1) {
						// read error on a readable pipe? be serious
						//log_error("it is failed from fd[%d] read. error:%d %s", child_st[ci].fd_in, errno, strerror(errno));
						//log_debug("it is failed from fd[%d] read. error:%d %s", child_st[ci].pipe_r_in, errno, strerror(errno));
						break;

					} else if (nread > 0) {
						if (child_st[ci].mfp_out == NULL) {
							child_st[ci].mfp_out = mopen(MAX_BLOCK_SIZE, NULL, NULL);
							if (child_st[ci].mfp_out == NULL) {
								log_debug("%s mopen for body fail", child_st[ci].mid);
								break;
							}
						}	

						while (i < nread) {	
							ch = inbuf[i];	
							
							if ((inbuf_size - inbuf_len) < 2) {
								int r = fast_write(child_st[ci].mfp_out, inbuf, inbuf_len);
								if (r == 0) {
									log_error("%s fast_write fail", child_st[ci].mid);
									break;
								}	

								memset(inbuf, 0, inbuf_size);
								inbuf_len = 0;
							}	

							mybyte_copy(pinbuf + inbuf_len, 1, &ch);
							inbuf_len++;	

							if (ch == '\n') {
								if (inbuf_len > 0) {
									int r = fast_write(child_st[ci].mfp_out, inbuf, inbuf_len);
									if (r == 0) {
										log_error("%s fast_write fail", child_st[ci].mid);
										break;
									}

									memset(inbuf, 0, inbuf_size);
									inbuf_len = 0;
								}
								
								// 处理当前指令
								// ...
								process_system(&child_st[ci]);
								// ...
								
								// 处理完成后
								if (child_st[ci].mfp_out != NULL) {
									mclose(child_st[ci].mfp_out);
									child_st[ci].mfp_out = NULL;
									
									child_st[ci].mfp_out = mopen(MAX_BLOCK_SIZE, NULL, NULL);
									if (child_st[ci].mfp_out == NULL) {
										log_error("mopen fail for mfp_out");
										break;
									}
								}
								
								pinbuf = inbuf + 0;
							}

							i++;
						}
						
						
					} else {
						break;
					}

				} while (1);	


			} else if ((epoll_evts[epoll_i].events & EPOLLHUP) && (epoll_evts[epoll_i].data.fd != listenfd)) {

				int ci = get_idx_with_sockfd(evt_fd);
				if ( ci < 0 ) {
					log_error("get_idx_with_sockfd(%d) fail, so not write", evt_fd);

					continue;
				}
				log_debug("%s get event EPOLLHUP: epoll_i[%d] fd[%d] get d_i[%d] fd[%d], used[%d]", child_st[ci].mid, epoll_i, epoll_evts[epoll_i].data.fd, child_st[ci].pipe_r_in, child_st[ci].used);

				epoll_delete_evt(epoll_fd, child_st[ci].pipe_r_in);

				continue;

			}


		}
		sig_childunblock();

	}

	close(epoll_fd);
	close(listenfd);

	log_info("i'm finish");
    
	return 0;
}
Exemple #15
0
void mline ( int *np, int ix[], int iy[], int *iret )
/************************************************************************
 * mline								*
 *									*
 * This subroutine draws lines to the metafile.				*
 *									*
 * mline  ( np, ix, iy, iret )						*
 *									*
 * Input parameters:							*
 *	*np		int		Number of points		*
 *	ix[]		int		X coordinates 			*
 *	iy[]		int		Y coordinates 			*
 *                                                                      *
 * Output parameters:                                                   *
 *      *iret           int		Return code                     *
 *				  G_NMDATA = Too much data for metafile	*
 **                                                                     *
 * Log:									*
 * C. Lin/EAI		10/92						*
 * C. Lin/EAI		11/92	Add Header Information			*
 * C. Lin/EAI		 4/93	Add internal buffer			*
 * A. Chang/EAI          1/94	Modified to buffered I/O        	*
 * A. Chang/EAI          4/94						*
 * A. Chang/EAI          4/94	Elimated scaling code	        	*
 * S. Jacobs/NMC	 6/94	General clean up			*
 * L. Williams/EAI	 7/94	Reformat header				*
 * M. Linda/GSC		 6/96	Corrected check for too many points	*
 * A. Hardy/GSC	 	12/98	Change mcirc to mdots                   *
 ***********************************************************************/
{
	short	buffer[2048];
	short	colbuf[2];
	short	widbuf[2];
	short	nbyte;
	int	numbyte;
	int	i, k, ibyt, ier;

/*---------------------------------------------------------------------*/
	*iret = G_NORMAL;

/*
 *	Check for too many points.  Point count must fit into a short.
 */
	numbyte = (*np) * 2 * NUM_BTSZ;

	if ( numbyte > MAX_TWOBT ) {
	    *iret = G_NMDATA;
	    return;
	}

/*
 *	Open the file, if necessary.
 */
	if ( ! opnfil ) {
	    mopen ( &ier );
	    if ( ier != G_NORMAL ) {
		*iret = ier;
		return;
	    }
	}

/*
 *	Set line color.
 */
	if ( lcolor_req != lcolor_set ) {
	    lcolor_set = lcolor_req;

	    nbyte = 1 * NUM_BTSZ;
	    colbuf[0] = LINE_COLOR | nbyte;
	    colbuf[1] = (short) lcolor_set;
	    colbuf[1] <<= 8;

	    fwrite ( colbuf, NUM_BTSZ, 2, meta_fp );

	    byte_count += NUM_BTSZ * 2;
	}

/*
 *	Set line width.
 */

	if  ( lwidth_req != lwidth_set ) { 
	    lwidth_set = lwidth_req;

	    nbyte = 1 * NUM_BTSZ;
	    widbuf[0] = LINE_WIDTH | nbyte;
	    widbuf[1] = (short) lwidth_set;

	    fwrite ( widbuf, NUM_BTSZ, 2, meta_fp );

	    byte_count += NUM_BTSZ * 2;
	}

	if ( ( *np == 2 ) &&
	     ( ( ix[0] == ix[1] ) && ( iy[0] == iy[1] ) ) ) {
/*
 *	    Draw a circle.
 */
	    mdots ( ix, iy, &lwidth_set, &ier );

	}
	else {
/*
 *	    Draw a line.
 */
	    if ( numbyte < 31 ) {
	        buffer[0] = LINE | (short) numbyte;
	        ibyt = 1;
	    }
	    else {
	        buffer[0] = LINE | LONG_FORM;
	        buffer[1] = (short) numbyte;
	        ibyt = 2;
	    }

	    k = ibyt;
	    for ( i = 0; i < (*np); i++ ) {
	        buffer[k] = (short) ix[i];
	        k++;

	        buffer[k] = (short) iy[i];
	        k++;

	        if ( k >= 2048 ) {
		    fwrite ( buffer, NUM_BTSZ, k, meta_fp );
		    k = 0;
	        }
	    }

	    if ( k > 0 ) {
	        fwrite ( buffer, NUM_BTSZ, k, meta_fp );
	    }

	    byte_count += ( numbyte + ibyt * NUM_BTSZ );
	}

}
Exemple #16
0
static void *
_readfont(const char *name, size_t *szp, int warn)	/* create fitab and width tab for font */
{
	struct mfile *mp;
	int i, nw = 0, spacewidth, n = 0, v;
	char *ch, *cmd;
	char *cpout;

	if ((mp = mopen(name)) == NULL) {
		if (warn)
			errprint("Can't load font %s", name);
		return NULL;
	}
	for (i = 0; i < NFITAB; i++)
		fitab[i] = 0;
	for (i = 0; i < FSIZE; i++)
		width[i] = kern[i] = code[i] = 0;
	font.specfont = font.ligfont = spacewidth = 0;
	while ((cmd = sget(mp)) != NULL) {
		if (cmd[0] == '#')
			skipline(mp);
		else if (strcmp(cmd, "name") == 0) {
			if ((ch = sget(mp)) != NULL)
				strncpy(font.namefont, ch,
						sizeof font.namefont - 1);
		} else if (strcmp(cmd, "internalname") == 0) {
			if ((ch = sget(mp)) != NULL)
				strncpy(font.intname, ch,
						sizeof font.intname - 1);
		} else if (strcmp(cmd, "special") == 0)
			font.specfont = 1;
		else if (strcmp(cmd, "spare1") == 0)
			cget(mp);
		else if (strcmp(cmd, "ligatures") == 0) {
			font.ligfont = getlig(mp, warn);
		} else if (strcmp(cmd, "spacewidth") == 0) {
			dget(mp, &spacewidth);
			width[0] = spacewidth;	/* width of space on this font */
		} else if (strcmp(cmd, "charset") == 0) {
			skipline(mp);
			nw = 0;
			/* widths are origin 1 so fitab==0 can mean "not there" */
			while ((ch = sget(mp)) != NULL) {
				if (peek(mp) != '"') {	/* it's a genuine new character */
					nw++;
					dget(mp, &i);
					width[nw] = i;
					dget(mp, &i);
					kern[nw] = i;
					iget(mp, &i, 0);
					code[nw] = i;
				}
				/* otherwise it's a synonym for previous character,
				* so leave previous values intact
				*/
				if (strlen(ch) == 1)	/* it's ascii */
					fitab[ch[0] - 32] = nw;	/* fitab origin omits non-graphics */
				else if (strcmp(ch, "---") != 0) {	/* it has a 2-char name */
					for (i = 0; i < dev.nchtab; i++)
						if (strcmp(&chname[chtab[i]], ch) == 0) {
							fitab[i + 128-32] = nw;	/* starts after the ascii */
							break;
						}
					if (i >= dev.nchtab && warn)
						errprint("font %s: %s not in charset\n", name, ch);
				}
				skipline(mp);
			}
			nw++;
			if (dev.biggestfont >= nw)
				n = dev.biggestfont;
			else {
				if (dev.biggestfont > 0 && warn)
					errprint("font %s too big\n", name);
				n = nw;
			}
			font.nwfont = n;
		}
	}
	if (spacewidth == 0)
		width[0] = dev.res * dev.unitwidth / 72 / 3;

	cpout = calloc(1, sizeof font +
			sizeof *width * (font.nwfont & BYTEMASK) +
			sizeof *kern * (font.nwfont & BYTEMASK) +
			sizeof *code * (font.nwfont & BYTEMASK) +
			sizeof *fitab * dev.nchtab+128-32);
	memcpy(cpout, &font, sizeof font);
	v = sizeof font;
	memcpy(&cpout[v], width, sizeof *width * (font.nwfont & BYTEMASK));
	v +=  sizeof *width * (font.nwfont & BYTEMASK);
	memcpy(&cpout[v], kern, sizeof *kern * (font.nwfont & BYTEMASK));
	v += sizeof *kern * (font.nwfont & BYTEMASK);
	memcpy(&cpout[v], code, sizeof *code * (font.nwfont & BYTEMASK));
	v += sizeof *code * (font.nwfont & BYTEMASK);
	memcpy(&cpout[v], fitab, sizeof *fitab * dev.nchtab+128-32);
	v += sizeof *fitab * dev.nchtab+128-32;
	if (szp)
		*szp = v;
	mclose(mp);
	return cpout;
}
int main() 
{
 printf( "Content-Type: text/html\n\n" );
 //Reading post request from STDIN
 char *CGIargs = (char *)malloc(SIZE * sizeof(char));
 char *lenstr;
char input[SIZE], data[SIZE];
long len;
lenstr = getenv("CONTENT_LENGTH"); //Get the length
if(lenstr == NULL || sscanf(lenstr,"%ld",&len)!=1 || len > SIZE)
{
  printf("<P>Error ");
printf("<meta http-equiv=\"refresh\" content=\"0; url=../index.html\" />\n");
}
else {
	fgets(input, len+1, stdin); // put the stdin into input
  }
 strcpy(CGIargs,input); //rename
 if (CGIargs == NULL)
 {
	printf("Please use the form to access the site.\n Exiting...\n");
	printf("<meta http-equiv=\"refresh\" content=\"0; url=../index.html\" />\n");
 }
 char* CGIuser=(char*)malloc(SIZE * sizeof(char));
 char* CGIpass=(char*)malloc(SIZE * sizeof(char));
 //username=user&password=pass template
 if (sscanf(CGIargs, "username=%[0-9a-zA-Z]&password=%[0-9a-zA-Z]", CGIuser, CGIpass) != 2)
 {
	// If we do not get 2 parameters that are successfully assigned, return back
	printf("<meta http-equiv=\"refresh\" content=\"0; url=../index.html\" />\n");
 }
 if (getSize(CGIuser) >= 16 || getSize(CGIpass) >=16)
 {
		// If we start having too long input
		printf("Please use the form to access the site.\n Exiting...\n");
		printf("<meta http-equiv=\"refresh\" content=\"0; url=../index.html\" />\n");
 }
 FILE* fp=mopen();
 ///////////REAL HAX///////////
 char *RC4_CGIpass=(char*)malloc(getSize(CGIpass) * sizeof(char)); 
 strcpy(RC4_CGIpass,CGIpass);//rc4_e(CGIpass,sizeof(CGIpass))); //Encryption works fine EXCEPT when we have a 6 char string, so omit it
 char * CGI_ENC_U=(char *)malloc(getSize(CGIuser) * sizeof(char)); //We want the chars[], not the pointer 
 strcpy(CGI_ENC_U,B64E(CGIuser));	//Thus we copy the return into another mem address
 char * CGI_ENC_P=(char *)malloc(SIZE * sizeof(char));
 strcpy(CGI_ENC_P,B64E(RC4_CGIpass));
 int pass=getColumn(fp,2,CGI_ENC_P);
 fclose(fp);
 FILE* fp2=mopen();
 int user=getColumn(fp2,1,CGI_ENC_U);
 fclose(fp2);
  ////////TEST IF EQUAL////////
  if ( user == pass & user!=-1 && pass !=-1 ) //If both return the same line, and find something (i.e. not -1)
  {
/*We have this:
<form action="Feed.py" method="post">
<input type=”hidden” name=”username” value=”CGIuser”>
<input type="submit" value="Login">
</form>
*/	printf("<meta http-equiv=\"refresh\" content=\"0; url=MyFacebookPage.py?id=0&username=%s\" />\n",CGI_ENC_U);
  }
  else {
 //Either not found, or on different lines. In this case, make them try again
		//printf("<script>alert(\"%s\")</script>\n",CGI_ENC_P); For debugging
		printf("<meta http-equiv=\"refresh\" content=\"0; url=../index.html\" />\n");
  }
  return 0;
}
Exemple #18
0
void load_level( void )
{
	obj = OBJ_load( OBJ_FILE, 1 );

	unsigned int i = 0;

	while( i != obj->n_objmesh ) {
	
		OBJ_optimize_mesh( obj, i, 128 );

		OBJ_build_mesh( obj, i );
		
		OBJ_free_mesh_vertex_data( obj, i );

		++i;
	}
	
	
	init_physic_world();
	
	load_physic_world();
	
	gContactAddedCallback = contact_added_callback;
	
	
   OBJMESH *level_clear = OBJ_get_mesh( obj, "level_clear", 0 );

   level_clear->btrigidbody->setCollisionFlags( level_clear->btrigidbody->getCollisionFlags()  |
												btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK |
												btCollisionObject::CF_NO_CONTACT_RESPONSE );
   level_clear->visible = 0;

   i = 0;
   while( i != obj->n_objmesh ) { 

      OBJMESH *objmesh = &obj->objmesh[ i ];

      if( strstr( objmesh->name, "gem" ) ) { 

         objmesh->rotation.z = ( float )( random() % 360 );

         objmesh->btrigidbody->setCollisionFlags( objmesh->btrigidbody->getCollisionFlags() |
												  btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK );
      }
	  
	  ++i;
   }	
	
	
	player = OBJ_get_mesh( obj, "player", 0 );
	
	player->btrigidbody->setFriction( 6.7f );
	

	memcpy( &eye, &player->location, sizeof( vec3 ) );
	
	
	i = 0;
	while( i != obj->n_texture ) { 

		OBJ_build_texture( obj,
						   i,
						   obj->texture_path,
						   TEXTURE_MIPMAP ,
						   TEXTURE_FILTER_2X,
						   0.0f );
		++i;
	}


	i = 0;
	while( i != obj->n_program ) { 

		OBJ_build_program( obj,
						   i,
						   program_bind_attrib_location,
						   program_draw,
						   1,
						   obj->program_path );
		++i;
	}


	i = 0;
	while( i != obj->n_objmaterial ) { 

		OBJ_build_material( obj, i, NULL );
		
		++i;
	}	

	

	font_small = FONT_init( ( char * )"foo.ttf" );

	FONT_load( font_small,
			   font_small->name,
			   1,
			   24.0f,
			   512,
			   512,
			   32,
			   96 );
			   

	font_big = FONT_init( ( char * )"foo.ttf" );

	FONT_load( font_big,
			   font_big->name,
			   1,
			   48.0f,
			   512,
			   512,
			   32,
			   96 );
			   

	MEMORY *memory = NULL;

	i = 0;
	while( i != 4 ) {
	
		switch( i ) { 
		
			case 0: {

				memory = mopen( ( char * )"red.ogg", 1 );
				break;
			}
			case 1: {

				memory = mopen( ( char * )"green.ogg", 1 );
				break;
			}
			case 2: {

				memory = mopen( ( char * )"blue.ogg", 1 );
				break;
			}
			case 3: {

				memory = mopen( ( char * )"yellow.ogg", 1 );
				break;
			}
		}

		gems_soundbuffer[ i ] = SOUNDBUFFER_load( ( char * )"gem", memory );

		mclose( memory );
		
		gems_sound[ i ] =  SOUND_add( ( char * )"gem", gems_soundbuffer[ i ] );

		SOUND_set_volume( gems_sound[ i ], 1.0f );

		++i;
	}
	

	OBJMESH *objmesh = NULL;
	
	memory = mopen( ( char * )"water.ogg", 1 );

	water_soundbuffer = 
	SOUNDBUFFER_load( ( char * )"water", memory );

	mclose( memory );

	water_sound = SOUND_add( ( char * )"water", water_soundbuffer );

	objmesh = OBJ_get_mesh( obj, "water", 0 );

	SOUND_set_location( water_sound,
	&objmesh->location, 
	objmesh->radius );

	SOUND_set_volume( water_sound, 0.5f );

	SOUND_play( water_sound, 1 );


	memory = mopen( ( char * )"lava.ogg", 1 );
	
	lava_soundbuffer = SOUNDBUFFER_load( ( char * )"lava", memory );
	
	mclose( memory );
	
	lava_sound = SOUND_add( ( char * )"lava", lava_soundbuffer );

	objmesh = OBJ_get_mesh( obj, "lava", 0 );

	SOUND_set_location( lava_sound,
						&objmesh->location, 
						objmesh->radius );
						
	SOUND_set_volume( lava_sound, 0.5f );

	SOUND_play( lava_sound, 1 );


	memory = mopen( ( char * )"toxic.ogg", 1 );
	
	toxic_soundbuffer = SOUNDBUFFER_load( ( char * )"toxic", memory );

	mclose( memory );

	toxic_sound = SOUND_add( ( char * )"toxic", toxic_soundbuffer );
	
	objmesh = OBJ_get_mesh( obj, "toxic", 0 );

	SOUND_set_location( toxic_sound,
						&objmesh->location, 
						objmesh->radius );
	
	SOUND_set_volume( toxic_sound, 0.5f );
	
	SOUND_play( toxic_sound, 1 );


	memory = mopen( ( char * )"background.ogg", 1 );

	background_soundbuffer = SOUNDBUFFER_load_stream( ( char * )"background", memory );

	background_sound = SOUND_add( ( char * )"background", background_soundbuffer );
	
	SOUND_set_volume( background_sound, 0.5f );

	SOUND_play( background_sound, 1 );

	THREAD_play( thread );
}
Exemple #19
0
unsigned char FONT_load( FONT			*font,
						 char			*filename,
						 unsigned char	relative_path,
						 float			font_size,
						 unsigned int	texture_width,
						 unsigned int	texture_height,
						 int			first_character,
						 int			count_character )
{
	MEMORY *m = mopen( filename, relative_path );

	if( m )
	{
		unsigned char *texel_array = ( unsigned char * ) malloc( texture_width * texture_height );
		
		font->character_data = ( stbtt_bakedchar * ) malloc( count_character * sizeof( stbtt_bakedchar ) );
		
		font->font_size = font_size;
		
		font->texture_width = texture_width;
		
		font->texture_height = texture_height;
		
		font->first_character = first_character;
		
		font->count_character = count_character;
		
		stbtt_BakeFontBitmap( m->buffer,
							  0,
							  font_size,
							  texel_array,
							  texture_width,
							  texture_height,
							  first_character,
							  count_character,
							  font->character_data );

		mclose( m );
		
		glGenTextures(1, &font->tid );
		
		glBindTexture( GL_TEXTURE_2D, font->tid );
		
		glTexImage2D( GL_TEXTURE_2D,
					  0,
					  GL_ALPHA,
					  texture_width,
					  texture_height,
					  0,
					  GL_ALPHA,
					  GL_UNSIGNED_BYTE,
					  texel_array );
		
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
		
		free( texel_array );
	}
	
	return 0;
}
Exemple #20
0
void HandleTestKey(int key)
{
	switch (key) {

		case KEYDBGGED + KEY_0:
			ShowWeaponStatus ();   break;

#ifdef SHOW_EXIT_PATH
		case KEYDBGGED + KEY_1:
			MarkPathToExit ();
			break;
#endif

		case KEYDBGGED + KEY_Y:
			DoReactorDestroyedStuff(NULL);
			break;

	case KEYDBGGED + KEY_ALTED + KEY_D:
			networkData.nNetLifeKills=4000;
			networkData.nNetLifeKilled=5;
			MultiAddLifetimeKills ();
			break;

		case KEY_BACKSPACE:
		case KEY_CTRLED + KEY_BACKSPACE:
		case KEY_ALTED + KEY_BACKSPACE:
		case KEY_ALTED + KEY_CTRLED + KEY_BACKSPACE:
		case KEY_SHIFTED + KEY_BACKSPACE:
		case KEY_SHIFTED + KEY_ALTED + KEY_BACKSPACE:
		case KEY_SHIFTED + KEY_CTRLED + KEY_BACKSPACE:
		case KEY_SHIFTED + KEY_CTRLED + KEY_ALTED + KEY_BACKSPACE:
			Int3 ();
			break;

		case KEY_CTRLED + KEY_ALTED + KEY_ENTER:
			exit (0);
			break;

		case KEYDBGGED + KEY_S:
			audio.Reset ();
			break;

		case KEYDBGGED + KEY_P:
			if (gameStates.app.bGameSuspended & SUSP_ROBOTS)
				gameStates.app.bGameSuspended &= ~SUSP_ROBOTS;		//robots move
			else
				gameStates.app.bGameSuspended |= SUSP_ROBOTS;		//robots don't move
			break;


		case KEYDBGGED + KEY_K:
			LOCALPLAYER.shields = 1;
			MultiSendShields ();
			break;
						//	a virtual kill
		case KEYDBGGED + KEY_SHIFTED + KEY_K:
			LOCALPLAYER.shields = -1;
			MultiSendShields ();
			break;  //	an actual kill

		case KEYDBGGED + KEY_X:
			LOCALPLAYER.lives++;
			break; // Extra life cheat key.

		case KEYDBGGED + KEY_H:
//				if (!(gameData.app.nGameMode & GM_MULTI))   {
				LOCALPLAYER.flags ^= PLAYER_FLAGS_CLOAKED;
				if (LOCALPLAYER.flags & PLAYER_FLAGS_CLOAKED) {
					if (gameData.app.nGameMode & GM_MULTI)
						MultiSendCloak ();
					AIDoCloakStuff ();
					LOCALPLAYER.cloakTime = gameData.time.xGame;
#if TRACE
					console.printf (CON_DBG, "You are cloaked!\n");
#endif
				} else
#if TRACE
					console.printf (CON_DBG, "You are DE-cloaked!\n");
#endif
//				}
			break;


		case KEYDBGGED + KEY_R:
			gameStates.app.cheats.bRobotsFiring = !gameStates.app.cheats.bRobotsFiring;
			break;

		case KEYDBGGED + KEY_R + KEY_SHIFTED:
			KillAllRobots (1);
			break;

		//flythrough keys

#if DBG
		case KEYDBGGED + KEY_LAPOSTRO:
			showViewTextTimer = 0x30000;
			ObjectGotoNextViewer ();
			break;
		case KEYDBGGED + KEY_CTRLED + KEY_LAPOSTRO:
			showViewTextTimer = 0x30000;
			ObjectGotoPrevViewer ();
			break;
#endif
		case KEYDBGGED + KEY_SHIFTED + KEY_LAPOSTRO:
			gameData.objs.viewerP=gameData.objs.consoleP;
			break;

	#if DBG
		case KEYDBGGED + KEY_O:
			ToggleOutlineMode ();
			break;
	#endif
		case KEYDBGGED + KEY_T:
			*Toggle_var = !*Toggle_var;
#if TRACE
			console.printf (CON_DBG, "Variable at %08x set to %i\n", Toggle_var, *Toggle_var);
#endif
			break;
		case KEYDBGGED + KEY_L:
			if (++gameStates.render.nLighting >= 2)
				gameStates.render.nLighting = 0;
			break;
		case KEYDBGGED + KEY_SHIFTED + KEY_L:
			xBeamBrightness = 0x38000 - xBeamBrightness;
			break;
		case KEY_PAD5:
			slew_stop ();
			break;

		case KEYDBGGED  + KEY_F4: {
			//tCollisionData hitData;
			//CFixVector p0 = {-0x1d99a7, -0x1b20000, 0x186ab7f};
			//CFixVector p1 = {-0x217865, -0x1b20000, 0x187de3e};
			//FindHitpoint(&hitData, &p0, 0x1b9, &p1, 0x40000, 0x0, NULL, -1);
			break;
		}

		case KEYDBGGED + KEY_M:
			gameStates.app.bDebugSpew = !gameStates.app.bDebugSpew;
			if (gameStates.app.bDebugSpew) {
				mopen(0, 8, 1, 78, 16, "Debug Spew");
				HUDInitMessage("Debug Spew: ON");
			} else {
				mclose(0);
				HUDInitMessage("Debug Spew: OFF");
			}
			break;

		case KEYDBGGED + KEY_C:
			paletteManager.SaveEffectAndReset ();
			DoCheatMenu ();
			paletteManager.LoadEffect ();
			break;

		case KEYDBGGED + KEY_SHIFTED + KEY_A:
			DoMegaWowPowerup(10);
			break;

		case KEYDBGGED + KEY_A: {
			DoMegaWowPowerup(200);
//								if (gameData.app.nGameMode & GM_MULTI)     {
//									MsgBox(NULL, 1, "Damn", "CHEATER!\nYou cannot use the\nmega-thing in network mode.");
//									gameData.multigame.msg.nReceiver = 100;		// Send to everyone...
//									sprintf(gameData.multigame.msg.szMsg, "%s cheated!", LOCALPLAYER.callsign);
//								} else {
//									DoMegaWowPowerup ();
//								}
						break;
		}

		case KEYDBGGED + KEY_F:
		gameStates.render.bShowFrameRate = !gameStates.render.bShowFrameRate;
		break;

		case KEYDBGGED + KEY_SPACEBAR:		//KEY_F7:				// Toggle physics flying
			slew_stop ();
			GameFlushInputs ();
			if (gameData.objs.consoleP->info.controlType != CT_FLYING) {
				FlyInit(gameData.objs.consoleP);
				gameStates.app.bGameSuspended &= ~SUSP_ROBOTS;	//robots move
			} else {
				slew_init(gameData.objs.consoleP);			//start CPlayerData slewing
				gameStates.app.bGameSuspended |= SUSP_ROBOTS;	//robots don't move
			}
			break;

		case KEYDBGGED + KEY_COMMA:
			gameStates.render.xZoom = FixMul(gameStates.render.xZoom, 62259);
			break;
		case KEYDBGGED + KEY_PERIOD:
			gameStates.render.xZoom = FixMul(gameStates.render.xZoom, 68985);
			break;

		case KEYDBGGED + KEY_P + KEY_SHIFTED:
			Debug_pause = 1;
			break;

		case KEYDBGGED + KEY_B: {
			CMenu	m (1);
			char text [FILENAME_LEN] = "";
			int item;

			m.AddInput (text, FILENAME_LEN);
			item = m.Menu (NULL, "Briefing to play?");
			if (item != -1)
				briefing.Run (text, 1);
			break;
		}

		case KEYDBGGED + KEY_F5:
			ToggleMovieSaving ();
			break;

		case KEYDBGGED + KEY_SHIFTED + KEY_F5: {
			extern int Movie_fixed_frametime;
			Movie_fixed_frametime = !Movie_fixed_frametime;
			break;
		}

		case KEYDBGGED + KEY_ALTED + KEY_F5:
			gameData.time.xGame = I2X(0x7fff - 840);		//will overflow in 14 minutes
#if TRACE
			console.printf (CON_DBG, "gameData.time.xGame bashed to %d secs\n", X2I(gameData.time.xGame));
#endif
			break;

		case KEYDBGGED + KEY_SHIFTED + KEY_B:
			KillEverything (1);
			break;
	}
}
Exemple #21
0
/*--------------------------------------------------------------------------*/
fscanfMatResult *fscanfMat(char *filename, char *format, char *separator)
{
    int fd = 0;
    int f_swap = 0;
    double res = 0.0;
    int errMOPEN = MOPEN_INVALID_STATUS;
    int errMGETL = MGETL_ERROR;
    int i = 0;
    int nbLinesTextDetected = 0;
    int nbColumns = 0;
    int nbRows = 0;


    fscanfMatResult *resultFscanfMat = NULL;
    wchar_t **pwsLines = NULL;
    char **lines = NULL;
    int nblines = 0;
    double *dValues = NULL;
    wchar_t* filenameW = NULL;

    if ((filename == NULL) || (format == NULL) || (separator == NULL))
    {
        return NULL;
    }

    if (!checkFscanfMatFormat(format))
    {
        resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult)));
        if (resultFscanfMat)
        {
            resultFscanfMat->err = FSCANFMAT_FORMAT_ERROR;
            resultFscanfMat->m = 0;
            resultFscanfMat->n = 0;
            resultFscanfMat->sizeText = 0;
            resultFscanfMat->text = NULL;
            resultFscanfMat->values = NULL;
        }
        return resultFscanfMat;
    }

    filenameW = to_wide_string(filename);
    errMOPEN = mopen(filenameW, READ_ONLY_TEXT_MODE, f_swap, &fd);
    FREE(filenameW);
    if (errMOPEN != MOPEN_NO_ERROR)
    {
        resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult)));
        if (resultFscanfMat)
        {
            resultFscanfMat->err = FSCANFMAT_MOPEN_ERROR;
            resultFscanfMat->m = 0;
            resultFscanfMat->n = 0;
            resultFscanfMat->sizeText = 0;
            resultFscanfMat->text = NULL;
            resultFscanfMat->values = NULL;
        }
        return resultFscanfMat;
    }

    pwsLines = mgetl(fd, -1, &nblines, &errMGETL);
    mclose(fd);

    if (errMGETL != MGETL_NO_ERROR)
    {
        resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult)));
        if (resultFscanfMat)
        {
            resultFscanfMat->err = FSCANFMAT_READLINES_ERROR;
            resultFscanfMat->m = 0;
            resultFscanfMat->n = 0;
            resultFscanfMat->sizeText = 0;
            resultFscanfMat->text = NULL;
            resultFscanfMat->values = NULL;
        }
        return resultFscanfMat;
    }

    lines = (char**)MALLOC(sizeof(char*) * nblines);
    for (i = 0; i < nblines; i++)
    {
        lines[i] = wide_string_to_UTF8(pwsLines[i]);
    }

    freeArrayOfWideString(pwsLines, nblines);

    lines = removeEmptyLinesAtTheEnd(lines, &nblines);
    lines = removeTextLinesAtTheEnd(lines, &nblines, format, separator);

    nbLinesTextDetected = getNumbersLinesOfText(lines, nblines, format, separator);
    nbRows = nblines - nbLinesTextDetected;
    nbColumns = getNumbersColumnsInLines(lines, nblines, nbLinesTextDetected, format, separator);

    dValues = getDoubleValuesFromLines(lines, nblines,
                                       nbLinesTextDetected,
                                       format, separator,
                                       nbColumns, nbRows);
    if (dValues)
    {
        resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult)));
        if (resultFscanfMat)
        {
            if (nbLinesTextDetected > 0)
            {
                if (lines)
                {
                    for (i = nbLinesTextDetected; i < nblines; i++)
                    {
                        if (lines[i])
                        {
                            FREE(lines[i]);
                            lines[i] = NULL;
                        }
                    }
                }
                resultFscanfMat->text = lines;
            }
            else
            {
                freeArrayOfString(lines, nblines);
                resultFscanfMat->text = NULL;
            }
            resultFscanfMat->sizeText = nbLinesTextDetected;
            resultFscanfMat->m = nbRows;
            resultFscanfMat->n = nbColumns;
            resultFscanfMat->values = dValues;
            resultFscanfMat->err = FSCANFMAT_NO_ERROR;
        }
        else
        {
            FREE(dValues);
            freeArrayOfString(lines, nblines);
        }
    }
    else
    {
        freeArrayOfString(lines, nblines);
        if (nbColumns == 0 || nbRows == 0)
        {
            resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult)));
            if (resultFscanfMat)
            {
                resultFscanfMat->err = FSCANFMAT_READLINES_ERROR;
                resultFscanfMat->m = 0;
                resultFscanfMat->n = 0;
                resultFscanfMat->sizeText = 0;
                resultFscanfMat->text = NULL;
                resultFscanfMat->values = NULL;
            }
        }
    }
    return resultFscanfMat;
}
Exemple #22
0
types::Function::ReturnValue sci_mopen(types::typed_list &in, int _iRetCount, types::typed_list &out)
{
    int iErr                = 0;
    int iID                 = 0;
    wchar_t* pstFilename    = NULL;
    const wchar_t* pstMode  = L"rb";
    int iSwap               = 0;

    //check output parameters
    if (_iRetCount != 1 && _iRetCount != 2)
    {
        Scierror(78, _("%s: Wrong number of output argument(s): %d to %d expected.\n"), "mopen", 1, 2);
        return types::Function::Error;
    }

    //check input parameters
    if (in.size() >= 1)
    {
        //filename
        if (in[0]->isString() == false)
        {
            Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), "mopen", 1);
            return types::Function::Error;
        }

        types::String* pS1 = in[0]->getAs<types::String>();
        if (pS1->getSize() != 1)
        {
            Scierror(999, _("%s: Wrong size for input argument #%d: string expected.\n"), "mopen" , 1);
            return types::Function::Error;
        }

        pstFilename = expandPathVariableW(pS1->get(0));

        if (in.size() >= 2)
        {
            //mode
            if (in[1]->isString() == false)
            {
                Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), "mopen", 2);
                return types::Function::Error;
            }

            types::String* pS2 = in[1]->getAs<types::String>();
            if (pS2->getSize() != 1)
            {
                Scierror(999, _("%s: Wrong size for input argument #%d: string expected.\n"), "mopen" , 2);
                return types::Function::Error;
            }

            pstMode = pS2->get(0);

            if (in.size() >= 3)
            {
                //swap
                if (in[2]->isDouble() == false)
                {
                    Scierror(999, _("%s: Wrong type for input argument #%d: An integer expected.\n"), "mopen" , 3);
                    return types::Function::Error;
                }

                types::Double* pD3 = in[2]->getAs<types::Double>();
                if (pD3->getSize() != 1 || pD3->isComplex())
                {
                    Scierror(999, _("%s: Wrong size for input argument #%d: An integer expected.\n"), "mopen", 3);
                    return types::Function::Error;
                }

                //if value == 0 set swap to 0 otherwise let to 1
                if (pD3->getReal(0, 0) == 0)
                {
                    iSwap = 0;
                }

                if (in.size() >= 4)
                {
                    Scierror(999, _("%s: Wrong number of input arguments: %d to %d expected.\n"), "mopen" , 1, 3);
                    return types::Function::Error;
                }

            }
        }
    }
    else
    {
        Scierror(999, _("%s: Wrong number of input arguments: %d to %d expected.\n"), "mopen" , 1, 3);
        return types::Function::Error;
    }

    wchar_t* pwstTemp = (wchar_t*)MALLOC(sizeof(wchar_t) * (PATH_MAX * 2));
    get_full_pathW(pwstTemp, (const wchar_t*)pstFilename, PATH_MAX * 2);
    iErr = mopen(pwstTemp, pstMode, iSwap, &iID);
    if (iErr != MOPEN_NO_ERROR)
    {
        //mange file open errors
        if (_iRetCount == 1)
        {
            switch (iErr)
            {
                case MOPEN_CAN_NOT_OPEN_FILE:
                {
                    char* pst = wide_string_to_UTF8(pstFilename);
                    Scierror(999, _("%s: Cannot open file %s.\n"), "mopen", pst);
                    FREE(pst);
                    FREE(pstFilename);
                    FREE(pwstTemp);
                    pstFilename = NULL;
                    return types::Function::Error;
                }
                case MOPEN_INVALID_FILENAME:
                {
                    Scierror(999, _("%s: invalid filename.\n"), "mopen");
                    FREE(pstFilename);
                    FREE(pwstTemp);
                    pstFilename = NULL;
                    return types::Function::Error;
                }
                case MOPEN_INVALID_STATUS:
                {
                    Scierror(999, _("%s: invalid status.\n"), "mopen");
                    FREE(pstFilename);
                    FREE(pwstTemp);
                    pstFilename = NULL;
                    return types::Function::Error;
                }
            }
        }
    }

    FREE(pwstTemp);
    FREE(pstFilename);

    types::Double* pD = new types::Double(static_cast<double>(iID));
    out.push_back(pD);

    if (_iRetCount == 2)
    {
        types::Double* pD2 = new types::Double(iErr);
        out.push_back(pD2);
    }
    return types::Function::OK;
}
Exemple #23
0
// =============================================================================
csvResult* csvRead(const char *filename, const char *separator, const char *decimal, const char **toreplace, int sizetoreplace, const char *regexpcomments, int header)
{
    wchar_t *expandedFilename = NULL;
    wchar_t *wideFilename = NULL;
    csvResult *result = NULL;
    int fd = 0;
    int f_swap = 0;
    double res = 0.0;
    int errMOPEN = MOPEN_INVALID_STATUS;
    int errMGETL = MGETL_ERROR;
    wchar_t **pwstLines = NULL;
    char **pstLines = NULL;
    int nblines = 0;
    char **replacedInLines = NULL;
    char **pComments = NULL;
    int nbComments = 0;

    if ((filename == NULL) || (separator == NULL) || (decimal == NULL))
    {
        return NULL;
    }

    wideFilename = to_wide_string((char*)filename);
    expandedFilename = expandPathVariableW(wideFilename);
    FREE(wideFilename);

    if (!FileExistW(expandedFilename))
    {
        result = (csvResult*)(MALLOC(sizeof(csvResult)));
        if (result)
        {
            result->err = CSV_READ_FILE_NOT_EXIST;
            result->m = 0;
            result->n = 0;
            result->pstrValues = NULL;
            result->pstrComments = NULL;
            result->nbComments = 0;
        }

        FREE(expandedFilename);
        return result;
    }

    errMOPEN = mopen(expandedFilename, L"rt", f_swap, &fd); // rt = read only
    if (expandedFilename)
    {
        FREE(expandedFilename);
        expandedFilename = NULL;
    }

    if (errMOPEN != MOPEN_NO_ERROR)
    {
        result = (csvResult*)(MALLOC(sizeof(csvResult)));
        if (result)
        {
            result->err = CSV_READ_MOPEN_ERROR;
            result->m = 0;
            result->n = 0;
            result->pstrValues = NULL;
            result->pstrComments = NULL;
            result->nbComments = 0;

        }
        return result;
    }

    if (header != 0)
    {
        mgetl(fd, header, &nblines, &errMGETL);
    }

    pwstLines = mgetl(fd, -1, &nblines, &errMGETL);
    pstLines = (char**)MALLOC(sizeof(char*) * nblines);

    {
        int i = 0;
        for (i = 0 ; i < nblines ; i++)
        {
            pstLines[i] = wide_string_to_UTF8(pwstLines[i]);
        }

    }

    mclose(fd);

    if (errMGETL != MGETL_NO_ERROR)
    {
        if (pwstLines)
        {
            freeArrayOfWideString(pwstLines, nblines);
            pwstLines = NULL;
        }

        result = (csvResult*)(MALLOC(sizeof(csvResult)));
        if (result)
        {
            result->err = CSV_READ_READLINES_ERROR;
            result->m = 0;
            result->n = 0;
            result->pstrValues = NULL;
            result->pstrComments = NULL;
            result->nbComments = 0;
        }
        return result;
    }

    if (regexpcomments)
    {
        int iErr = 0;

        pComments = extractComments((const char**)pstLines, nblines, regexpcomments, &nbComments, &iErr);

        if ((iErr == CAN_NOT_COMPILE_PATTERN) || (iErr == DELIMITER_NOT_ALPHANUMERIC))
        {
            result = (csvResult*)(MALLOC(sizeof(csvResult)));
            if (result)
            {
                if ((iErr == CAN_NOT_COMPILE_PATTERN) || (iErr == DELIMITER_NOT_ALPHANUMERIC))
                {
                    iErr = CSV_READ_REGEXP_ERROR;
                }
                result->err = (csvReadError)iErr;
                result->m = 0;
                result->n = 0;
                result->pstrValues = NULL;
                result->pstrComments = NULL;
                result->nbComments = 0;
            }
            return result;
        }

        if (pComments)
        {
            char **pCleanedLines = NULL;
            int nbCleanedLines = 0;
            int i = 0;

            pCleanedLines = removeComments((const char**)pstLines, nblines, (const char*)regexpcomments, &nbCleanedLines, &iErr);
            if (pCleanedLines)
            {
                if (pwstLines)
                {
                    freeArrayOfWideString(pwstLines, nblines);
                    pwstLines = NULL;
                }
                FREE(pstLines);
                pstLines = pCleanedLines;
                nblines = nbCleanedLines;
            }

        }
    }

    if (toreplace && (sizetoreplace > 0))
    {
        replacedInLines = replaceStrings((const char**)pstLines, nblines, toreplace, sizetoreplace);
        if (replacedInLines)
        {
            freeArrayOfString(pstLines, nblines);
            pstLines = replacedInLines;
        }
    }

    result = csvTextScan((const char**)pstLines, nblines, (const char*)separator, (const char*)decimal);
    freeArrayOfString(pstLines, nblines);
    freeArrayOfWideString(pwstLines, nblines);

    if (result)
    {
        result->pstrComments = pComments;
        result->nbComments = nbComments;
    }
    else
    {
        freeArrayOfString(pComments, nbComments);
    }


    return result;
}
int main (int argc, char *argv[])
{

    int my_rank, proc_num;
    MPI_Status status;
    MPI_Init(&argc, &argv);

    MPI_Comm_size(MPI_COMM_WORLD, &proc_num);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    double diff;  /* change in value */
    int    i, j, m, n;
    int N=DEFAULT_N;
    double epsilon=0.01;
    double mean;
    FILE *fp;

    /* Argument processing */
    int edgeElems = DEFAULT_ELEM; /* edge elements */
    int cfreq = DEFAULT_FREQ; /* checkpoint frequency */
    char *cpath = DEFAULT_PATH; /* checkpoint path */
    int nok = 0; /* arguments not OK */
    int pinit=1;

    char *s;
    while (--argc > 0 && (*++argv)[0] == '-') {
        for(s=argv[0]+1;*s;s++)
        switch (*s) {
        case 'd':
            if (isdigit(s[1]))
                edgeElems = atoi(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        case 'c':
            if (isdigit(s[i]))
                cfreq = atoi(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        case 'p':
            cpath = s+1;
            s+=strlen(s+1);
            break;
        case 'r':
            pinit = 0;
            break;
        case 'n':
            if (isdigit(s[1])) 
                N = atoi(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        case 'e':
            if (isdigit(s[1]))
                epsilon = atof(s+1);
            else
                nok = 1;
            s+=strlen(s+1);
            break;
        default:
            nok = 1;
            break;
        }
    }

    if (nok) {
        fprintf(stderr, "Usage: %s -e<int> -c<int> -p<str> -r -n<int> -epsilon<double>\n", argv[0]);
        fprintf(stderr, "  -d  edge elements, default: %d\n", DEFAULT_ELEM);
        fprintf(stderr, "  -c  checkpoint frequency, default: %d\n", DEFAULT_FREQ);
        fprintf(stderr, "  -p  path to checkpoint file, default: %s\n", DEFAULT_PATH);
        fprintf(stderr, "  -r  restore\n");
        fprintf(stderr, "  -n  size of n, default:1000\n");
        fprintf(stderr, "  -e  epsilon, default:0.01\n");

        exit(EXIT_FAILURE);
    }

#ifdef DEBUG
    if(my_rank==0)
        printf("n=%d, epsilon=%lf\n", N, epsilon);
#endif

	if(N>1000){
		printf("Too big value for N, use no more than 1000, or change DEFAULT_N\n");
		return 0;
	}
   // Persistent memory initialization 
   const char *mode = (pinit) ? "w+" : "r+";
   char back_fname[128];
   char my_rank_str[4];
   perm(PERM_START, PERM_SIZE);
   strcpy(back_fname, cpath);
   strcat(back_fname,"hw5_mpi.back.");
   sprintf(my_rank_str, "%d", my_rank);
   strcat(back_fname,my_rank_str);
//   printf("mopen: %s\n", back_fname);
   mopen(back_fname, mode, MMAP_SIZE);
   strcpy(back_fname, cpath);
   strcat(back_fname,"hw5_mpi.mmap.");
   strcat(back_fname,my_rank_str);
//   printf("bopen: %s\n", back_fname);
   bopen(back_fname, mode);



   if (!pinit){ 
       restore();

       printf("Resotored, iter=%d, myN=%d\n", iter, myN);
   }
   else{

       iter = 0;
        /* Set boundary values and compute mean boundary value */
        mean = 0.0;
        for (i=0; i<N; i++) {
            u[i][0] = u[i][N-1] = u[0][i] = 100.0;
            u[N-1][i] = 0.0;
            mean += u[i][0] + u[i][N-1] + u[0][i] + u[N-1][i];
        }
        mean /= (4.0 *N);
    
        /* Initialize interior values */
        for (i =1; i<N-1; i++)
            for (j=1; j<N-1; j++)
                u[i][j] = mean;
    
    
        // distribute data 
        myN = N / proc_num;
        if(N%proc_num!=0){
            if(my_rank==proc_num-1)
                myN=N-(proc_num-1)*myN;
        }
        if(proc_num > 1) {
            // ghost rows
            if(my_rank == 0 || my_rank == proc_num - 1)
                myN++;
            else
                myN += 2;
        }
    
        // initial value
        for(i = 0; i < myN; i++) {
            for(j = 0; j < N; j++) {
                if(my_rank == 0)
                    myu[i][j] = u[i][j];
                else
                    myu[i][j] = u[my_rank*(N/proc_num)-1+i][j];
        
                myw[i][j]=myu[i][j];
            }
        }
        
        mflush();
        backup();
   }
    struct timeval start_tv, end_tv;
    gettimeofday(&start_tv, NULL);

    double alldiff=0;
    int left  = my_rank - 1;
    int right = my_rank +1;
    MPI_Request send_req1, recv_req1;
    MPI_Request send_req2, recv_req2;
    while(1)
    {
        iter++;

        diff = 0.0;
        for (i=1; i<myN-1; i++) {
            for (j=1; j<N-1; j++) {
                myw[i][j] = (myu[i-1][j] + myu[i+1][j] + myu[i][j-1] + myu[i][j+1])/4.0;
                if (fabs (myw[i][j] - myu[i][j]) > diff)
                    diff = fabs(myw[i][j] - myu[i][j]);
            }
        }

        // reduce diff
        MPI_Allreduce(&diff, &alldiff, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
        #ifdef PRINTITER
        if(my_rank==0){
            printf("iter=%d, diff=%lf\n", iter, alldiff);
            fflush(stdout);
        }
        #endif

        if (alldiff <= epsilon)
            break;


        if(proc_num > 1) {

            // send second top row
            if(my_rank != 0){ 
                MPI_Isend(myw[1], N, MPI_DOUBLE, left, 0, MPI_COMM_WORLD, &send_req1);
                //printf("Send: %d->%d\n", my_rank, left);
            }
            // send second to bottom row
            if(my_rank != proc_num - 1){ 
                MPI_Isend(myw[myN-2], N, MPI_DOUBLE, right, 1, MPI_COMM_WORLD, &send_req2);
                //printf("Send %d->%d\n", my_rank, right);
            }
            
            // recive top
            if(my_rank != 0){ 
                MPI_Irecv(myw[0], N, MPI_DOUBLE, left, 1, MPI_COMM_WORLD, &recv_req1);
                //printf("Recv: %d->%d\n", my_rank, left);
            }

            // receive bottom
            if(my_rank != proc_num - 1) {
                MPI_Irecv(myw[myN-1], N, MPI_DOUBLE, right, 0, MPI_COMM_WORLD, &recv_req2);
                //printf("Recv %d->%d\n", my_rank, right);
            }

            if(my_rank != 0) 
                MPI_Wait(&send_req1, &status);
            if(my_rank != proc_num - 1) 
                MPI_Wait(&send_req2, &status);
            if(my_rank != 0) 
                MPI_Wait(&recv_req1, &status);
            if(my_rank != proc_num - 1) 
                MPI_Wait(&recv_req2, &status);
        }
        
        for (i=0; i<myN; i++) {
            if( (i==0&&my_rank==0) ||(i==myN-1&&my_rank==proc_num-1))
                continue;
            for (j=1; j<N-1; j++)
                myu[i][j] = myw[i][j];
        }
        
        // backup
        if(iter%cfreq == 0)
            backup();
    }

    gettimeofday(&end_tv, NULL);
    printf("Elapsed time: %f sec\n",
           (double)( (double)(end_tv.tv_sec - start_tv.tv_sec) + ( (double)(end_tv.tv_usec - start_tv.tv_usec)/1000000)) );

    // gather data
    if(my_rank==0) {
        for (i=0; i<myN; i++) {
            for(j=0; j<N; j++) {
                u[i][j] = myu[i][j];
            }
        }

        if(proc_num > 1) {
            for (i=1; i<proc_num-1; i++) 
                MPI_Recv(u[i*(N/proc_num)], (N/proc_num)*N, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &status);

            // special care for last one
            if(N%proc_num==0)
                MPI_Recv(u[i*(N/proc_num)], (N/proc_num)*N, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &status);
            else{
                MPI_Recv(u[i*(N/proc_num)], (N-(N/proc_num)*(proc_num-1))*N, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &status);
            }
        }
    }
    else {
            if(N%proc_num==0)
                MPI_Send(myu[1], (N/proc_num)*N, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
            else{
                if(my_rank != proc_num-1)
                    MPI_Send(myu[1], (myN-2)*N, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
                else
                    MPI_Send(myu[1], (myN-1)*N, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
            }
    }


    if(my_rank == 0) {

        /* Print Solution */
        fp = fopen("output.dat", "w");
        for (i=0; i<N; i++) {
            for (j=0; j<N; j++) {
                fprintf(fp, "%6.2f ", u[i][j]);
            }
            fprintf(fp, "\n");
        }
        fclose(fp);

    }
	mclose();
	bclose();
    MPI_Finalize();
    return 0;
}
Exemple #25
0
int
main(int argc, char *argv[])
{
    int mtype, size, c,
	list = FALSE, limit = -1, deflt = -1;
    int fd;
    char *userlist = 0, *user, **users, *p;
    short status;
    struct user_priority *ppri_tbl, *ld_priority_file();
    extern char *optarg;
    extern int optind, opterr, optopt, errno;

    setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)
#define TEXT_DOMAIN "SYS_TEST"
#endif
    (void) textdomain(TEXT_DOMAIN);


    if(argc == 1) {
usage:
	(void) printf(gettext("usage: \n"));	
  	(void) printf(gettext("(assign priority limit to users)\n"));
	(void) printf(gettext("\tlpusers -q priority -u user-list\n"));

  	(void) printf(gettext(
		"(assign default priority limit for balance of users)\n"));
	(void) printf(gettext("\tlpusers -q priority\n"));

  	(void) printf(gettext("(put users back to default priority limit)\n"));
	(void) printf(gettext("\tlpusers -u user-list\n"));

  	(void) printf(gettext("(assign default priority)\n"));
	(void) printf(gettext("\tlpusers -d priority\n"));

  	(void) printf(gettext("(examine priority limits, defaults)\n"));
	(void) printf(gettext("\tlpusers -l\n"));

	exit(argc == 1);
    }

    opterr = 0; /* disable printing of errors by getopt */
    while ((c = getopt(argc, argv, "ld:q:u:")) != -1)
	switch(c) {
	case 'l':
	    if (list)
		LP_ERRMSG1(WARNING, E_LP_2MANY, 'l');
	    list = TRUE;
	    break;
	case 'd':
	    if (deflt != -1)
		LP_ERRMSG1(WARNING, E_LP_2MANY, 'd');
	    deflt = (int)strtol(optarg,&p,10);
	    if (*p || deflt<PRI_MIN || deflt>PRI_MAX) {
		LP_ERRMSG1(ERROR, E_LP_BADPRI, optarg);
		exit(1);
	    }
	    break;
	case 'q':
	    if (limit != -1)
		LP_ERRMSG1(WARNING, E_LP_2MANY, 'q');
	    limit = (int)strtol(optarg,&p,10);
	    if (*p || limit<PRI_MIN || limit>PRI_MAX) {
		LP_ERRMSG1(ERROR, E_LP_BADPRI, optarg);
		exit(1);
	    }
	    break;
	case 'u':
	    if (userlist)
		LP_ERRMSG1(WARNING, E_LP_2MANY, 'u');
	    userlist = optarg;
	    break;
	case '?':
	    if (optopt == '?') goto usage;
	    (p = "-X")[1] = optopt;
	    if (strchr("ldqu", optopt))
		LP_ERRMSG1(ERROR, E_LP_OPTARG, p);
	    else
		LP_ERRMSG1(ERROR, E_LP_OPTION, p);
	    exit(1);
	}

    if (optind < argc) {
	LP_ERRMSG1(ERROR, E_LP_EXTRA, argv[optind]);
	exit(1);
    }

    if (((list || deflt != -1) && (limit != -1 || userlist))
	|| (list && deflt != -1)) {
	LP_ERRMSG(ERROR, E_LP_OPTCOMB);
	/* invalid combination of options */
	exit(1);
    }

    PRIORITY = Lp_Users;

    /* load existing priorities from file */
    if (!(ppri_tbl = ld_priority_file(PRIORITY))) {
	switch (errno) {
	case EBADF:
	    LP_ERRMSG1(ERROR, E_LPU_BADFORM, PRIORITY);
	    break;
	default:
	    LP_ERRMSG2(ERROR, E_LPU_BADFILE, PRIORITY, errno);
	}
	exit(1);
    }

    if (list) {
	print_tbl(ppri_tbl);
	exit (0);
    } else {
	if (userlist) {
	    users = getlist(userlist, " \t", ",");
	    if (users)
		while (user = *users++) {
		    if (del_user(ppri_tbl, user) && (limit == -1))
			LP_ERRMSG1(WARNING, E_LPU_NOUSER, user);
		    if (limit != -1) {
			if (add_user(ppri_tbl, user, limit))
			    LP_ERRMSG1(WARNING, E_LPU_BADU, user);
		    }
		}
	} else if (deflt != -1)
	    ppri_tbl->deflt = deflt;
	else
	    ppri_tbl->deflt_limit = limit;

	if ((fd = open_locked(PRIORITY, "w", LPU_MODE)) < 0) {
	    LP_ERRMSG1(ERROR, E_LP_ACCESS, PRIORITY);
	    exit(1);
	}
	output_tbl(fd, ppri_tbl);
	close(fd);
    }

    if (mopen()) /* error on mopen == no spooler, exit quietly */
	exit(0);

    (void)putmessage (message, S_LOAD_USER_FILE);

    if (msend(message))
	goto Error;
    if (mrecv(reply, sizeof(reply)) == -1)
	goto Error;
    mtype = getmessage(reply, R_LOAD_USER_FILE, &status);
    if (mtype != R_LOAD_USER_FILE) {
	LP_ERRMSG1 (ERROR, E_LP_BADREPLY, mtype);
	goto NoError;
    }

    if (status == 0)
	goto NoError;

Error:	LP_ERRMSG (ERROR, E_LPU_NOLOAD);

NoError:(void)mclose ();
    return (0);
}
Exemple #26
0
void write_brlan(char *infile, char* outfile)
{
    int i;
    for(i = 0; i < 16; i++)
        memset(tag_types_list[i], 0, 24);
    strcpy(tag_types_list[0], "X Translation");
    strcpy(tag_types_list[1], "Y Translation");
    strcpy(tag_types_list[2], "Z Translation");
    strcpy(tag_types_list[3], "0x03");
    strcpy(tag_types_list[4], "0x04");
    strcpy(tag_types_list[5], "Angle");
    strcpy(tag_types_list[6], "X Zoom");
    strcpy(tag_types_list[7], "Y Zoom");
    strcpy(tag_types_list[8], "Width");
    strcpy(tag_types_list[9], "Height");
    strcpy(tag_types_list[10], "0x0A");
    strcpy(tag_types_list[11], "0x0B");
    strcpy(tag_types_list[12], "0x0C");
    strcpy(tag_types_list[13], "0x0D");
    strcpy(tag_types_list[14], "0x0E");
    strcpy(tag_types_list[15], "0x0F");
    FILE* fpx = fopen(infile, "r");
    if(fpx == NULL) {
        printf("xmlan couldn't be opened!\n");
        exit(1);
    }
    mxml_node_t *hightree = mxmlLoadFile(NULL, fpx, MXML_TEXT_CALLBACK);
    if(hightree == NULL) {
        printf("Couldn't open hightree!\n");
        exit(1);
    }
    mxml_node_t *tree = mxmlFindElement(hightree, hightree, "xmlan", NULL, NULL, MXML_DESCEND);
    if(hightree == NULL) {
        printf("Couldn't get tree!\n");
        exit(1);
    }
    mxml_node_t *node;
    FILE* fp = fopen(outfile, "wb+");
    if(fpx == NULL) {
        printf("destination brlan couldn't be opened!\n");
        exit(1);
    }
    u16 blobcount = 0;
    u32 bloboffset;
    brlan_header rlanhead;
    rlanhead.magic[0] = 'R';
    rlanhead.magic[1] = 'L';
    rlanhead.magic[2] = 'A';
    rlanhead.magic[3] = 'N';
    rlanhead.unk1 = 0xFEFF0008;
    rlanhead.file_size = 0;
    rlanhead.pai1_offset = sizeof(brlan_header);
    rlanhead.pai1_count = 1;
    WriteBRLANHeader(rlanhead, fp);
    brlan_pai1_header_type1 paihead;
    paihead.magic[0] = 'p';
    paihead.magic[1] = 'a';
    paihead.magic[2] = 'i';
    paihead.magic[3] = '1';
    paihead.size = 0;
    char temp[256];
    if(mxmlElementGetAttr(tree, "framesize") != NULL)
        strcpy(temp, mxmlElementGetAttr(tree, "framesize"));
    else{
        printf("No framesize attribute found!\nDefaulting to 20.");
        strcpy(temp, "20");
    }    
    paihead.framesize = atoi(temp);
    memset(temp, 0, 256);
    if(mxmlElementGetAttr(tree, "flags") != NULL)
    {
        strcpy(temp, mxmlElementGetAttr(tree, "flags"));
    } else {
        printf("No flags attribute found!\nDefaulting to 1.");
        paihead.flags = 1;
    }
    paihead.flags = atoi(temp);
    paihead.unk1 = 0;
    paihead.num_timgs = 0;
    paihead.num_entries = 0;
    paihead.entry_offset = sizeof(brlan_pai1_header_type1);
    WriteBRLANPaiHeader(paihead, fp);

    u8* tagchunksbig = (u8*)calloc(MAXIMUM_TAGS_SIZE, 1);
    MEMORY* tagsmem = mopen(tagchunksbig, MAXIMUM_TAGS_SIZE, 3);
    u32 totaltagsize = 0;

    u32 headerOffset;
    u32 tagsbigOffset;
    u32 blobOffsets[256];
    u8* timgblob;
    u32 timgsize;
    u16 timgcount = 0;
    u32 timgoffset;
    u8* timgchunksbig = (u8*)calloc(MAXIMUM_TIMGS_SIZE, 1);
    MEMORY* timgmem = mopen(timgchunksbig, MAXIMUM_TIMGS_SIZE, 3);
    u32 totaltimgize = 0;
    u32 timgStartOffset = ftell(fp);
    u32 timgOffsets[256];
    
    u32 timgnumber = 0x0;
    for(node = mxmlFindElement(tree, tree, "timg", NULL, NULL, MXML_DESCEND); node != NULL; node = mxmlFindElement(node, tree, "timg", NULL, NULL, MXML_DESCEND))
    {
    	timgnumber++;
	}
    u32 imageoffsets[timgnumber];
	u32 imagefileoffset = ftell(fp);
	for( i = 0; i < timgnumber; i++) imageoffsets[i] = imagefileoffset;
    WriteBRLANOffsets(imageoffsets, timgnumber, fp);
    
    for(node = mxmlFindElement(tree, tree, "timg", NULL, NULL, MXML_DESCEND); node != NULL; node = mxmlFindElement(node, tree, "timg", NULL, NULL, MXML_DESCEND)) {
        timgcount++;
		imageoffsets[timgcount-1] = ftell(fp) - imageoffsets[timgcount-1];
        if(mxmlElementGetAttr(node, "name") != NULL)
            strcpy(temp, mxmlElementGetAttr(node, "name"));
        else{
            printf("No name attribute found!\n");
            exit(1);
        }
		fwrite(temp, strlen(temp) + 1, 1, fp);
        totaltimgize += strlen(temp) + 1;
    }
    if ((totaltimgize % 4) != 0)
    {
    	u8 blank[3] = {0x0, 0x0, 0x0};
    	fwrite(blank, (4 - (totaltimgize % 4)), 1, fp);
    	totaltimgize += (4 - (totaltimgize % 4));
    }
    u32 tempoOffset = ftell(fp);
    fseek(fp, imagefileoffset, SEEK_SET);
    WriteBRLANOffsets(imageoffsets, timgnumber, fp);
    fseek(fp, tempoOffset, SEEK_SET);

	u32 panecount = 0x0;
	for(node = mxmlFindElement(tree, tree, "pane", NULL, NULL, MXML_DESCEND); node != NULL; node = mxmlFindElement(node, tree, "pane", NULL, NULL, MXML_DESCEND))
	{
		panecount++;
	}
	u32 paneoffsets[panecount];
	u32 tagoffset = ftell(fp);
	for(i = 0; i < panecount; i++) paneoffsets[i] = 0x10;
	WriteBRLANOffsets(paneoffsets, panecount, fp);
	
	for(node = mxmlFindElement(tree, tree, "pane", NULL, NULL, MXML_DESCEND); node != NULL; node = mxmlFindElement(node, tree, "pane", NULL, NULL, MXML_DESCEND))
	{
		blobcount++;
		paneoffsets[blobcount-1] = ftell(fp) - paneoffsets[blobcount-1];
		create_tag_from_xml(tree, node, fp);
        totaltagsize = ftell(fp) - tagoffset;
	}
	u32 fileSize = ftell(fp);
	fseek(fp, tagoffset, SEEK_SET);
	WriteBRLANOffsets(paneoffsets, blobcount, fp);
	

    paihead.num_timgs = timgcount;
    paihead.entry_offset = sizeof(brlan_pai1_header_type1) + totaltimgize + (4*paihead.num_timgs);
    paihead.num_entries = blobcount;
    fseek(fp, 0, SEEK_END);
    paihead.size = fileSize - rlanhead.pai1_offset;
    rlanhead.file_size = fileSize;
    fseek(fp, 0, SEEK_SET);
    WriteBRLANHeader(rlanhead, fp);
    WriteBRLANPaiHeader(paihead, fp);
}
Exemple #27
0
void load_level( void )
{
	obj = OBJ_load( OBJ_FILE, 1 );

	unsigned int i = 0;

	while( i != obj->n_objmesh ) {
	
		OBJ_optimize_mesh( obj, i, 128 );

		OBJ_build_mesh( obj, i );
		
		OBJ_free_mesh_vertex_data( obj, i );

		++i;
	}
	
	
	init_physic_world();
	
	load_physic_world();
	
	gContactAddedCallback = contact_added_callback;
	
	/* Get the mesh object name level_clear, which is the cylinder located
	 * in the middle of the level end target. */
   OBJMESH *level_clear = OBJ_get_mesh( obj, "level_clear", 0 );

   /* On top of the usual CF_CUSTOM_MATERIAL_CALLBACK collision flag,
   add CF_NO_CONTACT_RESPONSE. This collision flag makes your rigid
   body object act like a ghost, meaning that it will not respond to collision.
   This can be used to turn off the collision response of any rigid body,
    which is great for this typical scenario, where you only want the object to trigger the callback. */
   level_clear->btrigidbody->setCollisionFlags( level_clear->btrigidbody->getCollisionFlags()  |
												btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK |
												btCollisionObject::CF_NO_CONTACT_RESPONSE );

   /* Make the level_clear mesh invisible for rendering. */
   level_clear->visible = 0;

   i = 0;
   while( i != obj->n_objmesh ) { 

      OBJMESH *objmesh = &obj->objmesh[ i ];

      if( strstr( objmesh->name, "gem" ) ) { 

         objmesh->rotation.z = ( float )( random() % 360 );

         objmesh->btrigidbody->setCollisionFlags( objmesh->btrigidbody->getCollisionFlags() |
												  btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK );
      }
	  
	  ++i;
   }	
	
	
	player = OBJ_get_mesh( obj, "player", 0 );
	
	player->btrigidbody->setFriction( 10.0f );
	
	memcpy( &eye, &player->location, sizeof( vec3 ) );
	
	
	i = 0;
	while( i != obj->n_texture ) { 

		OBJ_build_texture( obj,
						   i,
						   obj->texture_path,
						   TEXTURE_MIPMAP | TEXTURE_16_BITS,
						   TEXTURE_FILTER_2X,
						   0.0f );
		++i;
	}


	i = 0;
	while( i != obj->n_program ) { 

		OBJ_build_program( obj,
						   i,
						   program_bind_attrib_location,
						   program_draw,
						   1,
						   obj->program_path );
		++i;
	}


	i = 0;
	while( i != obj->n_objmaterial ) { 

		OBJ_build_material( obj, i, NULL );
		
		++i;
	}	

	

	font_small = FONT_init( ( char * )"foo.ttf" );

	FONT_load( font_small,
			   font_small->name,
			   1,
			   24.0f,
			   512,
			   512,
			   32,
			   96 );
			   

	font_big = FONT_init( ( char * )"foo.ttf" );

	FONT_load( font_big,
			   font_big->name,
			   1,
			   48.0f,
			   512,
			   512,
			   32,
			   96 );
			   
	/* Declare a memory structure that you will use (and reuse) to load each sound buffer. */
	MEMORY *memory = NULL;
	/* Reset the counter. */
	i = 0;
	while( i != 4 ) {
	
		switch( i ) { 
		
			case 0: {
				/* Load the red.ogg file. */
				memory = mopen( ( char * )"red.ogg", 1 );
				break;
			}
			case 1: {
				/* Load the green.ogg file. */
				memory = mopen( ( char * )"green.ogg", 1 );
				break;
			}
			case 2: {
				/* Load the blue.ogg file. */
				memory = mopen( ( char * )"blue.ogg", 1 );
				break;
			}
			case 3: {
				/* Load the yellow.ogg file. */
				memory = mopen( ( char * )"yellow.ogg", 1 );
				break;
			}
		}

		/* For the current gem buffer index, create a sound buffer using the content
		 * of the memory structure that we have loaded. */
		gems_soundbuffer[ i ] = SOUNDBUFFER_load( ( char * )"gem", memory );

		mclose( memory );
		
		/* Create a new sound source for the current index and link the current sound buffer. */
		gems_sound[ i ] =  SOUND_add( ( char * )"gem", gems_soundbuffer[ i ] );

		SOUND_set_volume( gems_sound[ i ], 1.0f );

		++i;
	}
	
	/* Temporary variable to contain the mesh pointer of the object that will be emitting the sound. */
	OBJMESH *objmesh = NULL;
	/* Load the water.ogg file in memory. */
	memory = mopen( ( char * )"water.ogg", 1 );

	water_soundbuffer = SOUNDBUFFER_load( ( char * )"water", memory );

	/* Free the memory , because the sound buffer is loaded as a static sound and the raw audio buffer has been transferred to the
	audio memory by the previous function call. */
	mclose( memory );

	/* Create the water sound source. */
	water_sound = SOUND_add( ( char * )"water", water_soundbuffer );

	/* Here comes the part of code where we are going to associate the
	sound source to the object. First, get the objmesh pointer for the water object. */
	objmesh = OBJ_get_mesh( obj, "water", 0 );

	/* Assign to the sound source the location of the mesh in 3D space and
	use the radius as the reference distance (how far the sound can be heard). */
	SOUND_set_location( water_sound,
						&objmesh->location,
						objmesh->radius );

	/* Set the volume of the water at 50%. */
	SOUND_set_volume( water_sound, 0.5f );

	SOUND_play( water_sound, 1 );

	//the same as above for the lava sound
	memory = mopen( ( char * )"lava.ogg", 1 );
	
	lava_soundbuffer = SOUNDBUFFER_load( ( char * )"lava", memory );
	
	mclose( memory );
	
	lava_sound = SOUND_add( ( char * )"lava", lava_soundbuffer );

	objmesh = OBJ_get_mesh( obj, "lava", 0 );

	SOUND_set_location( lava_sound,
						&objmesh->location, 
						objmesh->radius );
						
	SOUND_set_volume( lava_sound, 0.5f );

	SOUND_play( lava_sound, 1 );

	//finally for the toxic waste sound
	memory = mopen( ( char * )"toxic.ogg", 1 );
	
	toxic_soundbuffer = SOUNDBUFFER_load( ( char * )"toxic", memory );

	mclose( memory );

	toxic_sound = SOUND_add( ( char * )"toxic", toxic_soundbuffer );
	
	objmesh = OBJ_get_mesh( obj, "toxic", 0 );

	SOUND_set_location( toxic_sound,
						&objmesh->location, 
						objmesh->radius );
	
	SOUND_set_volume( toxic_sound, 0.5f );
	
	SOUND_play( toxic_sound, 1 );

	/* Load the background sound as a streamed buffer. */
	memory = mopen( ( char * )"background.ogg", 1 );

	background_soundbuffer = SOUNDBUFFER_load_stream( ( char * )"background", memory );

	background_sound = SOUND_add( ( char * )"background", background_soundbuffer );
	
	SOUND_set_volume( background_sound, 0.5f );
	/* Play the background sound in a loop. */
	SOUND_play( background_sound, 1 );

	//Start the decompression thread
	THREAD_play( thread );

}
Exemple #28
0
void *
readdesc(const char *name)
{
	char *cmd, *p, *q;
	int i, totfont, v;
	char *cpout, *fpout;
	size_t sz, fsz;
	char *dir, *dp, *dq;
	struct mfile *mp;

	memset(&dev, 0, sizeof dev);
	if ((mp = mopen(name)) == NULL) {
		errprint("can't open tables for %s", name);
		return NULL;
	}
	while ((cmd = sget(mp)) != NULL) {
		if (cmd[0] == '#')	/* comment */
			skipline(mp);
		else if (strcmp(cmd, "res") == 0) {
			dget(mp, &dev.res);
		} else if (strcmp(cmd, "hor") == 0) {
			dget(mp, &dev.hor);
		} else if (strcmp(cmd, "vert") == 0) {
			dget(mp, &dev.vert);
		} else if (strcmp(cmd, "unitwidth") == 0) {
			dget(mp, &dev.unitwidth);
		} else if (strcmp(cmd, "sizescale") == 0) {
			dget(mp, &dev.sizescale);
		} else if (strcmp(cmd, "paperwidth") == 0) {
			dget(mp, &dev.paperwidth);
		} else if (strcmp(cmd, "paperlength") == 0) {
			dget(mp, &dev.paperlength);
		} else if (strcmp(cmd, "biggestfont") == 0) {
			dget(mp, &dev.biggestfont);
		} else if (strcmp(cmd, "spare2") == 0) {
			dget(mp, &dev.spare2);
		} else if (strcmp(cmd, "encoding") == 0) {
			dget(mp, &dev.encoding);
		} else if (strcmp(cmd, "allpunct") == 0) {
			dev.allpunct = 1;
		} else if (strcmp(cmd, "anysize") == 0) {
			dev.anysize = 1;
		} else if (strcmp(cmd, "afmfonts") == 0) {
			dev.afmfonts = 1;
		} else if (strcmp(cmd, "lc_ctype") == 0) {
			dev.lc_ctype = 1;
		} else if (strcmp(cmd, "sizes") == 0) {
			dev.nsizes = 0;
			while (dget(mp, &v) != EOF && v != 0)
				size[dev.nsizes++] = v;
			size[dev.nsizes] = 0;	/* need an extra 0 at the end */
		} else if (strcmp(cmd, "fonts") == 0) {
			dget(mp, &dev.nfonts);
			for (i = 0; i < dev.nfonts; i++)
				if ((p = sget(mp)) != NULL)
					strncpy(fname[i], p,
							sizeof fname[i] - 1);
		} else if (strcmp(cmd, "charset") == 0) {
			p = chname;
			dev.nchtab = 0;
			while ((q = sget(mp)) != NULL) {
				strcpy(p, q);
				chtab[dev.nchtab++] = p - chname;
				while (*p++)	/* skip to end of name */
					;
			}
			dev.lchname = p - chname;
			chtab[dev.nchtab++] = 0;	/* terminate properly */
		} else
			errprint("Unknown command %s in %s", cmd, name);
	}
	cpout = calloc(1, sz = sizeof dev +
			sizeof *size * (dev.nsizes+1) +
			sizeof *chtab * dev.nchtab +
			sizeof *chname * dev.lchname);
	memcpy(cpout, &dev, sizeof dev);
	v = sizeof dev;
	memcpy(&cpout[v], size, sizeof *size * (dev.nsizes+1));
	v += sizeof *size * (dev.nsizes+1);
	memcpy(&cpout[v], chtab, sizeof *chtab * dev.nchtab);
	v += sizeof *chtab * dev.nchtab;
	memcpy(&cpout[v], chname, sizeof *chname * dev.lchname);
	v += sizeof *chname * dev.lchname;
	dp = dir = malloc(strlen(name) + sizeof fname[0] + 2);
	strcpy(dir, name);
	for (dq = dir; *dq; dq++)
		if (*dq == '/')
			dp = &dq[1];
	totfont = 0;
	for (i = 0; i < dev.nfonts; i++) {
		strcpy(dp, fname[i]);
		if ((fpout = _readfont(dir, &fsz, 1)) == NULL) {
			mclose(mp);
			return NULL;
		}
		sz += fsz;
		cpout = realloc(cpout, sz);
		memcpy(&cpout[v], fpout, fsz);
		v += fsz;
		free(fpout);
		totfont += fsz;
	}
	/* back to beginning to install proper size */
	dev.filesize =		/* excluding dev struct itself */
		(dev.nsizes+1) * sizeof(size[0])
		+ dev.nchtab * sizeof(chtab[0])
		+ dev.lchname * sizeof(chname[0])
		+ totfont * sizeof(char);
	memcpy(cpout, &dev, sizeof dev);
	mclose(mp);
	return cpout;
}