Example #1
0
void C_DECL A_LeafCheck(mobj_t *actor)
{
    int                 n;

    actor->special1++;
    if(actor->special1 >= 20)
    {
        P_MobjChangeState(actor, S_NULL);
        return;
    }

    if(P_Random() > 64)
    {
        if(FEQUAL(actor->mom[MX], 0) && FEQUAL(actor->mom[MY], 0))
        {
            P_ThrustMobj(actor, actor->target->angle,
                         FIX2FLT(P_Random() << 9) + 1);
        }
        return;
    }

    P_MobjChangeState(actor, S_LEAF1_8);
    n = P_Random();
    actor->mom[MZ] = FIX2FLT(n << 9) + 1;
    P_ThrustMobj(actor, actor->target->angle, FIX2FLT(P_Random() << 9) + 2);
    actor->flags |= MF_MISSILE;
}
Example #2
0
void EV_LightTurnOn(Line *line, float max)
{
    iterlist_t *list = P_GetSectorIterListForTag(P_ToXLine(line)->tag, false);
    if(!list) return;

    float lightLevel = 0;
    if(!FEQUAL(max, 0))
        lightLevel = max;

    IterList_SetIteratorDirection(list, ITERLIST_FORWARD);
    IterList_RewindIterator(list);

    Sector *sec;
    while((sec = (Sector *)IterList_MoveIterator(list)))
    {
        // If Max = 0 means to search for the highest light level in the
        // surrounding sector.
        if(FEQUAL(max, 0))
        {
            lightLevel = P_GetFloatp(sec, DMU_LIGHT_LEVEL);
            float otherLevel = DDMINFLOAT;
            P_FindSectorSurroundingHighestLight(sec, &otherLevel);
            if(otherLevel > lightLevel)
                lightLevel = otherLevel;
        }

        P_SetFloatp(sec, DMU_LIGHT_LEVEL, lightLevel);
    }
}
Example #3
0
void P_TranslatePlaneMaterialOrigin(Plane* plane, float deltaXY[2])
{
    float origin[2];

    DENG_ASSERT(plane);

    if(FEQUAL(deltaXY[0], 0) && FEQUAL(deltaXY[1], 0)) return;

    P_GetFloatpv(plane, DMU_OFFSET_XY, origin);
    if(!FEQUAL(deltaXY[0], 0))
    {
        origin[0] += deltaXY[0];
    }
    if(!FEQUAL(deltaXY[1], 0))
    {
        origin[1] += deltaXY[1];
    }
    P_SetFloatpv(plane, DMU_OFFSET_XY, origin);
}
Example #4
0
boolean B_EqualConditions(const statecondition_t* a, const statecondition_t* b)
{
    return (a->device == b->device &&
            a->type == b->type &&
            a->id == b->id &&
            a->state == b->state &&
            FEQUAL(a->pos, b->pos) &&
            a->flags.negate == b->flags.negate &&
            a->flags.multiplayer == b->flags.multiplayer);
}
Example #5
0
void P_TranslateSideMaterialOrigin(Side* side, SideSection section, float deltaXY[2])
{
    DENG_ASSERT(side);
    DENG_ASSERT(VALID_SIDESECTION(section));
{
    const uint dmuSurfaceOriginFlags = DMU_OFFSET_XY | DMU_FLAG_FOR_SIDESECTION(section);
    float origin[2];

    if(FEQUAL(deltaXY[0], 0) && FEQUAL(deltaXY[1], 0)) return;

    P_GetFloatpv(side, dmuSurfaceOriginFlags, origin);
    if(!FEQUAL(deltaXY[0], 0))
    {
        origin[0] += deltaXY[0];
    }
    if(!FEQUAL(deltaXY[1], 0))
    {
        origin[1] += deltaXY[1];
    }
    P_SetFloatpv(side, dmuSurfaceOriginFlags, origin);
}}
Example #6
0
/**
 * Called every tic frame that the player origin is in a special sector
 */
