コード例 #1
0
ファイル: file.c プロジェクト: kanzure/brlcad
int
bu_same_file(const char *fn1, const char *fn2)
{
    struct stat sb1, sb2;

    if (UNLIKELY(!fn1 || !fn2)) {
	return 0;
    }

    if (UNLIKELY(fn1[0] == '\0' || fn2[0] == '\0')) {
	return 0;
    }

    if (!bu_file_exists(fn1, NULL) || !bu_file_exists(fn2, NULL)) {
	return 0;
    }

    if ((stat(fn1, &sb1) == 0) &&
	(stat(fn2, &sb2) == 0) &&
	(sb1.st_dev == sb2.st_dev) &&
	(sb1.st_ino == sb2.st_ino)) {
	return 1;
    }

    return 0;
}
コード例 #2
0
ファイル: file.c プロジェクト: kanzure/brlcad
int
bu_file_delete(const char *path)
{
    int fd = 0;
    int ret = 0;
    int retry = 0;
    struct stat sb;

    /* reject empty, special, or non-existent paths */
    if (!path
	|| BU_STR_EQUAL(path, "")
	|| BU_STR_EQUAL(path, ".")
	|| BU_STR_EQUAL(path, "..")
	|| !bu_file_exists(path, &fd))
    {
	return 0;
    }

    do {

	if (retry++) {
	    /* second pass, try to force deletion by changing file
	     * permissions (similar to rm -f).
	     */
	    if (fstat(fd, &sb) == -1) {
		break;
	    }
	    bu_fchmod(fd, (sb.st_mode|S_IRWXU));
	}

	ret = (remove(path) == 0) ? 0 : 1;

    } while (ret == 0 && retry < 2);
    close(fd);

    /* all boils down to whether the file still exists, not whether
     * remove thinks it succeeded.
     */
    if (bu_file_exists(path, &fd)) {
	/* failure */
	if (retry > 1) {
	    /* restore original file permission */
	    bu_fchmod(fd, sb.st_mode);
	}
	close(fd);
	return 0;
    } else {
	/* deleted */
	return 1;
    }
}
コード例 #3
0
int
main(int argc, char *argv[])
{
    static const char usage[] = "Usage:\n%s [-o outfile] \n\n  -o file \tFile to write out (default: ringworld.g)\n\n";

    char outfile[MAXPATHLEN] = "ringworld.g";
    int optc;
    struct rt_wdb *fp;

    while ((optc = bu_getopt(argc, argv, "o:h?")) != -1) {
    	if (bu_optopt == '?') optc='h';
	switch (optc) {
	    case 'o':
		snprintf(outfile, MAXPATHLEN, "%s", bu_optarg);
		break;
	    default:
		fprintf(stderr,usage, *argv);
		return optc == '?' ? EXIT_FAILURE : EXIT_SUCCESS;
	}
    }

    if (argc == 1) {
	fprintf(stderr,usage, *argv);
    	fprintf(stderr,"       Program continues running:\n");
    }

    if (bu_file_exists(outfile, NULL))
	bu_exit(EXIT_FAILURE, "ERROR: %s already exists.  Remove file and try again.", outfile);

    bu_log("Writing ringworld out to [%s]\n", outfile);

    fp = wdb_fopen(outfile);

    mk_sol(fp, SUN_DIAMETER);
    mk_ring(fp, RING_ORBIT, RING_WIDTH, RING_FLOOR_THICKNESS, RING_WALL_THICKNESS, RING_WALL_HEIGHT);
    mk_shadowring(fp, SHADOWRING_ORBIT, SHADOWRING_NUM, SHADOWRING_WIDTH, SHADOWRING_LENGTH, SHADOWRING_THICKNESS);

    /* generate a comb all.g */
    {
	struct wmember c;
	BU_LIST_INIT(&c.l);
	mk_addmember("ring.r", &c.l, NULL, WMOP_UNION);
	mk_addmember("sun.r", &c.l, NULL, WMOP_UNION);
	/* mk_addmember("shadowring.r", &c.l, NULL, WMOP_UNION); */
	mk_lcomb(fp, "all.g", &c, 0, NULL, NULL, NULL, 0);
    }


    wdb_close(fp);
    bu_log("BRL-CAD geometry database file [%s] created.\nDone.\n", outfile);

    return EXIT_SUCCESS;
}
コード例 #4
0
int
main(int argc, char *argv[])
{
    static const char usage[] = "Usage:\n%s [-o outfile] [-n count]\n\n  -o file \tFile to write out (default: metaball.g)\n  -n count\tTotal metaball point count (default %d)\n\n";
    static const int COUNTMAX = 555;

    char outfile[MAXPATHLEN] = "metaball.g";
    int optc;
    long count = COUNTMAX;

    if (argc == 1) {
	fprintf(stderr,usage, *argv, COUNTMAX);
    	fprintf(stderr,"       Program continues running:\n");
    }

    while ((optc = bu_getopt(argc, argv, "o:n:h?")) != -1) {
        if (bu_optopt == '?') optc='h';
	switch (optc) {
	    case 'o':
		snprintf(outfile, MAXPATHLEN, "%s", bu_optarg);
		break;
	    case 'n':
		count = atoi(bu_optarg);
		break;
	    default:
		fprintf(stderr,usage, *argv, COUNTMAX);
		return optc == '?' ? EXIT_FAILURE : EXIT_SUCCESS;
	}
    }

    if (count <= 0)
	bu_exit(EXIT_FAILURE, "ERROR: count must be greater than zero");

    if (bu_file_exists(outfile, NULL))
	bu_exit(EXIT_FAILURE, "ERROR: %s already exists.  Remove file and try again.", outfile);

    bu_log("Writing metaballs out to [%s]\n", outfile);

    /* make dinner */
    make_spaghetti(outfile, "meatballs.s", count);

    bu_log("BRL-CAD geometry database file [%s] created.\nDone.\n", outfile);

    return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: brlcad_path.c プロジェクト: cciechad/brlcad
/**
 * b u _ a r g v 0 _ f u l l _ p a t h
 *
 * returns the full path to argv0, regardless of how the application
 * was invoked.
 */
const char *
bu_argv0_full_path(void)
{
    static char buffer[MAXPATHLEN] = {0};

    const char *argv0 = bu_argv0();
    const char *ipwd = bu_ipwd();

    const char *which = bu_which(argv0);

    if (argv0[0] == BU_DIR_SEPARATOR) {
	/* seems to be a full path */
	snprintf(buffer, MAXPATHLEN, "%s", argv0);
	return buffer;
    }

    if (argv0[0] == '.' && argv0[1] == BU_DIR_SEPARATOR) {
	/* remove a ./ if present */
	argv0 += 2;
    }

    /* running from installed */
    if (which) {
	snprintf(buffer, MAXPATHLEN, "%s", which);
	return buffer;
    }

    /* running from source dir */
    snprintf(buffer, MAXPATHLEN, "%s%c%s", ipwd, BU_DIR_SEPARATOR, argv0);
    if (bu_file_exists(buffer)) {
	return buffer;
    }

    /* give up */
    snprintf(buffer, MAXPATHLEN, "%s", argv0);
    return buffer;
}
コード例 #6
0
int
ged_lc(struct ged *gedp, int argc, const char *argv[])
{
    char *file_name = NULL;
    int file_name_flag_cnt = 0;
    int sort_column = 1;
    int sort_column_flag_cnt = 0;
    int find_duplicates_flag = 0;
    int skip_special_duplicates_flag = 0;
    int skip_subtracted_regions_flag = 0;
    int descending_sort_flag = 0;
    int unrecognized_flag_cnt = 0;

    int orig_argc;
    const char **orig_argv;

    static const char *usage = "[-d|-s] [-r] [-z] [-0|-1|-2|-3|-4|-5] [-f {FileName}] {GroupName}";

    int c;
    int error_cnt = 0;

    FILE *outfile = NULL;
    struct bu_vls *output;

    const char *group_name;

    size_t i,j;
    struct bu_ptbl results1 = BU_PTBL_INIT_ZERO;
    struct bu_ptbl results2 = BU_PTBL_INIT_ZERO;
    char *path;
    char *plan;
    struct db_full_path root;
    int matches;
    struct region_record *regions;
    size_t ignored_cnt = 0;

    /* The defaults are the minimum widths to accommodate column headers */
    size_t region_id_len_max = 2;
    size_t material_id_len_max = 3;
    size_t los_len_max = 3;
    size_t obj_len_max = 6;

    /* For the output at the end */
    size_t start, end, incr;

    /* initialize result */
    bu_vls_trunc(gedp->ged_result_str, 0);

    if (argc == 1) {
	bu_vls_printf(gedp->ged_result_str, "Usage: %s\n", usage);
	return GED_HELP;
    }

    GED_CHECK_DATABASE_OPEN(gedp, GED_ERROR);
    GED_CHECK_ARGC_GT_0(gedp, argc, GED_ERROR);

    bu_optind = 1; /* re-init bu_getopt() */
    while ((c = bu_getopt(argc, (char * const *)argv, "dsrz012345f:")) != -1) {
	switch (c) {
	    case '0':
	    case '1':
	    case '2':
	    case '3':
	    case '4':
	    case '5':
		sort_column_flag_cnt++;
		sort_column = c - '0';
		break;
	    case 'f':
		file_name_flag_cnt++;
		file_name = bu_optarg;
		break;
	    case 's':
		skip_special_duplicates_flag = 1;
		/* FALLTHROUGH */
	    case 'd':
		find_duplicates_flag = 1;
		break;
	    case 'r':
		skip_subtracted_regions_flag = 1;
		break;
	    case 'z':
		descending_sort_flag = 1;
		break;
	    default:
		unrecognized_flag_cnt++;
	}
    }
    orig_argc = argc;
    orig_argv = argv;
    argc -= (bu_optind - 1);
    argv += (bu_optind - 1);

    /* Attempt to recreate the exact error messages from the original lc.tcl */

    if (file_name_flag_cnt > 1) {
	bu_vls_printf(gedp->ged_result_str, "Error: '-f' used more than once.\n");
	error_cnt++;
    }

    if (sort_column_flag_cnt > 1) {
	bu_vls_printf(gedp->ged_result_str, "Error: Sort column defined more than once.\n");
	error_cnt++;
    }

    if (file_name_flag_cnt + argc + unrecognized_flag_cnt > 3) {
	bu_vls_printf(gedp->ged_result_str, "Error: More than one group name and/or file name was specified.\n");
	error_cnt++;
    } else if (argc < 2) {
	if (file_name_flag_cnt && !file_name) {
	    bu_vls_printf(gedp->ged_result_str, "Error: Group name and file name not specified\n");
	} else {
	    bu_vls_printf(gedp->ged_result_str, "Error: Group name not specified.\n");
	}
        error_cnt++;
    } else if (argc + unrecognized_flag_cnt > 2) {
	bu_vls_printf(gedp->ged_result_str, "Error: More than one group name was specified.\n");
	error_cnt++;
    } else if (file_name_flag_cnt && !file_name) {
	bu_vls_printf(gedp->ged_result_str, "Error: File name not specified.\n");
	error_cnt++;
    }

    if (file_name) {
	char *norm_name;
	norm_name = bu_realpath(file_name, NULL);
	if (file_name[0] == '-') {
	    bu_vls_printf(gedp->ged_result_str, "Error: File name can not start with '-'.\n");
	    error_cnt++;
	} else if (bu_file_exists(file_name, NULL)) {
	    bu_vls_printf(gedp->ged_result_str, "Error: Output file %s already exists.\n",norm_name);
	    error_cnt++;
	} else {
	    outfile = fopen(file_name, "w");
	    if (!outfile) {
		bu_vls_printf(gedp->ged_result_str, "Error: %d\n", errno);
		error_cnt++;
	    }
	}
	bu_vls_printf(gedp->ged_result_str, "Output filename: %s\n", norm_name);
	bu_free(norm_name, "ged_lc");
	output = bu_vls_vlsinit();
    } else {
	output = gedp->ged_result_str;
    }

    if (error_cnt > 0) { return GED_ERROR; }

    group_name = argv[1];

    /* The 7 is for the "-name" and '\0' */
    plan = (char *) bu_malloc(sizeof(char) * (strlen(group_name) + 7), "ged_lc");
    sprintf(plan, "-name %s", group_name);
    matches = db_search(&results1, DB_SEARCH_TREE, plan, 0, NULL, gedp->ged_wdbp->dbip);
    if (matches < 1) {
	bu_vls_printf(gedp->ged_result_str, "Error: Group '%s' does not exist.\n", group_name);
	return GED_ERROR;
    }
    bu_free(plan, "ged_lc");
    db_search_free(&results1);

    if (skip_subtracted_regions_flag) {
	plan = "-type region ! -bool -";
    } else {
	plan = "-type region";
    }
    path = (char *) bu_malloc(sizeof(char) * (strlen(group_name) + 2), "ged_lc");
    sprintf(path, "/%s", group_name);
    db_string_to_path(&root, gedp->ged_wdbp->dbip, path);
    matches = db_search(&results2, DB_SEARCH_TREE, plan, root.fp_len, root.fp_names, gedp->ged_wdbp->dbip);
    bu_free(path, "ged_lc");
    if (matches < 1) { return GED_ERROR; }
    regions = (struct region_record *) bu_malloc(sizeof(struct region_record) * BU_PTBL_LEN(&results2), "ged_lc");
    for (i = 0; i < BU_PTBL_LEN(&results2); i++) {
	struct db_full_path *entry = (struct db_full_path *)BU_PTBL_GET(&results2, i);
	struct directory *dp_curr_dir = DB_FULL_PATH_CUR_DIR(entry);
	struct bu_attribute_value_set avs;

    	j = BU_PTBL_LEN(&results2) - i - 1 ;
	regions[j].ignore = 0;

	bu_avs_init_empty(&avs);
	db5_get_attributes(gedp->ged_wdbp->dbip, &avs, dp_curr_dir);

	regions[j].region_id = get_attr(&avs, "region_id");
	V_MAX(region_id_len_max, strlen(regions[j].region_id));
	regions[j].material_id = get_attr(&avs, "material_id");
	V_MAX(material_id_len_max, strlen(regions[j].material_id));
	regions[j].los = get_attr(&avs, "los");
	V_MAX(los_len_max, strlen(regions[j].los));
	regions[j].obj_name = dp_curr_dir->d_namep;
	V_MAX(obj_len_max, strlen(regions[j].obj_name));

	if (entry->fp_len > 1) {
	    struct directory *dp_parent = DB_FULL_PATH_GET(entry, entry->fp_len - 2);
	    regions[j].obj_parent = dp_parent->d_namep;
	} else {
	    regions[j].obj_parent = "--";
	}
    }

    if (find_duplicates_flag) {

	bu_sort((void *) regions, BU_PTBL_LEN(&results2), sizeof(struct region_record), cmp_regions, NULL);

	for (i = 1;  i < BU_PTBL_LEN(&results2); i++) {
	    int same;
	    if (skip_special_duplicates_flag) {
		same = !cmp_regions((void *)&(regions[i - 1]), (void *)&(regions[i]), NULL);
	    } else {
		same = !bu_strcmp(regions[i - 1].region_id, regions[i].region_id);
	    }
	    if (same) {
		regions[i].ignore = 1;
		ignored_cnt++;
	    }
	}

	if (ignored_cnt == BU_PTBL_LEN(&results2)) {
	    if (file_name) {
		print_cmd_args(output, orig_argc, orig_argv);
		bu_vls_printf(output, "No duplicate region_id\n");
		bu_vls_fwrite(outfile, output);
		fclose(outfile);
	    }
	    bu_vls_printf(gedp->ged_result_str, "No duplicate region_id\n");
	    bu_vls_printf(gedp->ged_result_str, "Done.\n");
	    bu_free(regions, "ged_lc");
	    return GED_ERROR;
	}
    }

    if (sort_column > 0) {
	bu_sort((void *) regions, BU_PTBL_LEN(&results2), sizeof(struct region_record), sort_regions, (void *)&sort_column);
    }

    if (file_name) {
	print_cmd_args(output, orig_argc, orig_argv);
    }

    bu_vls_printf(output, "List length: %d\n", BU_PTBL_LEN(&results2) - ignored_cnt);
    bu_vls_printf(output, "%-*s %-*s %-*s %-*s %s\n",
		  region_id_len_max + 1, "ID",
		  material_id_len_max + 1, "MAT",
		  los_len_max, "LOS",
		  obj_len_max,  "REGION",
		  "PARENT");
    end = BU_PTBL_LEN(&results2);
    if (descending_sort_flag) {
	start = end - 1; end = -1; incr = -1;
    } else {
	start = 0; incr = 1;
    }
    for (i = start; i != end; i += incr) {
	if (regions[i].ignore) { continue; }
	bu_vls_printf(output, "%-*s %-*s %-*s %-*s %s\n",
		      region_id_len_max + 1, regions[i].region_id,
		      material_id_len_max + 1, regions[i].material_id,
		      los_len_max, regions[i].los,
		      obj_len_max, regions[i].obj_name,
		      regions[i].obj_parent);
    }
    bu_vls_printf(gedp->ged_result_str, "Done.\n");

    if (file_name) {
	bu_vls_fwrite(outfile, output);
	fclose(outfile);
    }

    bu_free(regions, "ged_lc");

    return GED_OK;
}
コード例 #7
0
ファイル: saveview.c プロジェクト: kanzure/brlcad
int
ged_saveview(struct ged *gedp, int argc, const char *argv[])
{
    struct ged_display_list *gdlp;
    struct ged_display_list *next_gdlp;
    int i;
    FILE *fp;
    char *base;
    int c;
    char rtcmd[255] = {'r', 't', 0};
    char outlog[255] = {0};
    char outpix[255] = {0};
    char inputg[255] = {0};
    static const char *usage = "[-e] [-i] [-l] [-o] filename [args]";

    GED_CHECK_DATABASE_OPEN(gedp, GED_ERROR);
    GED_CHECK_VIEW(gedp, GED_ERROR);
    GED_CHECK_ARGC_GT_0(gedp, argc, GED_ERROR);

    /* initialize result */
    bu_vls_trunc(gedp->ged_result_str, 0);

    /* must be wanting help */
    if (argc == 1) {
	bu_vls_printf(gedp->ged_result_str, "Usage: %s %s", argv[0], usage);
	return GED_HELP;
    }

    bu_optind = 1;
    while ((c = bu_getopt(argc, (char * const *)argv, "e:i:l:o:")) != -1) {
	switch (c) {
	    case 'e':
		snprintf(rtcmd, 255, "%s", bu_optarg);
		break;
	    case 'l':
		snprintf(outlog, 255, "%s", bu_optarg);
		break;
	    case 'o':
		snprintf(outpix, 255, "%s", bu_optarg);
		break;
	    case 'i':
		snprintf(inputg, 255, "%s", bu_optarg);
		break;
	    default: {
		bu_vls_printf(gedp->ged_result_str, "Option '%c' unknown\n", c);
		bu_vls_printf(gedp->ged_result_str, "help saveview");
		return GED_ERROR;
	    }
	}
    }
    argc -= bu_optind-1;
    argv += bu_optind-1;

    if (argc < 2) {
	bu_vls_printf(gedp->ged_result_str, "Usage: %s %s", argv[0], usage);
	return GED_ERROR;
    }

    if ((fp = fopen(argv[1], "a")) == NULL) {
	perror(argv[1]);
	return GED_ERROR;
    }
    (void)bu_fchmod(fileno(fp), 0755);	/* executable */

    if (!gedp->ged_wdbp->dbip->dbi_filename) {
	bu_log("Error: geometry file is not specified\n");
	fclose(fp);
	return GED_ERROR;
    }

    if (!bu_file_exists(gedp->ged_wdbp->dbip->dbi_filename, NULL)) {
	bu_log("Error: %s does not exist\n", gedp->ged_wdbp->dbip->dbi_filename);
	fclose(fp);
	return GED_ERROR;
    }

    base = basename_without_suffix(argv[1], ".sh");
    if (outpix[0] == '\0') {
	snprintf(outpix, 255, "%s.pix", base);
    }
    if (outlog[0] == '\0') {
	snprintf(outlog, 255, "%s.log", base);
    }

    /* Do not specify -v option to rt; batch jobs must print everything. -Mike */
    fprintf(fp, "#!/bin/sh\n%s -M ", rtcmd);
    if (gedp->ged_gvp->gv_perspective > 0)
	fprintf(fp, "-p%g ", gedp->ged_gvp->gv_perspective);
    for (i = 2; i < argc; i++)
	fprintf(fp, "%s ", argv[i]);

    if (bu_strncmp(rtcmd, "nirt", 4) != 0)
	fprintf(fp, "\\\n -o %s\\\n $*\\\n", outpix);

    if (inputg[0] == '\0') {
	snprintf(inputg, 255, "%s", gedp->ged_wdbp->dbip->dbi_filename);
    }
    fprintf(fp, " '%s'\\\n ", inputg);

    gdlp = BU_LIST_NEXT(ged_display_list, gedp->ged_gdp->gd_headDisplay);
    while (BU_LIST_NOT_HEAD(gdlp, gedp->ged_gdp->gd_headDisplay)) {
	next_gdlp = BU_LIST_PNEXT(ged_display_list, gdlp);
	fprintf(fp, "'%s' ", bu_vls_addr(&gdlp->gdl_path));
	gdlp = next_gdlp;
    }

    fprintf(fp, "\\\n 2>> %s\\\n", outlog);
    fprintf(fp, " <<EOF\n");

    {
	vect_t eye_model;

	_ged_rt_set_eye_model(gedp, eye_model);
	_ged_rt_write(gedp, fp, eye_model);
    }

    fprintf(fp, "\nEOF\n");
    (void)fclose(fp);

    return GED_OK;
}
コード例 #8
0
ファイル: test_diff.c プロジェクト: kanzure/brlcad
int
main(int argc, char **argv)
{
    int i = 0;
    int diff_state = 0;
    struct bu_ptbl results;
    struct db_i *dbip1 = DBI_NULL;
    struct db_i *dbip2 = DBI_NULL;
    /*struct bu_vls diff_log = BU_VLS_INIT_ZERO;*/
    struct bn_tol *diff_tol;
    BU_GET(diff_tol, struct bn_tol);
    diff_tol->dist = BN_TOL_DIST;

    BU_PTBL_INIT(&results);

    if (argc != 3) {
	bu_log("Error - please specify two .g files\n");
	bu_exit(EXIT_FAILURE, NULL);
    }

    if (!bu_file_exists(argv[1], NULL)) {
	bu_exit(1, "Cannot stat file %s\n", argv[1]);
    }

    if (!bu_file_exists(argv[2], NULL)) {
	bu_exit(1, "Cannot stat file %s\n", argv[2]);
    }

    if ((dbip1 = db_open(argv[1], DB_OPEN_READONLY)) == DBI_NULL) {
	bu_exit(1, "Cannot open geometry database file %s\n", argv[1]);
    }
    RT_CK_DBI(dbip1);
    if (db_dirbuild(dbip1) < 0) {
	db_close(dbip1);
	bu_exit(1, "db_dirbuild failed on geometry database file %s\n", argv[1]);
    }

    /* Reset the material head so we don't get warnings when the global
     * is overwritten.  This will go away when material_head ceases to
     * be a librt global.*/
    rt_new_material_head(MATER_NULL);

    if ((dbip2 = db_open(argv[2], DB_OPEN_READONLY)) == DBI_NULL) {
	bu_exit(1, "Cannot open geometry database file %s\n", argv[2]);
    }
    RT_CK_DBI(dbip2);
    if (db_dirbuild(dbip2) < 0) {
	db_close(dbip1);
	db_close(dbip2);
	bu_exit(1, "db_dirbuild failed on geometry database file %s\n", argv[1]);
    }


    diff_state = db_diff(dbip1, dbip2, diff_tol, DB_COMPARE_ALL, &results);
    if (diff_state == DIFF_UNCHANGED) {
	bu_log("No differences found.\n");
    } else {
	print_diff_summary(&results);
    }

    for (i = 0; i < (int)BU_PTBL_LEN(&results); i++) {
	struct diff_result *result = (struct diff_result *)BU_PTBL_GET(&results, i);
	diff_free_result(result);
    }

    bu_ptbl_free(&results);
    BU_PUT(diff_tol, struct bn_tol);

    db_close(dbip1);
    db_close(dbip2);
    return 0;
}
コード例 #9
0
ファイル: whereis.c プロジェクト: cogitokat/brlcad
const char *
bu_whereis(const char *cmd)
{
    static const char *gotpath = NULL;

    char PATH[MAXPATHENV];

    char *directory = NULL;
    char *position = NULL;

    if (UNLIKELY(bu_debug & BU_DEBUG_PATHS)) {
	bu_log("bu_whereis: [%s]\n", cmd);
    }

    if (UNLIKELY(!cmd)) {
	return NULL;
    }

    /* start fresh */
    memset(PATH, 0, MAXPATHENV);
    memset(bu_whereis_result, 0, MAXPATHLEN);

    /* check for full/relative path match */
    bu_strlcpy(bu_whereis_result, cmd, MAXPATHLEN);
    if (!BU_STR_EQUAL(bu_whereis_result, cmd)) {
	if (UNLIKELY(bu_debug & BU_DEBUG_PATHS)) {
	    bu_log("command [%s] is too long\n", cmd);
	}
	return NULL;
    }
    if (bu_file_exists(bu_whereis_result, NULL) && strchr(bu_whereis_result, BU_DIR_SEPARATOR)) {
	if (bu_whereis_result[0] == '\0')
	    return NULL; /* never return empty */
	return bu_whereis_result;
    }

#if defined(HAVE_SYSCTL) && defined(CTL_USER) && defined(USER_CS_PATH)
    {
	int mib[2] = { CTL_USER, USER_CS_PATH };
	size_t len = MAXPATHENV;

	/* use sysctl() to get the PATH */
	if (sysctl(mib, 2, PATH, &len, NULL, 0) != 0) {
	    if (UNLIKELY(bu_debug & BU_DEBUG_PATHS)) {
		perror("sysctl of user.cs_path");
		bu_log("user.cs_path is unusable\n");
	    }
	    return NULL;
	}

	if (UNLIKELY(bu_debug & BU_DEBUG_PATHS)) {
	    bu_log("PATH is %s\n", PATH);
	}
    }
#endif  /* HAVE_SYSCTL */

    /* search for the executable */
    directory = PATH;
    do {
	position = strchr(directory, BU_PATH_SEPARATOR);
	if (position) {
	    *position = '\0';
	}

	/* empty means use current dir */
	if (strlen(directory) == 0) {
	    directory = ".";
	}

	snprintf(bu_whereis_result, MAXPATHLEN, "%s/%s", directory, cmd);
	if (bu_file_exists(bu_whereis_result, NULL)) {
	    if (bu_whereis_result[0] == '\0')
		return NULL; /* never return empty */
	    return bu_whereis_result;
	}

	if (position) {
	    directory = position + 1;
	} else {
	    directory = NULL;
	}
    } while (directory); /* iterate over PATH directories */

    /* no path or no match */
    if (UNLIKELY(bu_debug & BU_DEBUG_PATHS)) {
	bu_log("no %s in %s\n", cmd, gotpath ? gotpath : "(no path)");
    }

    return NULL;
}
コード例 #10
0
ファイル: fb-rle.c プロジェクト: kanzure/brlcad
static int
get_args(int argc, char **argv)
{
    int c;

    while ((c = bu_getopt(argc, argv, "cF:ds:w:n:S:W:N:X:Y:C:h?")) != -1) {
	switch (c) {
	    case 'c':
		crunch = 1;
		break;
	    case 'F':
		framebuffer = bu_optarg;
		break;
	    case 's':
		/* square file size */
		file_height = file_width = atoi(bu_optarg);
		break;
	    case 'S':
		screen_height = screen_width = atoi(bu_optarg);
		break;
	    case 'w':
		file_width = atoi(bu_optarg);
		break;
	    case 'W':
		screen_width = atoi(bu_optarg);
		break;
	    case 'n':
		file_height = atoi(bu_optarg);
		break;
	    case 'N':
		screen_height = atoi(bu_optarg);
		break;
	    case 'X':
		screen_xoff = atoi(bu_optarg);
		break;
	    case 'Y':
		screen_yoff = atoi(bu_optarg);
		break;
	    case 'C': {
		char *cp = bu_optarg;
		int *conp = background;

		/* premature null => atoi gives zeros */
		for (c=0; c < 3; c++) {
		    *conp++ = atoi(cp);
		    while (*cp && *cp++ != '/')
			;
		}
	    }
		break;
	    default:
		return 0;
	}
    }
    if (argv[bu_optind] != NULL) {
	if (bu_file_exists(argv[bu_optind], NULL)) {
	    (void) fprintf(stderr,
			   "\"%s\" already exists.\n",
			   argv[bu_optind]);
	    bu_exit(1, NULL);
	}
	if ((outrle.rle_file = fopen(argv[bu_optind], "wb")) == NULL) {
	    perror(argv[bu_optind]);
	    return 0;
	}
    }
    if (argc > ++bu_optind)
	(void) fprintf(stderr, "fb-rle: Excess arguments ignored\n");

    if (isatty(fileno(outrle.rle_file)))
	return 0;
    return 1;
}
コード例 #11
0
ファイル: lens.c プロジェクト: cogitokat/brlcad
int main(int ac, char *av[])
{
    struct rt_wdb *db_fp = NULL;
    struct bu_vls lens_type = BU_VLS_INIT_ZERO;
    struct bu_vls name = BU_VLS_INIT_ZERO;
    int lens_1side_2side;
    fastf_t ref_ind, thickness, diameter, focal_length;

    bu_vls_trunc(&lens_type, 0);
    bu_vls_trunc(&name, 0);

    ref_ind = 1.5;
    diameter = 200;
    thickness = diameter/5;
    focal_length = 600;
    lens_1side_2side = 2;
    bu_vls_printf(&lens_type, "DCX");
    bu_vls_printf(&name, "lens_%s_f%.1f_d%.1f", bu_vls_addr(&lens_type), focal_length, diameter);

    /* Process arguments */
    ReadArgs(ac, av, &lens_1side_2side, &ref_ind, &diameter, &thickness, &focal_length);

    /* Create file name if supplied, else use "lens.g" */
    if (av[bu_optind]) {
	if (!bu_file_exists(av[bu_optind], NULL)) {
	    db_fp = wdb_fopen(av[bu_optind]);
	} else {
	    bu_exit(-1, "Error - refusing to overwrite pre-existing file %s", av[bu_optind]);
	}
    }
    if (!av[bu_optind]) {
	if (!bu_file_exists(DEFAULT_LENS_FILENAME, NULL)) {
	    db_fp = wdb_fopen(DEFAULT_LENS_FILENAME);
	} else {
	    bu_exit(-1, "Error - no filename supplied and lens.g exists.");
	}
    }
    /* Make the requested lens*/
    if (lens_1side_2side == 1 && focal_length > 0) {
	bu_log("Making Plano-Convex lens...\n");
	bu_vls_trunc(&lens_type, 0);
	bu_vls_trunc(&name, 0);
	bu_vls_printf(&lens_type, "PCX");
	bu_vls_printf(&name, "lens_%s_f%.1f_d%.1f", bu_vls_addr(&lens_type), focal_length, diameter);
	MakeP(db_fp, bu_vls_addr(&name), diameter, focal_length, ref_ind, thickness);
    }
    if (lens_1side_2side == 1 && focal_length < 0) {
	bu_log("Making Plano-Concave lens...\n");
	bu_vls_trunc(&lens_type, 0);
	bu_vls_trunc(&name, 0);
	bu_vls_printf(&lens_type, "PCV");
	bu_vls_printf(&name, "lens_%s_f%.1f_d%.1f", bu_vls_addr(&lens_type), focal_length, diameter);
	MakeP(db_fp, bu_vls_addr(&name), diameter, focal_length, ref_ind, thickness);
    }

    if (lens_1side_2side == 2 && focal_length > 0) {
	bu_log("Making BiConvex lens...\n");
	bu_vls_trunc(&lens_type, 0);
	bu_vls_trunc(&name, 0);
	bu_vls_printf(&lens_type, "DCX");
	bu_vls_printf(&name, "lens_%s_f%.1f_d%.1f", bu_vls_addr(&lens_type), focal_length, diameter);
	MakeD(db_fp, bu_vls_addr(&name), diameter, focal_length, ref_ind, thickness);
    }
    if (lens_1side_2side == 2 && focal_length < 0) {
	bu_log("Making BiConcave lens...\n");
	bu_vls_trunc(&lens_type, 0);
	bu_vls_trunc(&name, 0);
	bu_vls_printf(&lens_type, "DCV");
	bu_vls_printf(&name, "lens_%s_f%.1f_d%.1f", bu_vls_addr(&lens_type), focal_length, diameter);
	MakeD(db_fp, bu_vls_addr(&name), diameter, focal_length, ref_ind, thickness);
    }

    /* Close database */
    wdb_close(db_fp);

    return 0;
}
コード例 #12
0
ファイル: getcwd.c プロジェクト: kanzure/brlcad
char *
bu_getcwd(char *buf, size_t size)
{
    char *cwd = NULL;
    char *pwd = NULL;
    char cbuf[MAXPATHLEN] = {0};
    size_t sz = size;

    /* NULL buf means allocate */
    if (!buf) {
	sz = MAXPATHLEN;
	buf = (char *)bu_calloc(1, sz, "alloc bu_getcwd");
    }

    /* FIRST: try getcwd */
#ifdef HAVE_GETCWD
    cwd = getcwd(cbuf, MAXPATHLEN);
    if (cwd
	&& strlen(cwd) > 0
	&& bu_file_exists(cwd, NULL))
    {
#if defined(HAVE_WORKING_REALPATH_FUNCTION)
	/* FIXME: shouldn't have gotten here with -std=c99 (HAVE_REALPATH test not working right?) */
	char rbuf[MAXPATHLEN] = {0};
	char *rwd = bu_realpath(cbuf, rbuf);
	if (rwd
	    && strlen(rwd) > 0
	    && bu_file_exists(rwd, NULL))
	{
	    BU_ASSERT(sz > strlen(rwd)+1);
	    bu_strlcpy(buf, rwd, strlen(rwd)+1);
	    return buf;
	}
#endif /* HAVE_WORKING_REALPATH_FUNCTION */
	BU_ASSERT(sz > strlen(cwd)+1);
	bu_strlcpy(buf, cwd, strlen(cwd)+1);
	return buf;
    }
#else
    /* quellage */
    cwd = memset(cbuf, 0, MAXPATHLEN);
#endif /* HAVE_GETCWD */


    /* SECOND: try environment */
    pwd = getenv("PWD");
    if (pwd
	&& strlen(pwd) > 0
	&& bu_file_exists(pwd, NULL))
    {
#if defined(HAVE_WORKING_REALPATH_FUNCTION)
	char rbuf[MAXPATHLEN] = {0};
	char *rwd = realpath(pwd, rbuf);
	if (rwd
	    && strlen(rwd) > 0
	    && bu_file_exists(rwd, NULL))
	{
	    BU_ASSERT(sz > strlen(rwd)+1);
	    bu_strlcpy(buf, rwd, strlen(rwd)+1);
	    return buf;
	}
#endif /* HAVE_WORKING_REALPATH_FUNCTION */
	BU_ASSERT(sz > strlen(pwd)+1);
	bu_strlcpy(buf, pwd, strlen(pwd)+1);
	return buf;
    }

    /* LAST: punt (but do not return NULL) */
    BU_ASSERT(sz > strlen(".")+1);
    bu_strlcpy(buf, ".", strlen(".")+1);
    return buf;
}
コード例 #13
0
ファイル: g-step.cpp プロジェクト: kanzure/brlcad
int
main(int argc, char *argv[])
{
    int ret = 0;
    int convert_tops_list = 0;
    struct directory **paths;
    int path_cnt = 0;
    AP203_Contents *sc = new AP203_Contents;

    // process command line arguments
    int c;
    char *output_file = (char *)NULL;
    while ((c = bu_getopt(argc, argv, "o:")) != -1) {
        switch (c) {
        case 'o':
            output_file = bu_optarg;
            break;
        default:
            usage();
            bu_exit(1, NULL);
            break;
        }
    }

    if (bu_optind >= argc || output_file == (char *)NULL) {
        usage();
        bu_exit(1, NULL);
    }

    argc -= bu_optind;
    argv += bu_optind;

    /* check our inputs/outputs */
    if (bu_file_exists(output_file, NULL)) {
        bu_exit(1, "ERROR: refusing to overwrite existing output file:\"%s\". Please remove file or change output file name and try again.", output_file);
    }

    if (!bu_file_exists(argv[0], NULL) && !BU_STR_EQUAL(argv[0], "-")) {
        bu_exit(2, "ERROR: unable to read input \"%s\" .g file", argv[0]);
    }

    if (argc < 2) {
        convert_tops_list = 1;
    }


    std::string iflnm = argv[0];
    std::string oflnm = output_file;

    /* load .g file */
    BRLCADWrapper *dotg  = new BRLCADWrapper();
    if (!dotg) {
        std::cerr << "ERROR: unable to create BRL-CAD instance" << std::endl;
        return 3;
    }
    if (!dotg->load(iflnm)) {
        std::cerr << "ERROR: unable to open BRL-CAD input file [" << oflnm << "]" << std::endl;
        delete dotg;
        return 2;
    }

    struct db_i *dbip = dotg->GetDBIP();
    struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DISK);

    if (convert_tops_list) {
        /* Need db_update_nref for DB_LS_TOPS to work */
        db_update_nref(dbip, &rt_uniresource);
        path_cnt = db_ls(dbip, DB_LS_TOPS, &paths);
        if (!path_cnt) {
            std::cerr << "ERROR: no objects found in .g file" << "\n" << std::endl;
            delete dotg;
            return 1;
        }
    } else {
        int i = 1;
        paths = (struct directory **)bu_malloc(sizeof(struct directory *) * argc, "dp array");
        while (i < argc) {
            bu_log("%d: %s\n", i, argv[i]);
            struct directory *dp = db_lookup(dbip, argv[i], LOOKUP_QUIET);
            if (dp == RT_DIR_NULL) {
                std::cerr << "ERROR: cannot find " << argv[i] << "\n" << std::endl;
                delete dotg;
                bu_free(paths, "free path memory");
                return 1;
            } else {
                paths[i-1] = dp;
                path_cnt++;
                i++;
            }
        }
        paths[i-1] = RT_DIR_NULL;
    }


    struct bu_vls scratch_string;
    bu_vls_init(&scratch_string);

    Registry *registry = new Registry(SchemaInit);
    InstMgr instance_list;
    STEPfile *sfile = new STEPfile(*registry, instance_list);

    registry->ResetSchemas();
    registry->ResetEntities();

    /* Populate the header instances */
    InstMgr *header_instances = sfile->HeaderInstances();

    /* 1 - Populate File_Name */
    SdaiFile_name * fn = (SdaiFile_name *)sfile->HeaderDefaultFileName();
    bu_vls_sprintf(&scratch_string, "'%s'", output_file);
    fn->name_(bu_vls_addr(&scratch_string));
    fn->time_stamp_("");
    StringAggregate_ptr author_tmp = new StringAggregate;
    author_tmp->AddNode(new StringNode("''"));
    fn->author_(author_tmp);
    StringAggregate_ptr org_tmp = new StringAggregate;
    org_tmp->AddNode(new StringNode("''"));
    fn->organization_(org_tmp);
    fn->preprocessor_version_("'BRL-CAD g-step exporter'");
    fn->originating_system_("''");
    fn->authorization_("''");
    header_instances->Append((SDAI_Application_instance *)fn, completeSE);

    /* 2 - Populate File_Description */
    SdaiFile_description * fd = (SdaiFile_description *)sfile->HeaderDefaultFileDescription();
    StringAggregate_ptr description_tmp = new StringAggregate;
    description_tmp->AddNode(new StringNode("''"));
    fd->description_(description_tmp);
    fd->implementation_level_("'2;1'");
    header_instances->Append((SDAI_Application_instance *)fd, completeSE);

    /* 3 - Populate File_Schema */
    SdaiFile_schema *fs = (SdaiFile_schema *)sfile->HeaderDefaultFileSchema();
    StringAggregate_ptr schema_tmp = new StringAggregate;
    schema_tmp->AddNode(new StringNode("'CONFIG_CONTROL_DESIGN'"));
    fs->schema_identifiers_(schema_tmp);
    header_instances->Append((SDAI_Application_instance *)fs, completeSE);

    sc->registry = registry;
    sc->instance_list = &instance_list;

    sc->default_context = Add_Default_Geometric_Context(sc);

    sc->application_context = (SdaiApplication_context *)sc->registry->ObjCreate("APPLICATION_CONTEXT");
    sc->instance_list->Append((STEPentity *)sc->application_context, completeSE);
    sc->application_context->application_("'CONFIGURATION CONTROLLED 3D DESIGNS OF MECHANICAL PARTS AND ASSEMBLIES'");

    sc->design_context = (SdaiDesign_context *)sc->registry->ObjCreate("DESIGN_CONTEXT");
    sc->instance_list->Append((STEPentity *)sc->design_context, completeSE);
    sc->design_context->name_("''");
    sc->design_context->life_cycle_stage_("'design'");
    sc->design_context->frame_of_reference_(sc->application_context);

    sc->solid_to_step = new std::map<struct directory *, STEPentity *>;
    sc->solid_to_step_shape = new std::map<struct directory *, STEPentity *>;
    sc->solid_to_step_manifold = new std::map<struct directory *, STEPentity *>;
    sc->comb_to_step = new std::map<struct directory *, STEPentity *>;
    sc->comb_to_step_shape = new std::map<struct directory *, STEPentity *>;
    sc->comb_to_step_manifold = new std::map<struct directory *, STEPentity *>;

    for (int i = 0; i < path_cnt; i++) {
        /* Now, add actual DATA */
        struct directory *dp = paths[i];
        struct rt_db_internal intern;
        rt_db_get_internal(&intern, dp, dbip, bn_mat_identity, &rt_uniresource);
        RT_CK_DB_INTERNAL(&intern);
        Object_To_STEP(dp, &intern, wdbp, sc);
        rt_db_free_internal(&intern);
    }

    /* Write STEP file */
    if (!bu_file_exists(output_file, NULL)) {
        std::ofstream stepout(output_file);
        sfile->WriteExchangeFile(stepout);
    }

    /* Free memory */
    header_instances->DeleteInstances();
    instance_list.DeleteInstances();
    delete dotg;
    delete registry;
    delete sfile;
    delete sc->solid_to_step;
    delete sc->solid_to_step_shape;
    delete sc->solid_to_step_manifold;
    delete sc->comb_to_step;
    delete sc->comb_to_step_shape;
    delete sc->comb_to_step_manifold;
    delete sc;
    bu_vls_free(&scratch_string);
    bu_free(paths, "free dp list");

    return ret;
}
コード例 #14
0
ファイル: parse_fmt.c プロジェクト: cogitokat/brlcad
void
direct_output(const char *buffer, com_table *ctp, struct rt_i *UNUSED(rtip))
{
    size_t i = 0;      /* current position on the *buffer */
    size_t j = 0;      /* position of last non-whitespace char in the *buffer */
    FILE *newf;
    static char *new_dest;
    static FILE *(*openfunc)() = 0;

    while (isspace((int)*(buffer+i)))
	++i;

    if (*(buffer+i) == '\0') {
	/* display current destination */
#if defined(HAVE_POPEN) && !defined(STRICT_FLAGS)
	printf("destination = %s%s'\n",
	       (openfunc == popen) ? "'| " : "'", dest_string);
#endif
	return;
    }

    if (BU_STR_EQUAL(buffer + i, "?")) {
	com_usage(ctp);
	return;
    }

    if (BU_STR_EQUAL(buffer + i, "default")) {
	newf = stdout;
	new_dest = def_dest_string;
	openfunc = 0;
    } else {
	if (*(buffer + i) == '|') {
#if defined(HAVE_POPEN) && !defined(STRICT_FLAGS)
	    openfunc=popen;
	    ++i;
#else
	    fprintf(stderr, "Error, support for pipe output is disabled.  Try a redirect instead.\n");
	    return;
#endif
	} else {
	    openfunc=fopen;
	}
	/*Find last non-whitespace character*/
	j = strlen(buffer);
	while (isspace((int)*(buffer+j-1))) j--;

	new_dest = bu_malloc(strlen(buffer + i)+1, "new_dest");

	snprintf(new_dest, j-i+1, "%s", buffer + i);
	if (bu_file_exists(new_dest, NULL)) {
	    fprintf(stderr, "File %s already exists.\n", new_dest);
	    return;
	}
	if ((newf = (*openfunc)(new_dest, "w")) == NULL) {
#if defined(HAVE_POPEN) && !defined(STRICT_FLAGS)
	    fprintf(stderr, "Cannot open %s '%s'\n",
		    (openfunc == popen) ? "pipe" : "file", new_dest);
#endif
	    fprintf(stderr, "Destination remains = '%s'\n", dest_string);

	    bu_free(new_dest, "new(now old)dest");
	    return;
	}


    }

    /* Clean up from previous output destination */
    if (outf != (FILE *)NULL && outf != stdout)
	fclose(outf);

    if (dest_string != def_dest_string)
	bu_free(dest_string, "free dest_string");

    /* Establish the new destination */
    outf = newf;
    dest_string = new_dest;
}