void P_PlayerInSpecialSector(player_t *player)
{
    Sector *sector = Mobj_Sector(player->plr->mo);

    if(IS_CLIENT) return;

    // Falling, not all the way down yet?
    if(!FEQUAL(player->plr->mo->origin[VZ], P_GetDoublep(sector, DMU_FLOOR_HEIGHT))) return;

    // Has hitten ground.
    switch(P_ToXSector(sector)->special)
    {
    default:
        break;

    case 5: ///< HELLSLIME DAMAGE
        if(!player->powers[PT_IRONFEET])
            if(!(mapTime & 0x1f))
                P_DamageMobj(player->plr->mo, NULL, NULL, 10, false);
        break;

    case 7: ///< NUKAGE DAMAGE
        if(!player->powers[PT_IRONFEET])
            if(!(mapTime & 0x1f))
                P_DamageMobj(player->plr->mo, NULL, NULL, 5, false);
        break;

    case 16: ///< SUPER HELLSLIME DAMAGE
    case 4:  ///< STROBE HURT
        if(!player->powers[PT_IRONFEET] || (P_Random() < 5))
        {
            if(!(mapTime & 0x1f))
                P_DamageMobj(player->plr->mo, NULL, NULL, 20, false);
        }
        break;

    case 9: ///< SECRET SECTOR
        player->secretCount++;
        P_ToXSector(sector)->special = 0;
        if(cfg.secretMsg)
        {
            P_SetMessage(player, "You've found a secret area!");
            // S_ConsoleSound(SFX_SECRET, 0, player - players); // jd64
        }
        break;
    }
}
Example #7
0
int EV_BuildPillar(Line * /*line*/, byte *args, dd_bool crush)
{
    iterlist_t *list = P_GetSectorIterListForTag((int) args[0], false);
    if(!list) return 0;

    int rtn = 0;

    IterList_SetIteratorDirection(list, ITERLIST_FORWARD);
    IterList_RewindIterator(list);

    Sector *sec;
    while((sec = (Sector *)IterList_MoveIterator(list)))
    {
        // If already moving keep going...
        if(P_ToXSector(sec)->specialData)
            continue;

        if(FEQUAL(P_GetDoublep(sec, DMU_FLOOR_HEIGHT),
                  P_GetDoublep(sec, DMU_CEILING_HEIGHT)))
            continue; // Pillar is already closed.

        rtn = 1;
        coord_t newHeight = 0;
        if(!args[2])
        {
            newHeight = P_GetDoublep(sec, DMU_FLOOR_HEIGHT) +
                ((P_GetDoublep(sec, DMU_CEILING_HEIGHT) -
                  P_GetDoublep(sec, DMU_FLOOR_HEIGHT)) * .5f);
        }
        else
        {
            newHeight = P_GetDoublep(sec, DMU_FLOOR_HEIGHT) + (coord_t) args[2];
        }

        pillar_t *pillar = (pillar_t *)Z_Calloc(sizeof(*pillar), PU_MAP, 0);
        pillar->thinker.function = (thinkfunc_t) T_BuildPillar;
        Thinker_Add(&pillar->thinker);

        P_ToXSector(sec)->specialData = pillar;
        pillar->sector = sec;

        if(!args[2])
        {
            pillar->ceilingSpeed = pillar->floorSpeed =
                (float) args[1] * (1.0f / 8);
        }
        else if(newHeight - P_GetDoublep(sec, DMU_FLOOR_HEIGHT) >
                P_GetDoublep(sec, DMU_CEILING_HEIGHT) - newHeight)
        {
            pillar->floorSpeed = (float) args[1] * (1.0f / 8);
            pillar->ceilingSpeed =
                (P_GetDoublep(sec, DMU_CEILING_HEIGHT) - newHeight) *
                      (pillar->floorSpeed / (newHeight - P_GetDoublep(sec, DMU_FLOOR_HEIGHT)));
        }
        else
        {
            pillar->ceilingSpeed = (float) args[1] * (1.0f / 8);
            pillar->floorSpeed =
                (newHeight - P_GetDoublep(sec, DMU_FLOOR_HEIGHT)) *
                    (pillar->ceilingSpeed / (P_GetDoublep(sec, DMU_CEILING_HEIGHT) - newHeight));
        }

        pillar->floorDest = newHeight;
        pillar->ceilingDest = newHeight;
        pillar->direction = 1;
        pillar->crush = crush * (int) args[3];
        SN_StartSequence((mobj_t *)P_GetPtrp(pillar->sector, DMU_EMITTER),
                         SEQ_PLATFORM + P_ToXSector(pillar->sector)->seqType);
    }
    return rtn;
}
Example #8
0
/* TODO: fix all ==s left */
int segment_intersection_2d_tol(double ax1, double ay1, double ax2,
				double ay2, double bx1, double by1,
				double bx2, double by2, double *x1,
				double *y1, double *x2, double *y2,
				double tol)
{
    double tola, tolb;

    double d, d1, d2, ra, rb, t;

    int switched = 0;

    /* TODO: Works for points ? */
    G_debug(4, "segment_intersection_2d()");
    G_debug(4, "    ax1  = %.18f, ay1  = %.18f", ax1, ay1);
    G_debug(4, "    ax2  = %.18f, ay2  = %.18f", ax2, ay2);
    G_debug(4, "    bx1  = %.18f, by1  = %.18f", bx1, by1);
    G_debug(4, "    bx2  = %.18f, by2  = %.18f", bx2, by2);


    /* Check identical lines */
    if ((FEQUAL(ax1, bx1, tol) && FEQUAL(ay1, by1, tol) &&
	 FEQUAL(ax2, bx2, tol) && FEQUAL(ay2, by2, tol)) ||
	(FEQUAL(ax1, bx2, tol) && FEQUAL(ay1, by2, tol) &&
	 FEQUAL(ax2, bx1, tol) && FEQUAL(ay2, by1, tol))) {
	G_debug(2, " -> identical segments");
	*x1 = ax1;
	*y1 = ay1;
	*x2 = ax2;
	*y2 = ay2;
	return 5;
    }

    /*  'Sort' lines by x1, x2, y1, y2 */
    if (bx1 < ax1)
	switched = 1;
    else if (bx1 == ax1) {
	if (bx2 < ax2)
	    switched = 1;
	else if (bx2 == ax2) {
	    if (by1 < ay1)
		switched = 1;
	    else if (by1 == ay1) {
		if (by2 < ay2)
		    switched = 1;	/* by2 != ay2 (would be identical */
	    }
	}
    }

    if (switched) {
	t = ax1;
	ax1 = bx1;
	bx1 = t;
	t = ay1;
	ay1 = by1;
	by1 = t;
	t = ax2;
	ax2 = bx2;
	bx2 = t;
	t = ay2;
	ay2 = by2;
	by2 = t;
    }

    d = (ax2 - ax1) * (by1 - by2) - (ay2 - ay1) * (bx1 - bx2);
    d1 = (bx1 - ax1) * (by1 - by2) - (by1 - ay1) * (bx1 - bx2);
    d2 = (ax2 - ax1) * (by1 - ay1) - (ay2 - ay1) * (bx1 - ax1);

    G_debug(2, "    d  = %.18g", d);
    G_debug(2, "    d1 = %.18g", d1);
    G_debug(2, "    d2 = %.18g", d2);

    tola = tol / MAX(fabs(ax2 - ax1), fabs(ay2 - ay1));
    tolb = tol / MAX(fabs(bx2 - bx1), fabs(by2 - by1));
    G_debug(2, "    tol  = %.18g", tol);
    G_debug(2, "    tola = %.18g", tola);
    G_debug(2, "    tolb = %.18g", tolb);
    if (!FZERO(d, tol)) {
	ra = d1 / d;
	rb = d2 / d;

	G_debug(2, "    not parallel/collinear: ra = %.18g", ra);
	G_debug(2, "                            rb = %.18g", rb);

	if ((ra <= -tola) || (ra >= 1 + tola) || (rb <= -tolb) ||
	    (rb >= 1 + tolb)) {
	    G_debug(2, "        no intersection");
	    return 0;
	}

	ra = MIN(MAX(ra, 0), 1);
	*x1 = ax1 + ra * (ax2 - ax1);
	*y1 = ay1 + ra * (ay2 - ay1);

	G_debug(2, "        intersection %.18f, %.18f", *x1, *y1);
	return 1;
    }

    /* segments are parallel or collinear */
    G_debug(3, " -> parallel/collinear");

    if ((!FZERO(d1, tol)) || (!FZERO(d2, tol))) {	/* lines are parallel */
	G_debug(2, "  -> parallel");
	return 0;
    }

    /* segments are colinear. check for overlap */

    /*    aa = adx*adx + ady*ady;
       bb = bdx*bdx + bdy*bdy;

       t = (ax1-bx1)*bdx + (ay1-by1)*bdy; */


    /* Collinear vertical */
    /* original code assumed lines were not both vertical
     *  so there is a special case if they are */
    if (FEQUAL(ax1, ax2, tol) && FEQUAL(bx1, bx2, tol) &&
	FEQUAL(ax1, bx1, tol)) {
	G_debug(2, "  -> collinear vertical");
	if (ay1 > ay2) {
	    t = ay1;
	    ay1 = ay2;
	    ay2 = t;
	}			/* to be sure that ay1 < ay2 */
	if (by1 > by2) {
	    t = by1;
	    by1 = by2;
	    by2 = t;
	}			/* to be sure that by1 < by2 */
	if (ay1 > by2 || ay2 < by1) {
	    G_debug(2, "   -> no intersection");
	    return 0;
	}

	/* end points */
	if (FEQUAL(ay1, by2, tol)) {
	    *x1 = ax1;
	    *y1 = ay1;
	    G_debug(2, "   -> connected by end points");
	    return 1;		/* endpoints only */
	}
	if (FEQUAL(ay2, by1, tol)) {
	    *x1 = ax2;
	    *y1 = ay2;
	    G_debug(2, "  -> connected by end points");
	    return 1;		/* endpoints only */
	}

	/* general overlap */
	G_debug(3, "   -> vertical overlap");
	/* a contains b */
	if (ay1 <= by1 && ay2 >= by2) {
	    G_debug(2, "    -> a contains b");
	    *x1 = bx1;
	    *y1 = by1;
	    *x2 = bx2;
	    *y2 = by2;
	    if (!switched)
		return 3;
	    else
		return 4;
	}
	/* b contains a */
	if (ay1 >= by1 && ay2 <= by2) {
	    G_debug(2, "    -> b contains a");
	    *x1 = ax1;
	    *y1 = ay1;
	    *x2 = ax2;
	    *y2 = ay2;
	    if (!switched)
		return 4;
	    else
		return 3;
	}

	/* general overlap, 2 intersection points */
	G_debug(2, "    -> partial overlap");
	if (by1 > ay1 && by1 < ay2) {	/* b1 in a */
	    if (!switched) {
		*x1 = bx1;
		*y1 = by1;
		*x2 = ax2;
		*y2 = ay2;
	    }
	    else {
		*x1 = ax2;
		*y1 = ay2;
		*x2 = bx1;
		*y2 = by1;
	    }
	    return 2;
	}

	if (by2 > ay1 && by2 < ay2) {	/* b2 in a */
	    if (!switched) {
		*x1 = bx2;
		*y1 = by2;
		*x2 = ax1;
		*y2 = ay1;
	    }
	    else {
		*x1 = ax1;
		*y1 = ay1;
		*x2 = bx2;
		*y2 = by2;
	    }
	    return 2;
	}

	/* should not be reached */
	G_warning(("Vect_segment_intersection() ERROR (collinear vertical segments)"));
	G_warning("%.15g %.15g", ax1, ay1);
	G_warning("%.15g %.15g", ax2, ay2);
	G_warning("x");
	G_warning("%.15g %.15g", bx1, by1);
	G_warning("%.15g %.15g", bx2, by2);
	return 0;
    }

    G_debug(2, "   -> collinear non vertical");

    /* Collinear non vertical */
    if ((bx1 > ax1 && bx2 > ax1 && bx1 > ax2 && bx2 > ax2) ||
	(bx1 < ax1 && bx2 < ax1 && bx1 < ax2 && bx2 < ax2)) {
	G_debug(2, "   -> no intersection");
	return 0;
    }

    /* there is overlap or connected end points */
    G_debug(2, "   -> overlap/connected end points");

    /* end points */
    if ((ax1 == bx1 && ay1 == by1) || (ax1 == bx2 && ay1 == by2)) {
	*x1 = ax1;
	*y1 = ay1;
	G_debug(2, "    -> connected by end points");
	return 1;
    }
    if ((ax2 == bx1 && ay2 == by1) || (ax2 == bx2 && ay2 == by2)) {
	*x1 = ax2;
	*y1 = ay2;
	G_debug(2, "    -> connected by end points");
	return 1;
    }

    if (ax1 > ax2) {
	t = ax1;
	ax1 = ax2;
	ax2 = t;
	t = ay1;
	ay1 = ay2;
	ay2 = t;
    }				/* to be sure that ax1 < ax2 */
    if (bx1 > bx2) {
	t = bx1;
	bx1 = bx2;
	bx2 = t;
	t = by1;
	by1 = by2;
	by2 = t;
    }				/* to be sure that bx1 < bx2 */

    /* a contains b */
    if (ax1 <= bx1 && ax2 >= bx2) {
	G_debug(2, "    -> a contains b");
	*x1 = bx1;
	*y1 = by1;
	*x2 = bx2;
	*y2 = by2;
	if (!switched)
	    return 3;
	else
	    return 4;
    }
    /* b contains a */
    if (ax1 >= bx1 && ax2 <= bx2) {
	G_debug(2, "    -> b contains a");
	*x1 = ax1;
	*y1 = ay1;
	*x2 = ax2;
	*y2 = ay2;
	if (!switched)
	    return 4;
	else
	    return 3;
    }

    /* general overlap, 2 intersection points (lines are not vertical) */
    G_debug(2, "    -> partial overlap");
    if (bx1 > ax1 && bx1 < ax2) {	/* b1 is in a */
	if (!switched) {
	    *x1 = bx1;
	    *y1 = by1;
	    *x2 = ax2;
	    *y2 = ay2;
	}
	else {
	    *x1 = ax2;
	    *y1 = ay2;
	    *x2 = bx1;
	    *y2 = by1;
	}
	return 2;
    }
    if (bx2 > ax1 && bx2 < ax2) {	/* b2 is in a */
	if (!switched) {
	    *x1 = bx2;
	    *y1 = by2;
	    *x2 = ax1;
	    *y2 = ay1;
	}
	else {
	    *x1 = ax1;
	    *y1 = ay1;
	    *x2 = bx2;
	    *y2 = by2;
	}
	return 2;
    }

    /* should not be reached */
    G_warning(("segment_intersection_2d() ERROR (collinear non vertical segments)"));
    G_warning("%.15g %.15g", ax1, ay1);
    G_warning("%.15g %.15g", ax2, ay2);
    G_warning("x");
    G_warning("%.15g %.15g", bx1, by1);
    G_warning("%.15g %.15g", bx2, by2);

    return 0;
}
Example #9
0
void T_PlatRaise(void *platThinkerPtr)
{
    plat_t *plat = (plat_t *)platThinkerPtr;
    result_e res;

    switch(plat->state)
    {
    case PS_UP:
        res = T_MovePlane(plat->sector, plat->speed, plat->high,
                          plat->crush, 0, 1);

        // Play a "while-moving" sound?
#if __JHERETIC__
        if(!(mapTime & 31))
            S_PlaneSound((Plane *)P_GetPtrp(plat->sector, DMU_FLOOR_PLANE), SFX_PLATFORMMOVE);
#endif
#if __JDOOM__ || __JDOOM64__
        if(plat->type == PT_RAISEANDCHANGE ||
           plat->type == PT_RAISETONEARESTANDCHANGE)
        {
            if(!(mapTime & 7))
                S_PlaneSound((Plane *)P_GetPtrp(plat->sector, DMU_FLOOR_PLANE), SFX_PLATFORMMOVE);
        }
#endif
        if(res == crushed && (!plat->crush))
        {
            plat->count = plat->wait;
            plat->state = PS_DOWN;
#if __JHEXEN__
            SN_StartSequenceInSec(plat->sector, SEQ_PLATFORM);
#else
# if __JDOOM64__
            if(plat->type != PT_DOWNWAITUPDOOR) // jd64 added test
# endif
                S_PlaneSound((Plane *)P_GetPtrp(plat->sector, DMU_FLOOR_PLANE), SFX_PLATFORMSTART);
#endif
        }
        else
        {
            if(res == pastdest)
            {
                plat->count = plat->wait;
                plat->state = PS_WAIT;
#if __JHEXEN__
                SN_StopSequenceInSec(plat->sector);
#else
                S_PlaneSound((Plane *)P_GetPtrp(plat->sector, DMU_FLOOR_PLANE), SFX_PLATFORMSTOP);
#endif
                switch(plat->type)
                {
                case PT_DOWNWAITUPSTAY:
#if __JHEXEN__
                case PT_DOWNBYVALUEWAITUPSTAY:
#else
# if !__JHERETIC__
                case PT_DOWNWAITUPSTAYBLAZE:
                case PT_RAISETONEARESTANDCHANGE:
# endif
# if __JDOOM64__
                case PT_DOWNWAITUPPLUS16STAYBLAZE: // jd64
                case PT_DOWNWAITUPDOOR: // jd64
# endif
                case PT_RAISEANDCHANGE:
#endif
                    stopPlat(plat);
                    break;

                default:
                    break;
                }
            }
        }
        break;

    case PS_DOWN:
        res =
            T_MovePlane(plat->sector, plat->speed, plat->low, false, 0, -1);

        if(res == pastdest)
        {
            plat->count = plat->wait;
            plat->state = PS_WAIT;

#if __JHEXEN__ || __JDOOM64__
            switch(plat->type)
            {
# if __JHEXEN__
            case PT_UPBYVALUEWAITDOWNSTAY:
# endif
            case PT_UPWAITDOWNSTAY:
                stopPlat(plat);
                break;

            default:
                break;
            }
#endif

#if __JHEXEN__
            SN_StopSequenceInSec(plat->sector);
#else
            S_PlaneSound((Plane *)P_GetPtrp(plat->sector, DMU_FLOOR_PLANE), SFX_PLATFORMSTOP);
#endif
        }
        else
        {
            // Play a "while-moving" sound?
#if __JHERETIC__
            if(!(mapTime & 31))
                S_PlaneSound((Plane *)P_GetPtrp(plat->sector, DMU_FLOOR_PLANE), SFX_PLATFORMMOVE);
#endif
        }
        break;

    case PS_WAIT:
        if(!--plat->count)
        {
            if(FEQUAL(P_GetDoublep(plat->sector, DMU_FLOOR_HEIGHT), plat->low))
                plat->state = PS_UP;
            else
                plat->state = PS_DOWN;
#if __JHEXEN__
            SN_StartSequenceInSec(plat->sector, SEQ_PLATFORM);
#else
            S_PlaneSound((Plane *)P_GetPtrp(plat->sector, DMU_FLOOR_PLANE), SFX_PLATFORMSTART);
#endif
        }
        break;

    default:
        break;
    }
}
Example #10
0
int
main(int argc, char *argv[])
{
  char         **av, fname[STRLEN], *out_fname, *subject_name, *cp, *tp1_name, *tp2_name ;
  char         s1_name[STRLEN], s2_name[STRLEN], *sname ;
  int          ac, nargs, i, n, options, max_index ;
  int          msec, minutes, seconds, nsubjects, input ;
  struct timeb start ;
  MRI          *mri_seg, *mri_tmp, *mri_in ;
  TRANSFORM    *transform ;
//  int          counts ;
  int          t;
  RANDOM_FOREST *rf = NULL ;
  GCA           *gca = NULL ;

  Progname = argv[0] ;

  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  parms.width = parms.height = parms.depth = DEFAULT_VOLUME_SIZE ;
  parms.ntrees = 10 ;
  parms.max_depth = 10 ;
  parms.wsize = 1 ;
  parms.training_size = 100 ;
  parms.training_fraction = .5 ;
  parms.feature_fraction = 1 ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_rf_long_train.c,v 1.5 2012/06/15 12:22:28 fischl Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  // parse command line args
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
  }
  if (argc < 3)
    usage_exit(1) ;


  // options parsed.   subjects, tp1 and tp2 and rf name remaining
  out_fname = argv[argc-1] ;
  nsubjects = (argc-2)/3 ;
  for (options = i = 0 ; i < nsubjects ; i++)
  {
    if (argv[i+1][0] == '-')
    {
      nsubjects-- ;
      options++ ;
    }
  }

  printf("training on %d subject and writing results to %s\n",
         nsubjects, out_fname) ;

  // rf_inputs can be T1, PD, ...per subject
  if (parms.nvols == 0)
    parms.nvols = ninputs ;
  /* gca reads same # of inputs as we read
     from command line - not the case if we are mapping to flash */
  n = 0 ;

  //////////////////////////////////////////////////////////////////
  // set up gca direction cosines, width, height, depth defaults

  gca = GCAread(gca_name) ;
  if (gca == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read GCA from %s", Progname, gca_name) ;
  
  
  /////////////////////////////////////////////////////////////////////////
  // weird way options and subject name are mixed here
  
  /////////////////////////////////////////////////////////
  // first calculate mean
  ////////////////////////////////////////////////////////
  // going through the subject one at a time
  max_index = nsubjects+options ;
  nargs = 0 ;
  mri_in = NULL ; 
#ifdef HAVE_OPENMP
  subject_name = NULL ; sname = NULL ; t = 0 ;
//  counts = 0 ;   would be private
  input = 0 ;
  transform = NULL ;
  tp1_name = tp2_name = NULL ;
  mri_tmp = mri_seg = NULL ;
#pragma omp parallel for firstprivate(tp1_name, tp2_name, mri_in,mri_tmp, input, xform_name, transform, subjects_dir, force_inputs, conform, Progname, mri_seg, subject_name, s1_name, s2_name, sname, t, fname) shared(mri_inputs, transforms, mri_segs,argv) schedule(static,1)
#endif
  for (i = 0 ; i < max_index ; i++)
  {
    subject_name = argv[3*i+1] ;
    tp1_name = argv[3*i+2] ;
    tp2_name = argv[3*i+3] ;
    sprintf(s1_name, "%s_%s.long.%s_base", subject_name, tp1_name, subject_name) ;
    sprintf(s2_name, "%s_%s.long.%s_base", subject_name, tp2_name, subject_name) ;

    //////////////////////////////////////////////////////////////
    printf("***************************************"
	   "************************************\n");
    printf("processing subject %s, %d of %d (%s and %s)...\n", subject_name,i+1-nargs,
	   nsubjects, s1_name,s2_name);

    for (t = 0 ; t < 2 ; t++)
    {
      sname = t == 0 ? s1_name : s2_name;

      // reading this subject segmentation
      sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, seg_dir) ;
      if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	fprintf(stderr, "Reading segmentation from %s...\n", fname) ;
      mri_seg = MRIread(fname) ;
      if (!mri_seg)
	ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s",
		  Progname, fname) ;

      if ((mri_seg->type != MRI_UCHAR) && (make_uchar != 0))
      {
	MRI *mri_tmp ;
	mri_tmp = MRIchangeType(mri_seg, MRI_UCHAR, 0, 1,1);
	MRIfree(&mri_seg) ;
	mri_seg = mri_tmp ;
      }

      if (wmsa_fname)
      {
	MRI *mri_wmsa ;
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, wmsa_fname) ;
	printf("reading WMSA labels from %s...\n", fname) ;
	mri_wmsa = MRIread(fname) ;
	if (mri_wmsa == NULL)
	  ErrorExit(ERROR_NOFILE, "%s: could not read WMSA file %s", fname) ;
	MRIbinarize(mri_wmsa, mri_wmsa,  1, 0, WM_hypointensities) ;
	MRIcopyLabel(mri_wmsa, mri_seg, WM_hypointensities) ;
	lateralize_hypointensities(mri_seg) ;
	if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON )
	{
	  char s[STRLEN] ;
	  sprintf(s, "%s/%s/mri/seg_%s",
		  subjects_dir, subject_name, wmsa_fname) ;
	  MRIwrite(mri_seg, s) ;
	}
      }
      if (binarize)
      {
	int j ;
	for (j = 0 ; j < 256 ; j++)
	{
	  if (j == binarize_in)
	    MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ;
	  else
	    MRIreplaceValues(mri_seg, mri_seg, j, 0) ;
	}
      }
      if (insert_fname)
      {
	MRI *mri_insert ;
	
	sprintf(fname, "%s/%s/mri/%s",
		subjects_dir, subject_name, insert_fname) ;
	mri_insert = MRIread(fname) ;
	if (mri_insert == NULL)
	  ErrorExit(ERROR_NOFILE,
		    "%s: could not read volume from %s for insertion",
		    Progname, insert_fname) ;
	
	MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ;
	MRIcopyLabel(mri_insert, mri_seg, insert_label) ;
	MRIfree(&mri_insert) ;
      }
      
      replaceLabels(mri_seg) ;
      MRIeraseBorderPlanes(mri_seg, 1) ;

      ////////////////////////////////////////////////////////////
      if (DIAG_VERBOSE_ON)
	fprintf(stderr,
		"Gather all input volumes for the subject %s.\n",
		subject_name);
      // inputs must be coregistered
      // note that inputs are T1, PD, ... per subject (same TE, TR, FA)
      for (input = 0 ; input < ninputs ; input++)
      {
	//////////// set the gca type //////////////////////////////
	// is this T1/PD training?
	// how can we allow flash data training ???????
	// currently checks the TE, TR, FA to be the same for all inputs
	// thus we cannot allow flash data training.
	////////////////////////////////////////////////////////////
	
	sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname,input_names[input]);
	if (DIAG_VERBOSE_ON)
	  printf("reading co-registered input from %s...\n", fname) ;
	fprintf(stderr, "   reading input %d: %s\n", input, fname);
	mri_tmp = MRIread(fname) ;
	if (!mri_tmp)
	  ErrorExit
	    (ERROR_NOFILE,
	     "%s: could not read image from file %s", Progname, fname) ;
	// input check 1
	if (getSliceDirection(mri_tmp) != MRI_CORONAL)
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must be in coronal direction, but it is not\n",
	     fname);
	}
	// input check 2
	if (conform &&
	    (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1))
	{
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: must have 1mm voxel size, but have (%f, %f, %f)\n",
	     fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize);
	}
	// input check 3 is removed.  now we can handle c_(ras) != 0 case
	// input check 4
	if (i == 0)
	{
	  TRs[input] = mri_tmp->tr ;
	  FAs[input] = mri_tmp->flip_angle ;
	  TEs[input] = mri_tmp->te ;
	}
	else if ((force_inputs == 0) &&
		 (!FEQUAL(TRs[input],mri_tmp->tr) ||
		  !FEQUAL(FAs[input],mri_tmp->flip_angle) ||
		  !FEQUAL(TEs[input], mri_tmp->te)))
	  ErrorExit
	    (ERROR_BADPARM,
	     "%s: subject %s input volume %s: sequence parameters "
	     "(%2.1f, %2.1f, %2.1f)"
	     "don't match other inputs (%2.1f, %2.1f, %2.1f)",
	     Progname, subject_name, fname,
	     mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te,
	     TRs[input], DEGREES(FAs[input]), TEs[input]) ;
	// first time do the following
	if (input == 0)
	{
	  int nframes = ninputs ;
	  
	  ///////////////////////////////////////////////////////////
	  mri_in = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
				    mri_tmp->type, nframes) ;
	  if (!mri_in)
	    ErrorExit
	      (ERROR_NOMEMORY,
	       "%s: could not allocate input volume %dx%dx%dx%d",
	       mri_tmp->width, mri_tmp->height, mri_tmp->depth,nframes) ;
	  MRIcopyHeader(mri_tmp, mri_in) ;
	}
	// -mask option ////////////////////////////////////////////
	if (mask_fname)
	{
	  MRI *mri_mask ;
	  
	  sprintf(fname, "%s/%s/mri/%s",
		  subjects_dir, subject_name, mask_fname);
	  printf("reading volume %s for masking...\n", fname) ;
	  mri_mask = MRIread(fname) ;
	  if (!mri_mask)
	  ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
		    Progname, fname) ;
	
	  MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
	  MRIfree(&mri_mask) ;
	}
	MRIcopyFrame(mri_tmp, mri_in, 0, input) ;
	MRIfree(&mri_tmp) ;

      }// end of inputs per subject
    
    
      /////////////////////////////////////////////////////////
      // xform_name is given, then we can use the consistent c_(r,a,s) for gca
      /////////////////////////////////////////////////////////
      if (xform_name)
      {
	// we read talairach.xfm which is a RAS-to-RAS
	sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, sname, xform_name) ;
	if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
	  printf("INFO: reading transform file %s...\n", fname);
	if (!FileExists(fname))
	{
	  fprintf(stderr,"ERROR: cannot find transform file %s\n",fname);
	  exit(1);
	}
	transform = TransformRead(fname);
	if (!transform)
	  ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s",
		    Progname, fname);
	
//        modify_transform(transform, mri_in, gca);
	// Here we do 2 things
	// 1. modify gca direction cosines to
	// that of the transform destination (both linear and non-linear)
	// 2. if ras-to-ras transform,
      // then change it to vox-to-vox transform (linear case)
	
      // modify transform to store inverse also
	TransformInvert(transform, mri_in) ;
      }
      else
      {
//        GCAreinit(mri_in, gca);
	// just use the input value, since dst = src volume
	transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;
      }
      
      /////////////////////////////////////////////////////////
      if (do_sanity_check)
      {
	// conduct a sanity check of particular labels, most importantly
	// hippocampus, that such labels do not exist in talairach coords
	// where they are known not to belong (indicating a bad manual edit)
	int errs = check(mri_seg, subjects_dir, subject_name);
	if (errs) 
	{
	  printf(
	    "ERROR: mri_ca_train: possible bad training data! subject:\n"
	    "\t%s/%s\n\n", subjects_dir, subject_name);
	  fflush(stdout) ;
	  sanity_check_badsubj_count++;
	}
      }
      
      mri_segs[i][t] = mri_seg ;
      mri_inputs[i][t] = mri_in ;
      transforms[i][t] = transform ;
    }
  }
  rf = train_rforest(mri_inputs, mri_segs, transforms, nsubjects, gca, &parms, wm_thresh,wmsa_whalf, 2) ;
  printf("writing random forest to %s\n", out_fname) ;
  if (RFwrite(rf, out_fname) != NO_ERROR)
    ErrorExit
      (ERROR_BADFILE, "%s: could not write rf to %s", Progname, out_fname) ;
  
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("classifier array training took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
  }
Example #11
0
int EV_Teleport(Line* line, int side, mobj_t* mo, dd_bool spawnFog)
{
    mobj_t* dest;

    // Clients cannot teleport on their own.
    if(IS_CLIENT) return 0;

    if(mo->flags2 & MF2_NOTELEPORT) return 0;

    // Don't teleport if hit back of line, so you can get out of teleporter.
    if(side == 1) return 0;

    if((dest = getTeleportDestination(P_ToXLine(line)->tag)) != NULL)
    {
        // A suitable destination has been found.
        coord_t oldPos[3], aboveFloor;
        angle_t oldAngle;
        mobj_t* fog;
        uint an;

        memcpy(oldPos, mo->origin, sizeof(mo->origin));
        oldAngle = mo->angle;
        aboveFloor = mo->origin[VZ] - mo->floorZ;

        if(!P_TeleportMove(mo, dest->origin[VX], dest->origin[VY], false))
            return 0;

        mo->origin[VZ] = mo->floorZ;

        if(spawnFog)
        {
            // Spawn teleport fog at source and destination.
            if((fog = P_SpawnMobj(MT_TFOG, oldPos, oldAngle + ANG180, 0)))
                S_StartSound(SFX_TELEPT, fog);

            an = dest->angle >> ANGLETOFINESHIFT;
            if((fog = P_SpawnMobjXYZ(MT_TFOG, dest->origin[VX] + 20 * FIX2FLT(finecosine[an]),
                                              dest->origin[VY] + 20 * FIX2FLT(finesine[an]),
                                              mo->origin[VZ], dest->angle + ANG180, 0)))
            {
                // Emit sound, where?
                S_StartSound(SFX_TELEPT, fog);
            }
        }

        mo->angle = dest->angle;
        if(mo->flags2 & MF2_FLOORCLIP)
        {
            mo->floorClip = 0;

            if(FEQUAL(mo->origin[VZ], P_GetDoublep(Mobj_Sector(mo), DMU_FLOOR_HEIGHT)))
            {
                terraintype_t const *tt = P_MobjFloorTerrain(mo);
                if(tt->flags & TTF_FLOORCLIP)
                {
                    mo->floorClip = 10;
                }
            }
        }

        mo->mom[MX] = mo->mom[MY] = mo->mom[MZ] = 0;

        // $voodoodolls Must be the real player.
        if(mo->player && mo->player->plr->mo == mo)
        {
            mo->reactionTime = 18; // Don't move for a bit.
            if(mo->player->powers[PT_FLIGHT] && aboveFloor > 0)
            {
                mo->origin[VZ] = mo->floorZ + aboveFloor;
                if(mo->origin[VZ] + mo->height > mo->ceilingZ)
                {
                    mo->origin[VZ] = mo->ceilingZ - mo->height;
                }
            }
            else
            {
                //mo->dPlayer->clLookDir = 0; /* $unifiedangles */
                mo->dPlayer->lookDir = 0;
            }
            mo->player->viewHeight = (coord_t) cfg.common.plrViewHeight;
            mo->player->viewHeightDelta = 0;
            mo->player->viewZ = mo->origin[VZ] + mo->player->viewHeight;
            mo->player->viewOffset[VX] = mo->player->viewOffset[VY] = mo->player->viewOffset[VZ] = 0;
            mo->player->bob = 0;

            //mo->dPlayer->clAngle = mo->angle; /* $unifiedangles */
            mo->dPlayer->flags |= DDPF_FIXANGLES | DDPF_FIXORIGIN | DDPF_FIXMOM;
        }

        return 1;
    }
Example #12
0
void Mobj_XYMoveStopping(mobj_t *mo)
{
    DENG_ASSERT(mo != 0);

    player_t *player = mo->player;

    if(player && (P_GetPlayerCheats(player) & CF_NOMOMENTUM))
    {
        // Debug option for no sliding at all.
        mo->mom[MX] = mo->mom[MY] = 0;
        return;
    }

    if(mo->flags & (MF_MISSILE | MF_SKULLFLY))
    {
        // No friction for missiles.
        return;
    }

    if(mo->origin[VZ] > mo->floorZ && !mo->onMobj && !(mo->flags2 & MF2_FLY))
    {
        // No friction when falling.
        return;
    }

#ifndef __JHEXEN__
    if(cfg.slidingCorpses)
    {
        // $dropoff_fix: Add objects falling off ledges. Does not apply to players!
        if(((mo->flags & MF_CORPSE) || (mo->intFlags & MIF_FALLING)) && !mo->player)
        {
            // Do not stop sliding if halfway off a step with some momentum.
            if(!INRANGE_OF(mo->mom[MX], 0, DROPOFFMOMENTUM_THRESHOLD) ||
               !INRANGE_OF(mo->mom[MY], 0, DROPOFFMOMENTUM_THRESHOLD))
            {
                if(!FEQUAL(mo->floorZ, P_GetDoublep(Mobj_Sector(mo), DMU_FLOOR_HEIGHT)))
                    return;
            }
        }
    }
#endif

    bool isVoodooDoll = Mobj_IsVoodooDoll(mo);
    bool belowWalkStop = (INRANGE_OF(mo->mom[MX], 0, WALKSTOP_THRESHOLD) &&
                          INRANGE_OF(mo->mom[MY], 0, WALKSTOP_THRESHOLD));

    bool belowStandSpeed = false;
    bool isMovingPlayer  = false;
    if(player)
    {
        belowStandSpeed = (INRANGE_OF(mo->mom[MX], 0, STANDSPEED) &&
                           INRANGE_OF(mo->mom[MY], 0, STANDSPEED));
        isMovingPlayer = (!FEQUAL(player->plr->forwardMove, 0) ||
                        !FEQUAL(player->plr->sideMove, 0));
    }

    // Stop player walking animation (only real players).
    if(!isVoodooDoll && player && belowStandSpeed && !isMovingPlayer &&
        !IS_NETWORK_SERVER) // Netgame servers use logic elsewhere for player animation.
    {
        // If in a walking frame, stop moving.
        if(P_PlayerInWalkState(player))
        {
            P_MobjChangeState(player->plr->mo, statenum_t(PCLASS_INFO(player->class_)->normalState));
        }
    }

    // Apply friction.
    if(belowWalkStop && !isMovingPlayer)
    {
        // $voodoodolls: Do not zero mom for voodoo dolls!
        if(!isVoodooDoll)
        {
            // Momentum is below the walkstop threshold; stop it completely.
            mo->mom[MX] = mo->mom[MY] = 0;

            // $voodoodolls: Stop view bobbing if this isn't a voodoo doll.
            if(player) player->bob = 0;
        }
    }
    else
    {
        coord_t friction = Mobj_Friction(mo);
        mo->mom[MX] *= friction;
        mo->mom[MY] *= friction;
    }
}
Example #13
0
int
main(int argc, char *argv[])
{
  char         **av, in_surf_fname[STRLEN], *in_patch_fname, *out_patch_fname,
  fname[STRLEN], path[STRLEN], *cp, hemi[10] ;
  int          ac, nargs ;
  MRI_SURFACE  *mris ;
  MRI          *mri_vertices ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mris_flatten.c,v 1.42 2016/12/10 22:57:46 fischl Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Gdiag |= DIAG_SHOW ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  Gdiag |= (DIAG_SHOW | DIAG_WRITE) ;
  memset(&parms, 0, sizeof(parms)) ;
  parms.dt = .1 ;
  parms.projection = PROJECT_PLANE ;
  parms.tol = 0.2 ;
  parms.n_averages = 1024 ;
  parms.l_dist = 1.0 ;
  parms.l_nlarea = 1.0 ;
  parms.niterations = 40 ;
  parms.area_coef_scale = 1.0 ;
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.98 /* DT_DECREASE*/ ;
  parms.error_ratio = 1.03 /*ERROR_RATIO */;
  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
  parms.momentum = 0.9 ;
  parms.desired_rms_height = -1.0 ;
  parms.base_name[0] = 0 ;
  parms.nbhd_size = 7 ;    /* out to 7-connected neighbors */
  parms.max_nbrs = 12 ;    /* 12 at each distance */
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
    print_help() ;

  parms.base_dt = base_dt_scale * parms.dt ;
  in_patch_fname = argv[1] ;
  out_patch_fname = argv[2] ;
  FileNamePath(in_patch_fname, path) ;
  cp = strrchr(in_patch_fname, '/') ;
  if (!cp)
    cp = in_patch_fname ;
  cp = strchr(cp, '.') ;
  if (cp)
  {
    strncpy(hemi, cp-2, 2) ;
    hemi[2] = 0 ;
  }
  else
    strcpy(hemi, "lh") ;
  if (one_surf_flag)
    sprintf(in_surf_fname, "%s", in_patch_fname) ;
  else
    sprintf(in_surf_fname, "%s/%s.%s", path, hemi, original_surf_name) ;

  if (parms.base_name[0] == 0)
  {
    FileNameOnly(out_patch_fname, fname) ;
    cp = strchr(fname, '.') ;
    if (cp)
      strcpy(parms.base_name, cp+1) ;
    else
      strcpy(parms.base_name, "flattened") ;
  }

  mris = MRISread(in_surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, in_surf_fname) ;

  if (sphere_flag)
  {
    MRIScenter(mris, mris) ;
    mris->radius = MRISaverageRadius(mris) ;
    MRISstoreMetricProperties(mris) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  }

  if (Gdiag_no >= 0)
  {
    int n ;
    printf("vertex %d has %d nbrs before patch:\n",
           Gdiag_no, mris->vertices[Gdiag_no].vnum) ;
    for (n = 0 ; n < mris->vertices[Gdiag_no].vnum ; n++)
      printf("\t%d\n", mris->vertices[Gdiag_no].v[n]) ;
  }
  if (one_surf_flag)  /* only have the 1 surface - no patch file */
  {
    mris->patch = 1 ;
    mris->status = MRIS_PATCH ;
    if (!FEQUAL(rescale,1))
    {
      MRISscaleBrain(mris, mris, rescale) ;
      MRIScomputeMetricProperties(mris) ;
    }
    MRISstoreMetricProperties(mris) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;

  } 
  else
  {
    MRISresetNeighborhoodSize(mris, mris->vertices[0].nsize) ; // set back to max
    if (label_fname) // read in a label instead of a patch
    {
      LABEL *area ;
      area = LabelRead(NULL, label_fname) ;
      if (area == NULL)
        ErrorExit(ERROR_BADPARM, "%s: could not read label file %s",
                  Progname, label_fname) ;

      LabelDilate(area, mris, dilate_label, CURRENT_VERTICES) ;
      MRISclearMarks(mris) ;
      LabelMark(area, mris) ;
      MRISripUnmarked(mris) ;
      MRISripFaces(mris);
      mris->patch = 1 ;
      mris->status = MRIS_CUT ;
      LabelFree(&area) ;
      printf("%d valid vertices (%2.1f %% of total)\n",
             MRISvalidVertices(mris), 
             100.0*MRISvalidVertices(mris)/mris->nvertices) ;
    }
    else
    {
      if (MRISreadPatch(mris, in_patch_fname) != NO_ERROR)
        ErrorExit(ERROR_BADPARM, "%s: could not read patch file %s",
                  Progname, in_patch_fname) ;
      if (dilate)
      {
        printf("dilating patch %d times\n", dilate) ;
        MRISdilateRipped(mris, dilate) ;
        printf("%d valid vertices (%2.1f %% of total)\n",
               MRISvalidVertices(mris), 100.0*MRISvalidVertices(mris)/mris->nvertices) ;
      }
    }
    MRISremoveRipped(mris) ;
    MRISupdateSurface(mris) ;
#if 0
    mris->nsize = 1 ; // before recalculation of 2 and 3-nbrs
    {
      int vno ;
      VERTEX *v ;
      for (vno= 0 ; vno < mris->nvertices ; vno++)
      {
        v = &mris->vertices[vno] ;
        v->vtotal = v->vnum ;
        v->nsize = 1 ;
      }
    }
    MRISsetNeighborhoodSize(mris, nbrs) ;
#endif
  }

  if (Gdiag_no >= 0)
    printf("vno %d is %sin patch\n", Gdiag_no,
           mris->vertices[Gdiag_no].ripflag ? "NOT " : "") ;

  if (Gdiag_no >= 0 && mris->vertices[Gdiag_no].ripflag == 0)
  {
    int n ;
    printf("vertex %d has %d nbrs after patch:\n",
           Gdiag_no, mris->vertices[Gdiag_no].vnum) ;
    for (n = 0 ; n < mris->vertices[Gdiag_no].vnum ; n++)
      printf("\t%d\n", mris->vertices[Gdiag_no].v[n]) ;
  }
  fprintf(stderr, "reading original vertex positions...\n") ;
  if (!FZERO(disturb))
    mrisDisturbVertices(mris, disturb) ;
  if (parms.niterations > 0)
  {
    MRISresetNeighborhoodSize(mris, nbrs) ;

    if (!FZERO(parms.l_unfold) || !FZERO(parms.l_expand))
    {
      static INTEGRATION_PARMS p2 ;
      sprintf(in_surf_fname, "%s/%s.%s", path, hemi, original_surf_name) ;
      if (stricmp(original_unfold_surf_name,"none") == 0)
      {
        printf("using current position of patch as initial position\n") ;
        MRISstoreMetricProperties(mris) ;  /* use current positions */
      }
      else if (!sphere_flag && !one_surf_flag)
        MRISreadOriginalProperties(mris, original_unfold_surf_name) ;
      *(&p2) = *(&parms) ;
      p2.l_dist = 0 ;
      p2.niterations = 100 ;
      p2.nbhd_size = p2.max_nbrs = 1 ;
      p2.n_averages = 0 ;
      p2.write_iterations = parms.write_iterations > 0 ? 25 : 0 ;
      p2.tol = -1 ;
      p2.dt = 0.5 ;
      p2.l_area = 0.0 ;
      p2.l_spring = 0.9 ;
      p2.l_convex = 0.9 ;
      p2.momentum = 0 ;
      p2.integration_type = INTEGRATE_MOMENTUM ;
      MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
#if 0
      p2.flags |= IPFLAG_NO_SELF_INT_TEST ;
      printf("expanding surface....\n") ;
      MRISexpandSurface(mris, 4.0, &p2) ;  // push it away from fissure
#endif
      p2.niterations = 100 ;
      MRISunfold(mris, &p2, 1) ;
      p2.niterations = 300 ;
      p2.l_unfold *= 0.25 ;
      MRISunfold(mris, &p2, 1) ;
      p2.l_unfold *= 0.25 ;
      MRISunfold(mris, &p2, 1) ;
#if 0
      printf("smoothing unfolded surface..\n");
      p2.niterations = 200 ;
      p2.l_unfold = 0 ;  // just smooth it
      MRISunfold(mris, &p2, max_passes) ;
#endif
      parms.start_t = p2.start_t ;
      parms.l_unfold = parms.l_convex = parms.l_boundary = parms.l_expand=0 ;
      MRIfree(&parms.mri_dist) ;
    }

    sprintf(in_surf_fname, "%s/%s.%s", path, hemi, original_surf_name) ;
    if (!sphere_flag && !one_surf_flag)
      MRISreadOriginalProperties(mris, original_surf_name) ;
    if (randomly_flatten)
      MRISflattenPatchRandomly(mris) ;
    else
      MRISflattenPatch(mris) ;

    /* optimize metric properties of flat map */
    fprintf(stderr,"minimizing metric distortion induced by projection...\n");
    MRISscaleBrain(mris, mris, scale) ;
    MRIScomputeMetricProperties(mris) ;
    MRISunfold(mris, &parms, max_passes) ;
    MRIScenter(mris, mris) ;
    fprintf(stderr, "writing flattened patch to %s\n", out_patch_fname) ;
    MRISwritePatch(mris, out_patch_fname) ;
  }

  if (plane_flag || sphere_flag)
  {
    char fname[STRLEN] ;
    FILE *fp ;

#if 0
    sprintf(fname, "%s.%s.out",
            mris->hemisphere == RIGHT_HEMISPHERE ? "rh" : "lh",
            parms.base_name);
#else
    sprintf(fname, "flatten.log") ;
#endif
    fp = fopen(fname, "a") ;

    if (plane_flag)
      MRIScomputeAnalyticDistanceError(mris, MRIS_PLANE, fp) ;
    else if (sphere_flag)
      MRIScomputeAnalyticDistanceError(mris, MRIS_SPHERE, fp) ;
    fclose(fp) ;
  }

  if (mri_overlay)
  {
    MRI  *mri_flattened ;
    char fname[STRLEN] ;

    // if it is NxNx1x1 reshape it to be Nx1x1xN
    if ( mri_overlay->width == mri_overlay->height &&
       mri_overlay->depth == 1 &&
       mri_overlay->nframes == 1)
    {
      MRI *mri_tmp ;
      printf("reshaping to move 2nd dimension to time\n") ;
      mri_tmp = mri_reshape( mri_overlay, mri_overlay->width, 1, 1, mri_overlay->height);
      MRIfree( &mri_overlay );
      mri_overlay = mri_tmp;
    }

    // put in some special code that knows about icosahedra
    if (mris->nvertices == 163842 ||  // ic7
        mris->nvertices == 40962 ||  // ic6
        mris->nvertices == 10242 ||  // ic5
        mris->nvertices == 2562)  // ic4
    {
      int nvals, start_index, end_index ;
      MRI *mri_tmp ;
      
      printf("cross-hemispheric correlation matrix detected, reshaping...\n") ;
      nvals = mri_overlay->width * mri_overlay->height * mri_overlay->depth ;
      if (nvals == 2*mris->nvertices)   // it's a corr matrix for both hemis
      {
        if (mris->hemisphere == LEFT_HEMISPHERE || mris->hemisphere == RIGHT_HEMISPHERE)
        {
          if (mris->hemisphere == LEFT_HEMISPHERE)
          {
            start_index = 0 ; 
            end_index = mris->nvertices-1 ;
          }
          else
          {
            start_index = mris->nvertices ; 
            end_index = 2*mris->nvertices-1 ;
          }
          mri_tmp = MRIextract(mri_overlay, NULL, start_index, 0, 0, mris->nvertices, 1, 1) ;
          MRIfree(&mri_overlay) ;
          mri_overlay = mri_tmp;
        }
        else // both hemis
        {
        }
      }
    }
    
    printf("resampling overlay (%d x %d x %d x %d) into flattened coordinates..\n",
           mri_overlay->width, mri_overlay->height, mri_overlay->depth, mri_overlay->nframes) ;
    if (synth_name)
    {
      LABEL *area_lh, *area_rh ;
      char  fname[STRLEN], path[STRLEN], fname_no_path[STRLEN] ;
      int   vno, n, vno2, n2 ;

      MRIsetValues(mri_overlay, 0) ;
      FileNameOnly(synth_name, fname_no_path) ;
      FileNamePath(synth_name, path) ;
      sprintf(fname, "%s/lh.%s", path, fname_no_path) ;
      area_lh = LabelRead(NULL, fname) ;
      if (area_lh == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",
                  Progname,fname) ;
      sprintf(fname, "%s/rh.%s", path, fname_no_path) ;
      area_rh = LabelRead(NULL, fname) ;
      if (area_rh == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",
                  Progname,fname) ;
#if 0
      for (n = 0 ; n < area_lh->n_points ; n++)
      {
        vno = area_lh->lv[n].vno ;
        MRIsetVoxVal(mri_overlay, vno, 0, 0, vno, 1) ;
	printf("synthesizing map with vno %d: (%2.1f, %2.1f)\n", vno, mris->vertices[vno].x, mris->vertices[vno].y) ;
        break ;
      }
#else
      for (n = 0 ; n < area_lh->n_points ; n++)
      {
        vno = area_lh->lv[n].vno ;
        if (vno >= 0)
        {
          for (n2 = 0 ; n2 < area_lh->n_points ; n2++)
          {
            vno2 = area_lh->lv[n2].vno ;
            if (vno2 >= 0)
              MRIsetVoxVal(mri_overlay, vno, 0, 0, vno2, 1) ;
          }
          for (n2 = 0 ; n2 < area_rh->n_points ; n2++)
          {
            vno2 = area_rh->lv[n2].vno ;
            if (vno2 >= 0)
              MRIsetVoxVal(mri_overlay, vno, 0, 0, mris->nvertices+vno2, 1) ;
          }
        }
      }
#endif
    }

    mri_flattened = MRIflattenOverlay(mris, mri_overlay, NULL, 1.0, label_overlay, &mri_vertices) ;
    printf("writing flattened overlay to %s\n", out_patch_fname) ;
    MRIwrite(mri_flattened, out_patch_fname) ;
    MRIfree(&mri_flattened) ;

    FileNameRemoveExtension(out_patch_fname, fname) ;
    strcat(fname, ".vnos.mgz") ;
    printf("writing flattened vertex #s to %s\n", fname) ;
    MRIwrite(mri_vertices, fname) ;
    MRIfree(&mri_vertices) ;
  }
#if 0
  sprintf(fname, "%s.area_error", out_fname) ;
  printf("writing area errors to %s\n", fname) ;
  MRISwriteAreaError(mris, fname) ;
  sprintf(fname, "%s.angle_error", out_fname) ;
  printf("writing angle errors to %s\n", fname) ;
  MRISwriteAngleError(mris, fname) ;
  MRISfree(&mris) ;
#endif

  exit(0) ;
  return(0) ;  /* for ansi */
}
Example #14
0
bool
operator==(vector A, vector B)
{
	return(FEQUAL(A.dx, B.dx) && FEQUAL(A.dy, B.dy) && FEQUAL(A.dz, B.dz));
}
Example #15
0
int EV_OpenPillar(Line * /*line*/, byte *args)
{
    iterlist_t *list = P_GetSectorIterListForTag((int) args[0], false);
    if(!list) return 0;

    int rtn = 0;

    IterList_SetIteratorDirection(list, ITERLIST_FORWARD);
    IterList_RewindIterator(list);

    Sector *sec;
    while((sec = (Sector *)IterList_MoveIterator(list)))
    {
        // If already moving keep going...
        if(P_ToXSector(sec)->specialData)
            continue;

        if(!FEQUAL(P_GetDoublep(sec, DMU_FLOOR_HEIGHT),
                   P_GetDoublep(sec, DMU_CEILING_HEIGHT)))
            continue; // Pillar isn't closed.

        rtn = 1;

        pillar_t *pillar = (pillar_t *)Z_Calloc(sizeof(*pillar), PU_MAP, 0);
        pillar->thinker.function = (thinkfunc_t) T_BuildPillar;
        Thinker_Add(&pillar->thinker);

        P_ToXSector(sec)->specialData = pillar;
        pillar->sector = sec;
        if(!args[2])
        {
            P_FindSectorSurroundingLowestFloor(sec,
                P_GetDoublep(sec, DMU_FLOOR_HEIGHT), &pillar->floorDest);
        }
        else
        {
            pillar->floorDest =
                P_GetDoublep(sec, DMU_FLOOR_HEIGHT) - (coord_t) args[2];
        }

        if(!args[3])
        {
            P_FindSectorSurroundingHighestCeiling(sec, 0, &pillar->ceilingDest);
        }
        else
        {
            pillar->ceilingDest =
                P_GetDoublep(sec, DMU_CEILING_HEIGHT) + (coord_t) args[3];
        }

        if(P_GetDoublep(sec, DMU_FLOOR_HEIGHT) - pillar->floorDest >=
           pillar->ceilingDest - P_GetDoublep(sec, DMU_CEILING_HEIGHT))
        {
            pillar->floorSpeed = (float) args[1] * (1.0f / 8);
            pillar->ceilingSpeed =
                (P_GetDoublep(sec, DMU_CEILING_HEIGHT) - pillar->ceilingDest) *
                    (pillar->floorSpeed / (pillar->floorDest - P_GetDoublep(sec, DMU_FLOOR_HEIGHT)));
        }
        else
        {
            pillar->ceilingSpeed = (float) args[1] * (1.0f / 8);
            pillar->floorSpeed =
                (pillar->floorDest - P_GetDoublep(sec, DMU_FLOOR_HEIGHT)) *
                    (pillar->ceilingSpeed / (P_GetDoublep(sec, DMU_CEILING_HEIGHT) - pillar->ceilingDest));
        }

        pillar->direction = -1; // Open the pillar.
        SN_StartSequence((mobj_t *)P_GetPtrp(pillar->sector, DMU_EMITTER),
                         SEQ_PLATFORM + P_ToXSector(pillar->sector)->seqType);
    }

    return rtn;
}
int
main(int argc, char *argv[]) {
    char         **av, fname[STRLEN], *out_fname, *subject_name, *cp ;
    int          ac, nargs, i, n, noint = 0, options ;
    int          msec, minutes, seconds, nsubjects, input ;
    struct timeb start ;
    GCA          *gca ;
    MRI          *mri_seg, *mri_tmp, *mri_inputs ;
    TRANSFORM    *transform ;
    LTA          *lta;
    GCA_BOUNDARY *gcab ;

    Progname = argv[0] ;

    ErrorInit(NULL, NULL, NULL) ;
    DiagInit(NULL, NULL, NULL) ;

    TimerStart(&start) ;

    parms.use_gradient = 0 ;
    spacing = 8 ;

    /* rkt: check for and handle version tag */
    nargs = handle_version_option
            (argc, argv,
             "$Id: mri_gcab_train.c,v 1.4 2011/03/16 20:23:33 fischl Exp $",
             "$Name:  $");
    if (nargs && argc - nargs == 1)
        exit (0);
    argc -= nargs;

    // parse command line args
    ac = argc ;
    av = argv ;
    for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
        nargs = get_option(argc, argv) ;
        argc -= nargs ;
        argv += nargs ;
    }

    printf("reading gca from %s\n", argv[1]) ;
    gca = GCAread(argv[1]) ;
    if (!gca)
        exit(Gerror) ;

    if (!strlen(subjects_dir)) /* hasn't been set on command line */
    {
        cp = getenv("SUBJECTS_DIR") ;
        if (!cp)
            ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                      Progname);
        strcpy(subjects_dir, cp) ;
        if (argc < 4)
            usage_exit(1) ;
    }

    // options parsed.   subjects and gca name remaining
    out_fname = argv[argc-1] ;
    nsubjects = argc-3 ;
    for (options = i = 0 ; i < nsubjects ; i++) {
        if (argv[i+1][0] == '-') {
            nsubjects-- ;
            options++ ;
        }
    }

    printf("training on %d subject and writing results to %s\n",
           nsubjects, out_fname) ;

    n = 0 ;

    gcab = GCABalloc(gca, 8, 0, 30, 10, target_label);
    strcpy(gcab->gca_fname, argv[1]) ;
    // going through the subject one at a time
    for (nargs = i = 0 ; i < nsubjects+options ; i++) {
        subject_name = argv[i+2] ;
        //////////////////////////////////////////////////////////////
        printf("***************************************"
               "************************************\n");
        printf("processing subject %s, %d of %d...\n", subject_name,i+1-nargs,
               nsubjects);

        if (stricmp(subject_name, "-NOINT") == 0) {
            printf("not using intensity information for subsequent subjects...\n");
            noint = 1 ;
            nargs++ ;
            continue ;
        } else if (stricmp(subject_name, "-INT") == 0) {
            printf("using intensity information for subsequent subjects...\n");
            noint = 0 ;
            nargs++ ;
            continue ;
        }
        // reading this subject segmentation
        sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, seg_dir) ;
        if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
            fprintf(stderr, "Reading segmentation from %s...\n", fname) ;
        mri_seg = MRIread(fname) ;
        if (!mri_seg)
            ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s",
                      Progname, fname) ;
        if ((mri_seg->type != MRI_UCHAR) && (mri_seg->type != MRI_FLOAT)) {
            ErrorExit
            (ERROR_NOFILE,
             "%s: segmentation file %s is not type UCHAR or FLOAT",
             Progname, fname) ;
        }

        if (binarize) {
            int j ;
            for (j = 0 ; j < 256 ; j++) {
                if (j == binarize_in)
                    MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ;
                else
                    MRIreplaceValues(mri_seg, mri_seg, j, 0) ;
            }
        }
        if (insert_fname) {
            MRI *mri_insert ;

            sprintf(fname, "%s/%s/mri/%s",
                    subjects_dir, subject_name, insert_fname) ;
            mri_insert = MRIread(fname) ;
            if (mri_insert == NULL)
                ErrorExit(ERROR_NOFILE,
                          "%s: could not read volume from %s for insertion",
                          Progname, insert_fname) ;

            MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ;
            MRIcopyLabel(mri_insert, mri_seg, insert_label) ;
            MRIfree(&mri_insert) ;
        }

        replaceLabels(mri_seg) ;
        MRIeraseBorderPlanes(mri_seg, 1) ;

        for (input = 0 ; input < gca->ninputs ; input++) {
            //////////// set the gca type //////////////////////////////
            // is this T1/PD training?
            // how can we allow flash data training ???????
            // currently checks the TE, TR, FA to be the same for all inputs
            // thus we cannot allow flash data training.
            ////////////////////////////////////////////////////////////

            sprintf(fname, "%s/%s/mri/%s",
                    subjects_dir, subject_name,input_names[input]);
            if (DIAG_VERBOSE_ON)
                printf("reading co-registered input from %s...\n", fname) ;
            fprintf(stderr, "   reading input %d: %s\n", input, fname);
            mri_tmp = MRIread(fname) ;
            if (!mri_tmp)
                ErrorExit
                (ERROR_NOFILE,
                 "%s: could not read image from file %s", Progname, fname) ;
            // input check 1
            if (getSliceDirection(mri_tmp) != MRI_CORONAL) {
                ErrorExit
                (ERROR_BADPARM,
                 "%s: must be in coronal direction, but it is not\n",
                 fname);
            }
            // input check 2
            if (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1) {
                ErrorExit
                (ERROR_BADPARM,
                 "%s: must have 1mm voxel size, but have (%f, %f, %f)\n",
                 fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize);
            }
            // input check 3 is removed.  now we can handle c_(ras) != 0 case
            // input check 4
            if (i == 0) {
                TRs[input] = mri_tmp->tr ;
                FAs[input] = mri_tmp->flip_angle ;
                TEs[input] = mri_tmp->te ;
            } else if (!FEQUAL(TRs[input],mri_tmp->tr) ||
                       !FEQUAL(FAs[input],mri_tmp->flip_angle) ||
                       !FEQUAL(TEs[input], mri_tmp->te))
                ErrorExit
                (ERROR_BADPARM,
                 "%s: subject %s input volume %s: sequence parameters "
                 "(%2.1f, %2.1f, %2.1f)"
                 "don't match other inputs (%2.1f, %2.1f, %2.1f)",
                 Progname, subject_name, fname,
                 mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te,
                 TRs[input], DEGREES(FAs[input]), TEs[input]) ;
            // first time do the following
            if (input == 0) {
                int nframes = gca->ninputs ;

                ///////////////////////////////////////////////////////////
                mri_inputs =
                    MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,
                                     mri_tmp->type, nframes) ;
                if (!mri_inputs)
                    ErrorExit
                    (ERROR_NOMEMORY,
                     "%s: could not allocate input volume %dx%dx%dx%d",
                     mri_tmp->width, mri_tmp->height, mri_tmp->depth,nframes) ;
                MRIcopyHeader(mri_tmp, mri_inputs) ;
            }
            // -mask option ////////////////////////////////////////////
            if (mask_fname)
            {
                MRI *mri_mask ;

                sprintf(fname, "%s/%s/mri/%s",
                        subjects_dir, subject_name, mask_fname);
                printf("reading volume %s for masking...\n", fname) ;
                mri_mask = MRIread(fname) ;
                if (!mri_mask)
                    ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n",
                              Progname, fname) ;

                MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ;
                MRIfree(&mri_mask) ;
            }
            MRIcopyFrame(mri_tmp, mri_inputs, 0, input) ;
            MRIfree(&mri_tmp) ;
        }// end of inputs per subject


        /////////////////////////////////////////////////////////
        // xform_name is given, then we can use the consistent c_(r,a,s) for gca
        /////////////////////////////////////////////////////////
        if (xform_name)
        {
            // we read talairach.xfm which is a RAS-to-RAS
            sprintf(fname, "%s/%s/mri/transforms/%s",
                    subjects_dir, subject_name, xform_name) ;
            if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                printf("INFO: reading transform file %s...\n", fname);
            if (!FileExists(fname))
            {
                fprintf(stderr,"ERROR: cannot find transform file %s\n",fname);
                exit(1);
            }
            transform = TransformRead(fname);
            if (!transform)
                ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s",
                          Progname, fname);

            modify_transform(transform, mri_inputs, gca);
            // Here we do 2 things
            // 1. modify gca direction cosines to
            // that of the transform destination (both linear and non-linear)
            // 2. if ras-to-ras transform,
            // then change it to vox-to-vox transform (linear case)

            // modify transform to store inverse also
            TransformInvert(transform, mri_inputs) ;
            // verify inverse
            lta = (LTA *) transform->xform;
        }
        else
        {
            GCAreinit(mri_inputs, gca);
            // just use the input value, since dst = src volume
            transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;
        }


        ////////////////////////////////////////////////////////////////////
        // train gca
        ////////////////////////////////////////////////////////////////////
        // segmentation is seg volume
        // inputs       is the volumes of all inputs
        // transform    is for this subject
        // noint        is whether to use intensity information or not
        GCABtrain(gcab, mri_inputs, mri_seg, transform, target_label) ;
        MRIfree(&mri_seg) ;
        MRIfree(&mri_inputs) ;
        TransformFree(&transform) ;
    }
    GCABcompleteTraining(gcab) ;

    if (smooth > 0) {
        printf("regularizing conditional densities with smooth=%2.2f\n", smooth) ;
        GCAregularizeConditionalDensities(gca, smooth) ;
    }
    if (navgs) {
        printf("applying mean filter %d times to conditional densities\n", navgs) ;
        GCAmeanFilterConditionalDensities(gca, navgs) ;
    }

    printf("writing trained GCAB to %s...\n", out_fname) ;
    if (GCABwrite(gcab, out_fname) != NO_ERROR)
        ErrorExit
        (ERROR_BADFILE, "%s: could not write gca to %s", Progname, out_fname) ;

    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
        MRI *mri ;

        mri = GCAbuildMostLikelyVolume(gca, NULL) ;
        MRIwrite(mri, "m.mgz") ;
        MRIfree(&mri) ;
    }

    if (histo_fname) {
        FILE *fp ;
        int   histo_counts[10000], xn, yn, zn, max_count ;
        GCA_NODE  *gcan ;

        memset(histo_counts, 0, sizeof(histo_counts)) ;
        fp = fopen(histo_fname, "w") ;
        if (!fp)
            ErrorExit(ERROR_BADFILE, "%s: could not open histo file %s",
                      Progname, histo_fname) ;

        max_count = 0 ;
        for (xn = 0 ; xn < gca->node_width;  xn++) {
            for (yn = 0 ; yn < gca->node_height ; yn++) {
                for (zn = 0 ; zn < gca->node_depth ; zn++) {
                    gcan = &gca->nodes[xn][yn][zn] ;
                    if (gcan->nlabels < 1)
                        continue ;
                    if (gcan->nlabels == 1 && IS_UNKNOWN(gcan->labels[0]))
                        continue ;
                    histo_counts[gcan->nlabels]++ ;
                    if (gcan->nlabels > max_count)
                        max_count = gcan->nlabels ;
                }
            }
        }
        max_count = 20 ;
        for (xn = 1 ; xn < max_count ;  xn++)
            fprintf(fp, "%d %d\n", xn, histo_counts[xn]) ;
        fclose(fp) ;
    }

    GCAfree(&gca) ;
    msec = TimerStop(&start) ;
    seconds = nint((float)msec/1000.0f) ;
    minutes = seconds / 60 ;
    seconds = seconds % 60 ;
    printf("classifier array training took %d minutes"
           " and %d seconds.\n", minutes, seconds) ;
    exit(0) ;
    return(0) ;
}
Example #17
0
Svg* Svg_FromDef(svgid_t uniqueId, const def_svgline_t* lines, uint lineCount)
{
    uint finalLineCount, finalPointCount;
    const def_svgline_t* slIt;
    const Point2Rawf* spIt;
    dd_bool lineIsLoop;
    SvgLinePoint* dpIt, *prev;
    SvgLine* dlIt;
    uint i, j;
    Svg* svg;

    if(!lines || lineCount == 0) return NULL;

    svg = (Svg*)malloc(sizeof(*svg));
    if(!svg) App_Error("Svg::FromDef: Failed on allocation of %lu bytes for new Svg.", (unsigned long) sizeof(*svg));

    svg->id = uniqueId;
    svg->dlist = 0;

    // Count how many lines and points we actually need.
    finalLineCount = 0;
    finalPointCount = 0;
    slIt = lines;
    for(i = 0; i < lineCount; ++i, slIt++)
    {
        // Skip lines with missing vertices...
        if(slIt->numPoints < 2) continue;

        ++finalLineCount;

        finalPointCount += slIt->numPoints;
        if(slIt->numPoints > 2)
        {
            // If the end point is equal to the start point, we'll ommit it and
            // set this line up as a loop.
            if(FEQUAL(slIt->points[slIt->numPoints-1].x, slIt->points[0].x) &&
               FEQUAL(slIt->points[slIt->numPoints-1].y, slIt->points[0].y))
            {
                finalPointCount -= 1;
            }
        }
    }

    // Allocate the final point set.
    svg->numPoints = finalPointCount;
    svg->points = (SvgLinePoint*)malloc(sizeof(*svg->points) * svg->numPoints);
    if(!svg->points) App_Error("Svg::FromDef: Failed on allocation of %lu bytes for new SvgLinePoint set.", (unsigned long) (sizeof(*svg->points) * finalPointCount));

    // Allocate the final line set.
    svg->lineCount = finalLineCount;
    svg->lines = (SvgLine*)malloc(sizeof(*svg->lines) * finalLineCount);
    if(!svg->lines) App_Error("Svg::FromDef: Failed on allocation of %lu bytes for new SvgLine set.", (unsigned long) (sizeof(*svg->lines) * finalLineCount));

    // Setup the lines.
    slIt = lines;
    dlIt = svg->lines;
    dpIt = svg->points;
    for(i = 0; i < lineCount; ++i, slIt++)
    {
        // Skip lines with missing vertices...
        if(slIt->numPoints < 2) continue;

        // Determine how many points we'll need.
        dlIt->numPoints = slIt->numPoints;
        lineIsLoop = false;
        if(slIt->numPoints > 2)
        {
            // If the end point is equal to the start point, we'll ommit it and
            // set this line up as a loop.
            if(FEQUAL(slIt->points[slIt->numPoints-1].x, slIt->points[0].x) &&
               FEQUAL(slIt->points[slIt->numPoints-1].y, slIt->points[0].y))
            {
                dlIt->numPoints -= 1;
                lineIsLoop = true;
            }
        }

        // Copy points.
        spIt = slIt->points;
        dlIt->head = dpIt;
        prev = NULL;
        for(j = 0; j < dlIt->numPoints; ++j, spIt++)
        {
            SvgLinePoint* next = (j < dlIt->numPoints-1)? dpIt + 1 : NULL;

            dpIt->coords.x = spIt->x;
            dpIt->coords.y = spIt->y;

            // Link in list.
            dpIt->next = next;
            dpIt->prev = prev;

            // On to the next point!
            prev = dpIt;
            dpIt++;
        }

        // Link circularly?
        prev->next = lineIsLoop? dlIt->head : NULL;
        dlIt->head->prev = lineIsLoop? prev : NULL;

        // On to the next line!
        dlIt++;
    }

    return svg;
}
Example #18
0
void SV_WriteSector(Sector *sec, MapStateWriter *msw)
{
    Writer1 *writer = msw->writer();

    int i, type;
    float flooroffx           = P_GetFloatp(sec, DMU_FLOOR_MATERIAL_OFFSET_X);
    float flooroffy           = P_GetFloatp(sec, DMU_FLOOR_MATERIAL_OFFSET_Y);
    float ceiloffx            = P_GetFloatp(sec, DMU_CEILING_MATERIAL_OFFSET_X);
    float ceiloffy            = P_GetFloatp(sec, DMU_CEILING_MATERIAL_OFFSET_Y);
    byte lightlevel           = (byte) (255.f * P_GetFloatp(sec, DMU_LIGHT_LEVEL));
    short floorheight         = (short) P_GetIntp(sec, DMU_FLOOR_HEIGHT);
    short ceilingheight       = (short) P_GetIntp(sec, DMU_CEILING_HEIGHT);
    short floorFlags          = (short) P_GetIntp(sec, DMU_FLOOR_FLAGS);
    short ceilingFlags        = (short) P_GetIntp(sec, DMU_CEILING_FLAGS);
    world_Material *floorMaterial   = (world_Material *)P_GetPtrp(sec, DMU_FLOOR_MATERIAL);
    world_Material *ceilingMaterial = (world_Material *)P_GetPtrp(sec, DMU_CEILING_MATERIAL);

    xsector_t *xsec = P_ToXSector(sec);

#if !__JHEXEN__
    // Determine type.
    if(xsec->xg)
        type = sc_xg1;
    else
#endif
        if(!FEQUAL(flooroffx, 0) || !FEQUAL(flooroffy, 0) || !FEQUAL(ceiloffx, 0) || !FEQUAL(ceiloffy, 0))
        type = sc_ploff;
    else
        type = sc_normal;

    // Type byte.
    Writer_WriteByte(writer, type);

    // Version.
    // 2: Surface colors.
    // 3: Surface flags.
    Writer_WriteByte(writer, 3); // write a version byte.

    Writer_WriteInt16(writer, floorheight);
    Writer_WriteInt16(writer, ceilingheight);
    Writer_WriteInt16(writer, msw->serialIdFor(floorMaterial));
    Writer_WriteInt16(writer, msw->serialIdFor(ceilingMaterial));
    Writer_WriteInt16(writer, floorFlags);
    Writer_WriteInt16(writer, ceilingFlags);
#if __JHEXEN__
    Writer_WriteInt16(writer, (short) lightlevel);
#else
    Writer_WriteByte(writer, lightlevel);
#endif

    float rgb[3];
    P_GetFloatpv(sec, DMU_COLOR, rgb);
    for(i = 0; i < 3; ++i)
        Writer_WriteByte(writer, (byte)(255.f * rgb[i]));

    P_GetFloatpv(sec, DMU_FLOOR_COLOR, rgb);
    for(i = 0; i < 3; ++i)
        Writer_WriteByte(writer, (byte)(255.f * rgb[i]));

    P_GetFloatpv(sec, DMU_CEILING_COLOR, rgb);
    for(i = 0; i < 3; ++i)
        Writer_WriteByte(writer, (byte)(255.f * rgb[i]));

    Writer_WriteInt16(writer, xsec->special);
    Writer_WriteInt16(writer, xsec->tag);

#if __JHEXEN__
    Writer_WriteInt16(writer, xsec->seqType);
#endif

    if(type == sc_ploff
#if !__JHEXEN__
       || type == sc_xg1
#endif
       )
    {
        Writer_WriteFloat(writer, flooroffx);
        Writer_WriteFloat(writer, flooroffy);
        Writer_WriteFloat(writer, ceiloffx);
        Writer_WriteFloat(writer, ceiloffy);
    }

#if !__JHEXEN__
    if(xsec->xg) // Extended General?
    {
        SV_WriteXGSector(sec, writer);
    }
#endif
}