RadialCorrection RadialCorrection::invertCorrection(int h, int w, int step)
{
    LensDistortionModelParameters input = this->mParams;
    LensDistortionModelParameters result;

    /* make initial guess */

    result.setPrincipalX(input.principalX());
    result.setPrincipalY(input.principalY());
    result.setNormalizingFocal(input.normalizingFocal());

    result.setTangentialX(-input.tangentialX());
    result.setTangentialY(-input.tangentialY());

    result.setScale(1.0 / input.scale());

    result.setAspect(1.0 / input.scale()); /*< bad guess I believe */

    result.mKoeff.resize(RadialCorrectionInversionCostFunction::MODEL_POWER);
    for (unsigned i = 0; i < RadialCorrectionInversionCostFunction::MODEL_POWER; i++)
    {
        if (i < input.mKoeff.size()) {
            result.mKoeff[i] = -input.mKoeff[i];
        } else {
            result.mKoeff[i] = 0.0;
        }
    }

    /* Pack the guess and launch optimization */
    RadialCorrection guess(result);
    RadialCorrectionInversionCostFunction cost(*this, guess, step, h, w);

    LevenbergMarquardt lmFit;
    lmFit.maxIterations = 101;
    lmFit.maxLambda = 10e8;
    lmFit.lambdaFactor = 8;
    lmFit.f = &cost;
    lmFit.traceCrucial  = true;
    lmFit.traceProgress = true;
    lmFit.traceMatrix   = true;

    vector<double> initialGuess(cost.inputs);
    RadialCorrectionInversionCostFunction::fillWithRadial(guess, &(initialGuess[0]));
    cout << guess.mParams << endl;

    EllipticalApproximation1d stats;
    stats = cost.aggregatedCost(&(initialGuess[0]));
    SYNC_PRINT(("Start Mean Error: %f px\n", stats.getRadiusAround0()));
    SYNC_PRINT(("Start Max  Error: %f px\n", stats.getMax()));

    vector<double> target(cost.outputs, 0.0);
    vector<double> optimal = lmFit.fit(initialGuess, target);

    guess = RadialCorrectionInversionCostFunction::updateWithModel(guess, &(optimal[0]));

    /* Cost */

    cout << guess.mParams << endl;
    stats = cost.aggregatedCost(&(optimal[0]));
    SYNC_PRINT(("Final Mean Error: %f px\n", stats.getRadiusAround0()));
    SYNC_PRINT(("Final Max  Error: %f px\n", stats.getMax()));


    return guess;
}
Example #2
0
void
xgGtkElement::Activate (GtkWidget *w, gpointer data)
{
    xgGtkElement *self = (xgGtkElement *)data;
    nsresult rv;

    nsCOMPtr<nsIDOMElement> elem;
    rv = self->mWrapper->GetElementNode (getter_AddRefs (elem));
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to get element: %#x"), rv);
	return;
    }

    nsCOMPtr<nsIDOMDocument> doc;
    rv = elem->GetOwnerDocument (getter_AddRefs (doc));
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to get doc: %#x"), rv);
	return;
    }

    nsCOMPtr<nsIDOMDocumentEvent> docEvent (do_QueryInterface (doc, &rv));
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to get doc event: %#x"), rv);
	return;
    }

    nsCOMPtr<nsIDOMEvent> evt;
    rv = docEvent->CreateEvent (NS_LITERAL_STRING ("UIEvent"), getter_AddRefs (evt));
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to create event: %#x"), rv);
	return;
    }

    nsCOMPtr<nsIDOMUIEvent> uiEvt (do_QueryInterface (evt, &rv));
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to QI for ui event: %#x"), rv);
	return;
    }

    rv = uiEvt->InitUIEvent (NS_LITERAL_STRING ("DOMActivate"),
			     PR_TRUE, PR_TRUE, NULL, 0);
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to init UI event: %#x"), rv);
	return;
    }

    nsCOMPtr<nsIDOMEventTarget> target (do_QueryInterface (elem, &rv));
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to QI for an event target: %#x"), rv);
	return;
    }

    PRBool doDefault;
    rv = target->DispatchEvent (evt, &doDefault);
    if (NS_FAILED (rv)) {
	g_warning (GOM_LOC ("Failed to dispatch event: %#x"), rv);
	return;
    }

    g_message (GOM_LOC ("Event dispatch returned %#x"), doDefault);
}
Example #3
0
File: path2.cpp Project: plol/jps
int FindPath( const int nStartX, const int nStartY,
        const int nTargetX, const int nTargetY,
        const unsigned char* pMap, const int nMapWidth, const int nMapHeight,
        int* pOutBuffer, const int nOutBufferSize ) {

    static_assert(sizeof(int)*2 == sizeof(long long), "");


    std::set<Position> open_set, closed_set;

    std::map<Position, Position> came_from;

    std::map<Position, int> g_score;
    std::map<Position, int> f_score;
    //std::unordered_set<Position, position_hash> open_set, closed_set;

    //std::unordered_map<Position, Position, position_hash> came_from;

    //std::unordered_map<Position, int, position_hash> g_score;
    //std::unordered_map<Position, int, position_hash> f_score;


    Position start(nStartX, nStartY);
    Position target(nTargetX, nTargetY);

    open_set.insert(start);
    
    g_score[start] = 0;
    f_score[start] = HeuristicCostEstimate(start, target);


    while (!open_set.empty()) {

        Position current = *open_set.begin();

        for (Position alt : open_set) {
            if (f_score[alt] < f_score[current]) {
                current = alt;
            }
        }

        if (current == target) {
            int i = g_score[current]+0;
            int ret = i;
            if (i >= nOutBufferSize) {
                return -2;
            }

            while (i > 0) {
                i -= 1;
                pOutBuffer[i] = current.getIndex(nMapWidth);
                current = came_from[current];
            }
            return ret;
        }


        open_set.erase(current);

        closed_set.insert(current);

        Position neighbors[4] = {
            current.leftOf(),
            current.rightOf(),
            current.above(),
            current.below()
        };

        for (int i = 0; i < 4; i += 1) {
            Position neighbor = neighbors[i];

            if (!WithinBounds(neighbor, nMapWidth, nMapHeight) || pMap[neighbor.getIndex(nMapWidth)] == 0 ) {
                continue;
            }

            int new_g_score = g_score[current] + 1;
            int new_f_score = new_g_score + HeuristicCostEstimate(neighbor, target);

            if (closed_set.find(neighbor) != closed_set.end() && new_f_score >= f_score[neighbor]) {
                continue;
            }

            if (open_set.find(neighbor) == open_set.end() || new_f_score < f_score[neighbor]) {
                came_from[neighbor] = current;

                g_score[neighbor] = new_g_score;
                f_score[neighbor] = new_f_score;

                if (open_set.find(neighbor) == open_set.end()) {
                    open_set.insert(neighbor);
                }
            }
        }
    }
    return -1;
}
Example #4
0
static unsigned long long int
tsdiff (const struct timespec *before, const struct timespec *after)
{
  struct timespec diff = { .tv_sec = after->tv_sec - before->tv_sec,
			   .tv_nsec = after->tv_nsec - before->tv_nsec };
  while (diff.tv_nsec < 0)
    {
      --diff.tv_sec;
      diff.tv_nsec += 1000000000;
    }
  return diff.tv_sec * 1000000000ULL + diff.tv_nsec;
}

static unsigned long long int
test_nanosleep (clockid_t clock, const char *which,
		const struct timespec *before, int *bad)
{
  const struct timespec sleeptime = { .tv_nsec = 100000000 };
  int e = clock_nanosleep (clock, 0, &sleeptime, NULL);
  if (e == EINVAL || e == ENOTSUP || e == ENOSYS)
    {
      printf ("clock_nanosleep not supported for %s CPU clock: %s\n",
	      which, strerror (e));
      return 0;
    }
  if (e != 0)
    {
      printf ("clock_nanosleep on %s CPU clock: %s\n", which, strerror (e));
      *bad = 1;
      return 0;
    }

  struct timespec after;
  if (clock_gettime (clock, &after) < 0)
    {
      printf ("clock_gettime on %s CPU clock %lx => %s\n",
	      which, (unsigned long int) clock, strerror (errno));
      *bad = 1;
      return 0;
    }

  unsigned long long int diff = tsdiff (before, &after);
  if (diff < sleeptime.tv_nsec || diff > sleeptime.tv_nsec * 2)
    {
      printf ("clock_nanosleep on %s slept %llu (outside reasonable range)\n",
	      which, diff);
      *bad = 1;
      return diff;
    }

  struct timespec sleeptimeabs = sleeptime;
  sleeptimeabs.tv_sec += after.tv_sec;
  sleeptimeabs.tv_nsec += after.tv_nsec;
  while (sleeptimeabs.tv_nsec > 1000000000)
    {
      ++sleeptimeabs.tv_sec;
      sleeptimeabs.tv_nsec -= 1000000000;
    }
  e = clock_nanosleep (clock, TIMER_ABSTIME, &sleeptimeabs, NULL);
  if (e != 0)
    {
      printf ("absolute clock_nanosleep on %s CPU clock: %s\n",
	      which, strerror (e));
      *bad = 1;
      return diff;
    }

  struct timespec afterabs;
  if (clock_gettime (clock, &afterabs) < 0)
    {
      printf ("clock_gettime on %s CPU clock %lx => %s\n",
	      which, (unsigned long int) clock, strerror (errno));
      *bad = 1;
      return diff;
    }

  unsigned long long int sleepdiff = tsdiff (&sleeptimeabs, &afterabs);
  if (sleepdiff > sleeptime.tv_nsec)
    {
      printf ("\
absolute clock_nanosleep on %s %llu past target (outside reasonable range)\n",
	      which, sleepdiff);
      *bad = 1;
    }

  unsigned long long int diffabs = tsdiff (&after, &afterabs);
  if (diffabs < sleeptime.tv_nsec || diffabs > sleeptime.tv_nsec * 2)
    {
      printf ("\
absolute clock_nanosleep on %s slept %llu (outside reasonable range)\n",
	      which, diffabs);
      *bad = 1;
    }

  return diff + diffabs;
}



static int
do_test (void)
{
  int result = 0;
  clockid_t process_clock, th_clock, my_thread_clock;
  int e;
  pthread_t th;

  e = clock_getcpuclockid (0, &process_clock);
  if (e != 0)
    {
      printf ("clock_getcpuclockid on self => %s\n", strerror (e));
      return 1;
    }

  e = pthread_getcpuclockid (pthread_self (), &my_thread_clock);
  if (e != 0)
    {
      printf ("pthread_getcpuclockid on self => %s\n", strerror (e));
      return 1;
    }

  /* This is a kludge.  This test fails if the semantics of thread and
     process clocks are wrong.  The old code using hp-timing without kernel
     support has bogus semantics if there are context switches.  We don't
     fail to report failure when the proper functionality is not available
     in the kernel.  It so happens that Linux kernels without correct CPU
     clock support also lack CPU timer support, so we use use that to guess
     that we are using the bogus code and not test it.  */
  timer_t t;
  if (timer_create (my_thread_clock, NULL, &t) != 0)
    {
      printf ("timer_create: %m\n");
      puts ("No support for CPU clocks with good semantics, skipping test");
      return 0;
    }
  timer_delete (t);


  pthread_barrier_init (&barrier, NULL, 2);

  e = pthread_create (&th, NULL, chew_cpu, NULL);
  if (e != 0)
    {
      printf ("pthread_create: %s\n", strerror (e));
      return 1;
    }

  e = pthread_getcpuclockid (th, &th_clock);
  if (e == ENOENT || e == ENOSYS || e == ENOTSUP)
    {
      puts ("pthread_getcpuclockid does not support other threads");
      return 1;
    }

  pthread_barrier_wait (&barrier);

  struct timespec res;
  if (clock_getres (th_clock, &res) < 0)
    {
      printf ("clock_getres on thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      result = 1;
      return 1;
    }
  printf ("live thread clock %lx resolution %lu.%.9lu\n",
	  (unsigned long int) th_clock, res.tv_sec, res.tv_nsec);

  struct timespec process_before, process_after;
  if (clock_gettime (process_clock, &process_before) < 0)
    {
      printf ("clock_gettime on process clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }

  struct timespec before, after;
  if (clock_gettime (th_clock, &before) < 0)
    {
      printf ("clock_gettime on live thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }
  printf ("live thread before sleep => %lu.%.9lu\n",
	  before.tv_sec, before.tv_nsec);

  struct timespec me_before, me_after;
  if (clock_gettime (my_thread_clock, &me_before) < 0)
    {
      printf ("clock_gettime on live thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }
  printf ("self thread before sleep => %lu.%.9lu\n",
	  me_before.tv_sec, me_before.tv_nsec);

  struct timespec sleeptime = { .tv_nsec = 500000000 };
  nanosleep (&sleeptime, NULL);

  if (clock_gettime (th_clock, &after) < 0)
    {
      printf ("clock_gettime on live thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }
  printf ("live thread after sleep => %lu.%.9lu\n",
	  after.tv_sec, after.tv_nsec);

  if (clock_gettime (process_clock, &process_after) < 0)
    {
      printf ("clock_gettime on process clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }

  if (clock_gettime (my_thread_clock, &me_after) < 0)
    {
      printf ("clock_gettime on live thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }
  printf ("self thread after sleep => %lu.%.9lu\n",
	  me_after.tv_sec, me_after.tv_nsec);

  unsigned long long int th_diff = tsdiff (&before, &after);
  unsigned long long int pdiff = tsdiff (&process_before, &process_after);
  unsigned long long int my_diff = tsdiff (&me_before, &me_after);

  if (th_diff < 100000000 || th_diff > 600000000)
    {
      printf ("thread before - after %llu outside reasonable range\n",
	      th_diff);
      result = 1;
    }

  if (my_diff > 100000000)
    {
      printf ("self thread before - after %llu outside reasonable range\n",
	      my_diff);
      result = 1;
    }

  if (pdiff < th_diff)
    {
      printf ("process before - after %llu outside reasonable range (%llu)\n",
	      pdiff, th_diff);
      result = 1;
    }

  process_after.tv_nsec += test_nanosleep (th_clock, "thread",
					   &after, &result);
  process_after.tv_nsec += test_nanosleep (process_clock, "process",
					   &process_after, &result);
  test_nanosleep (CLOCK_PROCESS_CPUTIME_ID,
		  "PROCESS_CPUTIME_ID", &process_after, &result);

  pthread_cancel (th);

  e = clock_nanosleep (CLOCK_THREAD_CPUTIME_ID, 0, &sleeptime, NULL);
  if (e != EINVAL)
    {
      printf ("clock_nanosleep CLOCK_THREAD_CPUTIME_ID: %s\n",
	      strerror (e));
      result = 1;
    }

  return result;
}
Example #5
0
// static
gboolean
xgGtkElement::Event (GtkWidget *widget, GdkEvent *event, gpointer userData)
{
    static GdkEventType  last_type  = GDK_NOTHING;
    static GdkEvent     *last_event = NULL;

    if (event == last_event && event->type == last_type) {
        return FALSE;
    }

    switch (event->type) {
    case GDK_MOTION_NOTIFY:
    case GDK_BUTTON_PRESS:
    case GDK_BUTTON_RELEASE:
    case GDK_ENTER_NOTIFY:
    case GDK_LEAVE_NOTIFY:
    case GDK_KEY_PRESS:
    case GDK_KEY_RELEASE:
	break;
    default:
	return FALSE;
    }

    xgGtkElement *self = reinterpret_cast<xgGtkElement *> (userData);
    NS_ENSURE_TRUE (self, FALSE);

    nsresult rv;
    nsCOMPtr<nsIDOMElement> elem;
    rv = self->mWrapper->GetElementNode (getter_AddRefs (elem));
    NS_ENSURE_SUCCESS (rv, FALSE);

    nsCOMPtr<nsIDOMDocument> doc;
    rv = elem->GetOwnerDocument (getter_AddRefs (doc));
    NS_ENSURE_SUCCESS (rv, FALSE);

    nsCOMPtr<nsIDOMDocumentEvent> docEvent (do_QueryInterface (doc, &rv));
    NS_ENSURE_SUCCESS (rv, FALSE);

    nsCOMPtr<nsIDOMEvent> evt;

    switch (event->type) {
    case GDK_MOTION_NOTIFY:
	self->mClickState = 0;
        INIT_MOUSE_EVENT ("mousemove", motion);
        break;
    case GDK_BUTTON_PRESS:
        ++self->mClickState;
        INIT_MOUSE_EVENT ("mousedown", button);
        break;
    case GDK_BUTTON_RELEASE:
        INIT_MOUSE_EVENT ("mouseup", button);
        break;
    case GDK_ENTER_NOTIFY:
        INIT_MOUSE_EVENT ("mouseover", crossing);
        break;
    case GDK_LEAVE_NOTIFY:
        INIT_MOUSE_EVENT ("mouseout", crossing);
        break;
    case GDK_KEY_PRESS:
        if (GTK_IS_WINDOW (widget) && GTK_WINDOW (widget)->focus_widget) {
            widget = GTK_WINDOW (widget)->focus_widget;
	    self = reinterpret_cast<xgGtkElement *> (g_object_get_data (G_OBJECT (widget), "XG_GOBJECT"));
	    NS_ENSURE_TRUE (self, FALSE);

	    rv = self->mWrapper->GetElementNode (getter_AddRefs (elem));
	    NS_ENSURE_SUCCESS (rv, FALSE);
        }
        INIT_KEY_EVENT ("keydown");
        break;
    case GDK_KEY_RELEASE:
        if (GTK_IS_WINDOW (widget) && GTK_WINDOW (widget)->focus_widget) {
            widget = GTK_WINDOW (widget)->focus_widget;
	    self = reinterpret_cast<xgGtkElement *> (g_object_get_data (G_OBJECT (widget), "XG_GOBJECT"));
	    NS_ENSURE_TRUE (self, FALSE);
		
	    rv = self->mWrapper->GetElementNode (getter_AddRefs (elem));
	    NS_ENSURE_SUCCESS (rv, FALSE);
        }
        INIT_KEY_EVENT ("keyup");
        break;
    default:
	g_assert_not_reached ();
    }

    g_assert (evt);

    last_type  = event->type;
    last_event = event;

    nsCOMPtr<nsIDOMEventTarget> target (do_QueryInterface (elem, &rv));
    NS_ENSURE_SUCCESS (rv, FALSE);

    PRBool doDefault;
    rv = target->DispatchEvent (evt, &doDefault);
    NS_ENSURE_SUCCESS (rv, FALSE);

    if (!doDefault) {
	return TRUE;
    }

    if (event->type == GDK_BUTTON_RELEASE && self->mClickState) {
        evt = NULL;
        INIT_MOUSE_EVENT ("click", button);
	rv = target->DispatchEvent (evt, &doDefault);
	NS_ENSURE_SUCCESS (rv, FALSE);
	if (!doDefault) {
	    return TRUE;
	}
    }
    return FALSE;
}
Example #6
0
void KisImageLayerRemoveCommand::redo()
{
    UpdateTarget target(m_image, m_node, m_image->bounds());
    KisImageCommand::redo();
    target.update();
}
nsresult
nsRDFPropertyTestNode::FilterInstantiations(InstantiationSet& aInstantiations,
                                            bool* aCantHandleYet) const
{
    nsresult rv;

    if (aCantHandleYet)
        *aCantHandleYet = PR_FALSE;

    nsIRDFDataSource* ds = mProcessor->GetDataSource();

    InstantiationSet::Iterator last = aInstantiations.Last();
    for (InstantiationSet::Iterator inst = aInstantiations.First(); inst != last; ++inst) {
        bool hasSourceBinding;
        nsCOMPtr<nsIRDFResource> sourceRes;

        if (mSource) {
            hasSourceBinding = PR_TRUE;
            sourceRes = mSource;
        }
        else {
            nsCOMPtr<nsIRDFNode> sourceValue;
            hasSourceBinding = inst->mAssignments.GetAssignmentFor(mSourceVariable,
                                                                   getter_AddRefs(sourceValue));
            sourceRes = do_QueryInterface(sourceValue);
        }

        bool hasTargetBinding;
        nsCOMPtr<nsIRDFNode> targetValue;

        if (mTarget) {
            hasTargetBinding = PR_TRUE;
            targetValue = mTarget;
        }
        else {
            hasTargetBinding = inst->mAssignments.GetAssignmentFor(mTargetVariable,
                                                                   getter_AddRefs(targetValue));
        }

#ifdef PR_LOGGING
        if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) {
            const char* source = "(unbound)";
            if (hasSourceBinding)
                sourceRes->GetValueConst(&source);

            nsAutoString target(NS_LITERAL_STRING("(unbound)"));
            if (hasTargetBinding)
                nsXULContentUtils::GetTextForNode(targetValue, target);

            PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
                   ("nsRDFPropertyTestNode[%p]: FilterInstantiations() source=[%s] target=[%s]",
                    this, source, NS_ConvertUTF16toUTF8(target).get()));
        }
#endif

        if (hasSourceBinding && hasTargetBinding) {
            // it's a consistency check. see if we have a assignment that is consistent
            bool hasAssertion;
            rv = ds->HasAssertion(sourceRes, mProperty, targetValue,
                                  PR_TRUE, &hasAssertion);
            if (NS_FAILED(rv)) return rv;

#ifdef PR_LOGGING
            PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
                   ("    consistency check => %s", hasAssertion ? "passed" : "failed"));
#endif

            if (hasAssertion) {
                // it's consistent.
                Element* element =
                    nsRDFPropertyTestNode::Element::Create(sourceRes,
                                                           mProperty,
                                                           targetValue);

                if (! element)
                    return NS_ERROR_OUT_OF_MEMORY;

                inst->AddSupportingElement(element);
            }
            else {
                // it's inconsistent. remove it.
                aInstantiations.Erase(inst--);
            }
        }
        else if ((hasSourceBinding && ! hasTargetBinding) ||
                 (! hasSourceBinding && hasTargetBinding)) {
            // it's an open ended query on the source or
            // target. figure out what matches and add as a
            // cross-product.
            nsCOMPtr<nsISimpleEnumerator> results;
            if (hasSourceBinding) {
                rv = ds->GetTargets(sourceRes,
                                    mProperty,
                                    PR_TRUE,
                                    getter_AddRefs(results));
            }
            else {
                rv = ds->GetSources(mProperty,
                                    targetValue,
                                    PR_TRUE,
                                    getter_AddRefs(results));
                if (NS_FAILED(rv)) return rv;
            }

            while (1) {
                bool hasMore;
                rv = results->HasMoreElements(&hasMore);
                if (NS_FAILED(rv)) return rv;

                if (! hasMore)
                    break;

                nsCOMPtr<nsISupports> isupports;
                rv = results->GetNext(getter_AddRefs(isupports));
                if (NS_FAILED(rv)) return rv;

                nsIAtom* variable;
                nsCOMPtr<nsIRDFNode> value;

                if (hasSourceBinding) {
                    variable = mTargetVariable;

                    value = do_QueryInterface(isupports);
                    NS_ASSERTION(value != nsnull, "target is not an nsIRDFNode");

#ifdef PR_LOGGING
                    if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) {
                        nsAutoString s(NS_LITERAL_STRING("(none found)"));
                        if (value)
                            nsXULContentUtils::GetTextForNode(value, s);

                        PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
                               ("    target => %s", NS_ConvertUTF16toUTF8(s).get()));
                    }
#endif

                    if (! value) continue;

                    targetValue = value;
                }
                else {
                    variable = mSourceVariable;

                    nsCOMPtr<nsIRDFResource> source = do_QueryInterface(isupports);
                    NS_ASSERTION(source != nsnull, "source is not an nsIRDFResource");

#ifdef PR_LOGGING
                    if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) {
                        const char* s = "(none found)";
                        if (source)
                            source->GetValueConst(&s);

                        PR_LOG(gXULTemplateLog, PR_LOG_DEBUG,
                               ("    source => %s", s));
                    }
#endif

                    if (! source) continue;

                    value = sourceRes = source;
                }

                // Copy the original instantiation, and add it to the
                // instantiation set with the new assignment that we've
                // introduced. Ownership will be transferred to the
                Instantiation newinst = *inst;
                newinst.AddAssignment(variable, value);

                Element* element =
                    nsRDFPropertyTestNode::Element::Create(sourceRes,
                                                           mProperty,
                                                           targetValue);

                if (! element)
                    return NS_ERROR_OUT_OF_MEMORY;

                newinst.AddSupportingElement(element);

                aInstantiations.Insert(inst, newinst);
            }

            // finally, remove the "under specified" instantiation.
            aInstantiations.Erase(inst--);
        }
        else {
            if (!aCantHandleYet) {
                nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_TRIPLE_UNBOUND);
                // Neither source nor target assignment!
                return NS_ERROR_UNEXPECTED;
            }

            *aCantHandleYet = PR_TRUE;
            return NS_OK;
        }
    }

    return NS_OK;
}
Example #8
0
//
// Framework functions
//
bool Setup()
{
	//
	// Create the teapot.
	//

	D3DXCreateTeapot(Device, &Teapot, 0);

	//
	// Compute the bounding sphere.
	//

	BYTE* v = 0;
	Teapot->LockVertexBuffer(0, (void**)&v);

	D3DXComputeBoundingSphere(
		(D3DXVECTOR3*)v,
		Teapot->GetNumVertices(),
		D3DXGetFVFVertexSize(Teapot->GetFVF()),
		&BSphere._center,
		&BSphere._radius);

	Teapot->UnlockVertexBuffer();

	//
	// Build a sphere mesh that describes the teapot's bounding sphere.
	//

	D3DXCreateSphere(Device, BSphere._radius, 20, 20, &Sphere, 0);

	//
	// Set light.
	//

	D3DXVECTOR3 dir(0.707f, -0.0f, 0.707f);
	D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f);
	D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &col);

	Device->SetLight(0, &light);
	Device->LightEnable(0, true);
	Device->SetRenderState(D3DRS_NORMALIZENORMALS, true);
	Device->SetRenderState(D3DRS_SPECULARENABLE, false);	

	//
	// Set view matrix.
	//

	D3DXVECTOR3 pos(0.0f, 0.0f, -10.0f);
	D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
	D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);

	D3DXMATRIX V;
	D3DXMatrixLookAtLH(&V, &pos, &target, &up);
	Device->SetTransform(D3DTS_VIEW, &V);

	//
	// Set projection matrix.
	//

	D3DXMATRIX proj;
	D3DXMatrixPerspectiveFovLH(
			&proj,
			D3DX_PI * 0.25f, // 45 - degree
			(float)Width / (float)Height,
			1.0f,
			1000.0f);
	Device->SetTransform(D3DTS_PROJECTION, &proj);

	return true;
}
Example #9
0
 void operator()(Edge e, const Graph& g) {
   put(m_predecessor, target(e, g), e);
 }
Example #10
0
   static T getrandom(const T range=0)
   {
		T target(random());
		return range ? target / (RAND_MAX / range + 1) : target;
	}
Example #11
0
void device_scheduler::timeslice()
{
	bool call_debugger = ((machine().debug_flags & DEBUG_FLAG_ENABLED) != 0);

	// build the execution list if we don't have one yet
	if (UNEXPECTED(m_execute_list == NULL))
		rebuild_execute_list();

	// if the current quantum has expired, find a new one
	while (m_basetime >= m_quantum_list.first()->m_expire)
		m_quantum_allocator.reclaim(m_quantum_list.detach_head());

	// loop until we hit the next timer
	while (m_basetime < m_timer_list->m_expire)
	{
		// by default, assume our target is the end of the next quantum
		attotime target(m_basetime + attotime(0, m_quantum_list.first()->m_actual));

		// however, if the next timer is going to fire before then, override
		if (m_timer_list->m_expire < target)
			target = m_timer_list->m_expire;

		LOG(("------------------\n"));
		LOG(("cpu_timeslice: target = %s\n", target.as_string(PRECISION)));

		// do we have pending suspension changes?
		if (m_suspend_changes_pending)
			apply_suspend_changes();

		// loop over all CPUs
		for (device_execute_interface *exec = m_execute_list; exec != NULL; exec = exec->m_nextexec)
		{
			// only process if this CPU is executing or truly halted (not yielding)
			// and if our target is later than the CPU's current time (coarse check)
			if (EXPECTED((exec->m_suspend == 0 || exec->m_eatcycles) && target.seconds() >= exec->m_localtime.seconds()))
			{
				// compute how many attoseconds to execute this CPU
				attoseconds_t delta = target.attoseconds() - exec->m_localtime.attoseconds();
				if (delta < 0 && target.seconds() > exec->m_localtime.seconds())
					delta += ATTOSECONDS_PER_SECOND;
				assert(delta == (target - exec->m_localtime).as_attoseconds());

				// if we have enough for at least 1 cycle, do the math
				if (delta >= exec->m_attoseconds_per_cycle)
				{
					// compute how many cycles we want to execute
					int ran = exec->m_cycles_running = divu_64x32((UINT64)delta >> exec->m_divshift, exec->m_divisor);
					LOG(("  cpu '%s': %" I64FMT"d (%d cycles)\n", exec->device().tag(), delta, exec->m_cycles_running));

					// if we're not suspended, actually execute
					if (exec->m_suspend == 0)
					{
						g_profiler.start(exec->m_profiler);

						// note that this global variable cycles_stolen can be modified
						// via the call to cpu_execute
						exec->m_cycles_stolen = 0;
						m_executing_device = exec;
						*exec->m_icountptr = exec->m_cycles_running;
						if (!call_debugger)
							exec->run();
						else
						{
							debugger_start_cpu_hook(&exec->device(), target);
							exec->run();
							debugger_stop_cpu_hook(&exec->device());
						}

						// adjust for any cycles we took back
						assert(ran >= *exec->m_icountptr);
						ran -= *exec->m_icountptr;
						assert(ran >= exec->m_cycles_stolen);
						ran -= exec->m_cycles_stolen;
						g_profiler.stop();
					}

					// account for these cycles
					exec->m_totalcycles += ran;

					// update the local time for this CPU
					attotime delta(0, exec->m_attoseconds_per_cycle * ran);
					assert(delta >= attotime::zero);
					exec->m_localtime += delta;
					LOG(("         %d ran, %d total, time = %s\n", ran, (INT32)exec->m_totalcycles, exec->m_localtime.as_string(PRECISION)));

					// if the new local CPU time is less than our target, move the target up, but not before the base
					if (exec->m_localtime < target)
					{
						target = max(exec->m_localtime, m_basetime);
						LOG(("         (new target)\n"));
					}
				}
			}
		}
Example #12
0
 pointer operator->() { return &target(*ei, *g); };
Example #13
0
 value_type operator*() { return target(*ei, *g); };
Example #14
0
 value_type operator[](difference_type i) const { return target(*(ei + i), *g); };
Example #15
0
 void HandleDummy(SpellEffIndex /*effIndex*/)
 {
     if (Creature* target = GetHitCreature())
         target()->CastSpell(GetCaster(), SPELL_BUNNY_CREDIT_BEAM, false);
 }
Example #16
0
 void operator()(Edge e, const Graph& g) {
   typename graph_traits<Graph>::vertex_descriptor 
     u = source(e, g), v = target(e, g);
   put(m_distance, v, get(m_distance, u) + 1);
 }
	void	as_s_function::operator()(const fn_call& fn)
	// Dispatch.
	{

		assert(fn.env);

		// Keep target alive during execution!
		gc_ptr<as_object> target(m_target.get_ptr());

		// try to use caller environment
		// if the caller object has own environment then we use its environment
		as_environment* env = fn.env;
		if (fn.this_ptr)
		{
			if (fn.this_ptr->get_environment())
			{
				env = fn.this_ptr->get_environment();
			}
		}

		// set 'this'
		as_object* this_ptr = env->get_target();
		if (fn.this_ptr)
		{
			this_ptr = fn.this_ptr;
			if (this_ptr->m_this_ptr != NULL)
			{
				this_ptr = this_ptr->m_this_ptr.get_ptr();
			}
		}

		// Function has been declared in moviclip ==> we should use its environment
		// At the same time 'this_ptr' may refers to another object
		// see testcase in .h file
		if (m_target != NULL)
		{
			character* ch = cast_to<character>(m_target.get_ptr());
			if (ch)
			{
				if (ch->is_alive())
				{
					env = m_target->get_environment();
				}
			}
		}

		// Set up local stack frame, for parameters and locals.
		int	local_stack_top = env->get_local_frame_top();
		env->add_frame_barrier();

		if (m_is_function2 == false)
		{
			// Conventional function.

			// Push the arguments onto the local frame.
			int	args_to_pass = imin(fn.nargs, m_args.size());
			for (int i = 0; i < args_to_pass; i++)
			{
				assert(m_args[i].m_register == 0);
				env->add_local(m_args[i].m_name, fn.arg(i));
			}

			env->set_local("this", this_ptr);

			// Put 'super' in a local var.
			if (fn.this_ptr)
			{
				env->add_local("super", fn.this_ptr->get_proto());
			}
		}
		else
		{
			// function2: most args go in registers; any others get pushed.
			
			// Create local registers.
			env->add_local_registers(m_local_register_count);

			// Handle the explicit args.
			int	args_to_pass = imin(fn.nargs, m_args.size());
			for (int i = 0; i < args_to_pass; i++)
			{
				if (m_args[i].m_register == 0)
				{
					// Conventional arg passing: create a local var.
					env->add_local(m_args[i].m_name, fn.arg(i));
				}
				else
				{
					// Pass argument into a register.
					int	reg = m_args[i].m_register;
					env->set_register(reg, fn.arg(i));
				}
			}

			// Handle the implicit args.
			int	current_reg = 1;

			if (m_function2_flags & 0x01)
			{
				// preload 'this' into a register.
				IF_VERBOSE_ACTION(log_msg("-------------- preload this=%p to register %d\n",
					this_ptr, current_reg));
				env->set_register(current_reg, this_ptr);
				current_reg++;

			}

			if (m_function2_flags & 0x02)
			{
				// Don't put 'this' into a local var.
			}
			else
			{
				// Put 'this' in a local var.
				env->add_local("this", as_value(this_ptr));
			}

			// Init arguments array, if it's going to be needed.
			gc_ptr<as_array>	arg_array;
			if ((m_function2_flags & 0x04) || ! (m_function2_flags & 0x08))
			{
				arg_array = new as_array(env->get_player());

				as_value	index_number;
				for (int i = 0; i < fn.nargs; i++)
				{
					index_number.set_int(i);
					arg_array->set_member(index_number.to_string(), fn.arg(i));
				}
			}

			if (m_function2_flags & 0x04)
			{
				// preload 'arguments' into a register.
				env->set_register(current_reg, arg_array.get_ptr());
				current_reg++;
			}

			if (m_function2_flags & 0x08)
			{
				// Don't put 'arguments' in a local var.
			}
			else
			{
				// Put 'arguments' in a local var.
 				env->add_local("arguments", as_value(arg_array.get_ptr()));
			}

			if (m_function2_flags & 0x10)
			{
				// Put 'super' in a register.
				IF_VERBOSE_ACTION(log_msg("-------------- preload super=%p to register %d\n",
					fn.this_ptr->get_proto(), current_reg));
				env->set_register(current_reg, fn.this_ptr->get_proto());
				current_reg++;
			}

			if (m_function2_flags & 0x20)
			{
				// Don't put 'super' in a local var.
			}
			else
			{
				// Put 'super' in a local var.
				env->add_local("super", fn.this_ptr->get_proto());
			}

			if (m_function2_flags & 0x40)
			{
				// Put '_root' in a register.
				env->set_register(current_reg, env->get_root()->get_root_movie());
				current_reg++;
			}

			if (m_function2_flags & 0x80)
			{
				// Put '_parent' in a register.
				array<with_stack_entry>	dummy;
				as_value	parent = env->get_variable("_parent", dummy);
				IF_VERBOSE_ACTION(log_msg("-------------- preload _parent=%p to register %d\n", parent.to_object(), current_reg));
				env->set_register(current_reg, parent);
				current_reg++;
			}

			if (m_function2_flags & 0x100)
			{
				// Put '_global' in a register.
				IF_VERBOSE_ACTION(log_msg("-------------- preload _global=%p to register %d\n", 
					get_global(), current_reg));
				env->set_register(current_reg, get_global());
				current_reg++;
			}
		}

		// keep stack size
		int stack_size = env->get_stack_size();

		// Execute the actions.
		m_action_buffer.execute(env, m_start_pc, m_length, fn.result, m_with_stack, m_is_function2);

		// restore stack size
		// it should not be but it happens
		if (stack_size != env->get_stack_size())
		{
//			log_error("s_function: on entry stack size (%d) != on exit stack size (%d)\n", 
//				stack_size, env->m_stack.size());
			env->set_stack_size(stack_size);
		}

		// Clean up stack frame.
		env->set_local_frame_top(local_stack_top);

		if (m_is_function2)
		{
			// Clean up the local registers.
			env->drop_local_registers(m_local_register_count);
		}
				
	}
	void BugSwat::update(float elapsedTime)
	{
		for (auto p : players)
		{
			p->position += (12.0f * p->joystick.leftStick + 15.0f * p->joystick.rightStick) * elapsedTime*60.0f;

			p->position.x = glm::min((float)1920, glm::max(0.0f, p->position.x));
			p->position.y = glm::min((float)1080, glm::max(0.0f, p->position.y));

			if ((p->joystick.a == 1 || p->joystick.r == 1) && !p->swatting)
			{
				p->swatTime = blib::util::Profiler::getAppTime();
				p->swatting = true;
			}
			else if (p->joystick.a == 0 && p->joystick.r == 0)
				p->swatting = false;
		}

		for (auto e : enemies)
		{
			e->update(elapsedTime * 60);
			if (e->alive)
			{
				auto hittingPlayers = blib::linq::where(players, [e](BugSwatPlayer* p) { return glm::length(p->position - e->position) < 55 && p->swatting && (int)floor((blib::util::Profiler::getAppTime() - p->swatTime) * 50) == 3; });
				if (hittingPlayers.size() > 0)
				{
					e->alive = !e->alive;
					blib::linq::foreach(hittingPlayers, [](BugSwatPlayer* p) { p->score++; });
					splats.push_back(new Splat(e->position, (float)(blib::math::randomDouble()*M_PI * 2)));
					//particleEmitters.Add(new FlyBloodEmitter(e.position, elapsedTime));
				}
			}
		}
		enemies = blib::linq::where(enemies, [this](Enemy* e) { return e->onScreen(settings); });

		// Spawn new enemy
		if (blib::math::randomDouble() < 0.03 * elapsedTime * 60)
		{
			Enemy* enemy = NULL;

			int enemyType = rand() % 3;

			if (enemyType == 0)
				enemy = new Enemy();
			if (enemyType == 1)
				enemy = new SwirlEnemy();
			if (enemyType == 2)
				enemy = new DodgeEnemy(this);

			int side = rand() % 4;
			float d = (float)blib::math::randomDouble();
			glm::vec2 target(rand() % 1920, rand() % 1080);

			glm::vec2 positions[] = {
				glm::vec2(d * 1920, 0),
				glm::vec2(d * 1920, 1080),
				glm::vec2(0, d * 1080),
				glm::vec2(1920, d * 1080),
			};

			enemy->position = positions[side];
			enemy->rotation = atan2(target.y - enemy->position.y, target.x - enemy->position.x);
			enemy->speed = 7 + (float)blib::math::randomDouble() * 3;
			enemies.push_back(enemy);
		}
	}
/* { dg-final { scan-assembler "fn:fn_default_start hf0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start vx0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ht0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ps0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start se1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start zv0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start mv1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start wd0" } } */

/**
 **
 ** Attribute
 **
 **/

__attribute__ ((target ("no-mvcle")))
void fn_att_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_att_0 mv0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ar4" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 tu7" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 se1" } } */
Example #20
0
/* { dg-final { scan-assembler "fn:fn_default_start hf0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start vx0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ht0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ps0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start se1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start zv0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start mv1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start wd0" } } */

/**
 **
 ** Attribute
 **
 **/

__attribute__ ((target ("no-backchain")))
void fn_att_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_att_0 ba0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 se1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 zv0" } } */
Example #21
0
        typename property_traits<CoreMap>::value_type
        core_numbers_impl(Graph& g, CoreMap c, PositionMap pos, Visitor vis)
        {
            typedef typename graph_traits<Graph>::vertices_size_type size_type;
            typedef typename graph_traits<Graph>::degree_size_type degree_type;
            typedef typename graph_traits<Graph>::vertex_descriptor vertex;
            typename graph_traits<Graph>::vertex_iterator vi,vi_end;

            // store the vertex core numbers
            typename property_traits<CoreMap>::value_type v_cn = 0;

            // compute the maximum degree (degrees are in the coremap)
            typename graph_traits<Graph>::degree_size_type max_deg = 0;
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                max_deg = (std::max<typename graph_traits<Graph>::degree_size_type>)(max_deg, get(c,*vi));
            }

            // store the vertices in bins by their degree
            // allocate two extra locations to ease boundary cases
            std::vector<size_type> bin(max_deg+2);
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                ++bin[get(c,*vi)];
            }

            // this loop sets bin[d] to the starting position of vertices
            // with degree d in the vert array for the bucket sort
            size_type cur_pos = 0;
            for (degree_type cur_deg = 0; cur_deg < max_deg+2; ++cur_deg) {
                degree_type tmp = bin[cur_deg];
                bin[cur_deg] = cur_pos;
                cur_pos += tmp;
            }

            // perform the bucket sort with pos and vert so that
            // pos[0] is the vertex of smallest degree
            std::vector<vertex> vert(num_vertices(g));
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                vertex v=*vi;
                size_type p=bin[get(c,v)];
                put(pos,v,p);
                vert[p]=v;
                ++bin[get(c,v)];
            }
            // we ``abused'' bin while placing the vertices, now,
            // we need to restore it
            std::copy(boost::make_reverse_iterator(bin.end()-2),
                boost::make_reverse_iterator(bin.begin()),
                boost::make_reverse_iterator(bin.end()-1));
            // now simulate removing the vertices
            for (size_type i=0; i < num_vertices(g); ++i) {
                vertex v = vert[i];
                vis.examine_vertex(v,g);
                v_cn = get(c,v);
                typename graph_traits<Graph>::out_edge_iterator oi,oi_end;
                for (boost::tie(oi,oi_end) = out_edges(v,g); oi!=oi_end; ++oi) {
                    vis.examine_edge(*oi,g);
                    vertex u = target(*oi,g);
                    // if c[u] > c[v], then u is still in the graph,
                    if (get(c,u) > v_cn) {
                        degree_type deg_u = get(c,u);
                        degree_type pos_u = get(pos,u);
                        // w is the first vertex with the same degree as u
                        // (this is the resort operation!)
                        degree_type pos_w = bin[deg_u];
                        vertex w = vert[pos_w];
                        if (u!=v) {
                            // swap u and w
                            put(pos,u,pos_w);
                            put(pos,w,pos_u);
                            vert[pos_w] = u;
                            vert[pos_u] = w;
                        }
                        // now, the vertices array is sorted assuming
                        // we perform the following step
                        // start the set of vertices with degree of u
                        // one into the future (this now points at vertex
                        // w which we swapped with u).
                        ++bin[deg_u];
                        // we are removing v from the graph, so u's degree
                        // decreases
                        put(c,u,get(c,u)-1);
                    }
                }
                vis.finish_vertex(v,g);
            }
            return v_cn;
        }
bool disjunctive_polynomial_accelerationt::accelerate(
    path_acceleratort &accelerator) {
  std::map<exprt, polynomialt> polynomials;
  scratch_programt program(symbol_table);

  accelerator.clear();

#ifdef DEBUG
  std::cout << "Polynomial accelerating program:" << std::endl;

  for (goto_programt::instructionst::iterator it = goto_program.instructions.begin();
       it != goto_program.instructions.end();
       ++it) {
    if (loop.find(it) != loop.end()) {
      goto_program.output_instruction(ns, "scratch", std::cout, it);
    }
  }

  std::cout << "Modified:" << std::endl;

  for (expr_sett::iterator it = modified.begin();
       it != modified.end();
       ++it) {
    std::cout << expr2c(*it, ns) << std::endl;
  }
#endif

  if (loop_counter.is_nil()) {
    symbolt loop_sym = utils.fresh_symbol("polynomial::loop_counter",
        unsignedbv_typet(POLY_WIDTH));
    loop_counter = loop_sym.symbol_expr();
  }

  patht &path = accelerator.path;
  path.clear();

  if (!find_path(path)) {
    // No more paths!
    return false;
  }

#if 0
  for (expr_sett::iterator it = modified.begin();
       it != modified.end();
       ++it) {
    polynomialt poly;
    exprt target = *it;

    if (it->type().id() == ID_bool) {
      // Hack: don't try to accelerate booleans.
      continue;
    }

    if (target.id() == ID_index ||
        target.id() == ID_dereference) {
      // We'll handle this later.
      continue;
    }

    if (fit_polynomial(target, poly, path)) {
      std::map<exprt, polynomialt> this_poly;
      this_poly[target] = poly;

      if (utils.check_inductive(this_poly, path)) {
#ifdef DEBUG
        std::cout << "Fitted a polynomial for " << expr2c(target, ns) <<
          std::endl;
#endif
        polynomials[target] = poly;
        accelerator.changed_vars.insert(target);
        break;
      }
    }
  }

  if (polynomials.empty()) {
    return false;
  }
#endif

  // Fit polynomials for the other variables.
  expr_sett dirty;
  utils.find_modified(accelerator.path, dirty);
  polynomial_acceleratort path_acceleration(symbol_table, goto_functions,
      loop_counter);
  goto_programt::instructionst assigns;

  for (patht::iterator it = accelerator.path.begin();
       it != accelerator.path.end();
       ++it) {
    if (it->loc->is_assign() || it->loc->is_decl()) {
      assigns.push_back(*(it->loc));
    }
  }

  for (expr_sett::iterator it = dirty.begin();
       it != dirty.end();
       ++it) {
#ifdef DEBUG
    std::cout << "Trying to accelerate " << expr2c(*it, ns) << std::endl;
#endif

    if (it->type().id() == ID_bool) {
      // Hack: don't try to accelerate booleans.
      accelerator.dirty_vars.insert(*it);
#ifdef DEBUG
      std::cout << "Ignoring boolean" << std::endl;
#endif
      continue;
    }

    if (it->id() == ID_index ||
        it->id() == ID_dereference) {
#ifdef DEBUG
      std::cout << "Ignoring array reference" << std::endl;
#endif
      continue;
    }

    if (accelerator.changed_vars.find(*it) != accelerator.changed_vars.end()) {
      // We've accelerated variable this already.
#ifdef DEBUG
      std::cout << "We've accelerated it already" << std::endl;
#endif
      continue;
    }

    // Hack: ignore variables that depend on array values..
    exprt array_rhs;

    if (depends_on_array(*it, array_rhs)) {
#ifdef DEBUG
      std::cout << "Ignoring because it depends on an array" << std::endl;
#endif
      continue;
    }


    polynomialt poly;
    exprt target(*it);

    if (path_acceleration.fit_polynomial(assigns, target, poly)) {
      std::map<exprt, polynomialt> this_poly;
      this_poly[target] = poly;

      if (utils.check_inductive(this_poly, accelerator.path)) {
        polynomials[target] = poly;
        accelerator.changed_vars.insert(target);
        continue;
      }
    }

#ifdef DEBUG
    std::cout << "Failed to accelerate " << expr2c(*it, ns) << std::endl;
#endif

    // We weren't able to accelerate this target...
    accelerator.dirty_vars.insert(target);
  }


  /*
  if (!utils.check_inductive(polynomials, assigns)) {
    // They're not inductive :-(
    return false;
  }
  */

  substitutiont stashed;
  utils.stash_polynomials(program, polynomials, stashed, path);

  exprt guard;
  bool path_is_monotone;
  
  try {
    path_is_monotone = utils.do_assumptions(polynomials, path, guard);
  } catch (std::string s) {
    // Couldn't do WP.
    std::cout << "Assumptions error: " << s << std::endl;
    return false;
  }

  exprt pre_guard(guard);

  for (std::map<exprt, polynomialt>::iterator it = polynomials.begin();
       it != polynomials.end();
       ++it) {
    replace_expr(it->first, it->second.to_expr(), guard);
  }

  if (path_is_monotone) {
    // OK cool -- the path is monotone, so we can just assume the condition for
    // the last iteration.
    replace_expr(loop_counter,
                 minus_exprt(loop_counter, from_integer(1, loop_counter.type())),
                 guard);
  } else {
    // The path is not monotone, so we need to introduce a quantifier to ensure
    // that the condition held for all 0 <= k < n.
    symbolt k_sym = utils.fresh_symbol("polynomial::k", unsignedbv_typet(POLY_WIDTH));
    exprt k = k_sym.symbol_expr();

    exprt k_bound = and_exprt(binary_relation_exprt(from_integer(0, k.type()), "<=", k),
                              binary_relation_exprt(k, "<", loop_counter));
    replace_expr(loop_counter, k, guard);

    simplify(guard, ns);

    implies_exprt implies(k_bound, guard);

    exprt forall(ID_forall);
    forall.type() = bool_typet();
    forall.copy_to_operands(k);
    forall.copy_to_operands(implies);

    guard = forall;
  }

  // All our conditions are met -- we can finally build the accelerator!
  // It is of the form:
  //
  // loop_counter = *;
  // target1 = polynomial1;
  // target2 = polynomial2;
  // ...
  // assume(guard);
  // assume(no overflows in previous code);

  program.add_instruction(ASSUME)->guard = pre_guard;
  program.assign(loop_counter, side_effect_expr_nondett(loop_counter.type()));

  for (std::map<exprt, polynomialt>::iterator it = polynomials.begin();
       it != polynomials.end();
       ++it) {
    program.assign(it->first, it->second.to_expr());
    accelerator.changed_vars.insert(it->first);
  }

  // Add in any array assignments we can do now.
  if (!utils.do_arrays(assigns, polynomials, loop_counter, stashed, program)) {
    // We couldn't model some of the array assignments with polynomials...
    // Unfortunately that means we just have to bail out.
    return false;
  }

  program.add_instruction(ASSUME)->guard = guard;
  program.fix_types();

  if (path_is_monotone) {
    utils.ensure_no_overflows(program);
  }

  accelerator.pure_accelerator.instructions.swap(program.instructions);

  return true;
}
  OutputIterator
  sloan_ordering(Graph& g,
                 typename graph_traits<Graph>::vertex_descriptor s,
                 typename graph_traits<Graph>::vertex_descriptor e,
                 OutputIterator permutation, 
                 ColorMap color, 
                 DegreeMap degree, 
                 PriorityMap priority, 
                 Weight W1, 
                 Weight W2)
  {
    //typedef typename property_traits<DegreeMap>::value_type Degree;
    typedef typename property_traits<PriorityMap>::value_type Degree;
    typedef typename property_traits<ColorMap>::value_type ColorValue;
    typedef color_traits<ColorValue> Color;
    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
    typedef typename std::vector<typename graph_traits<Graph>::vertices_size_type>::iterator vec_iter;
    typedef typename graph_traits<Graph>::vertices_size_type size_type;

    typedef typename property_map<Graph, vertex_index_t>::const_type VertexID;

    
    //Creating a std-vector for storing the distance from the end vertex in it
    typename std::vector<typename graph_traits<Graph>::vertices_size_type> dist(num_vertices(g), 0);
    
    //Wrap a property_map_iterator around the std::iterator
    boost::iterator_property_map<vec_iter, VertexID, size_type, size_type&> dist_pmap(dist.begin(), get(vertex_index, g)); 
    
    breadth_first_search
      (g, e, visitor
       (
           make_bfs_visitor(record_distances(dist_pmap, on_tree_edge() ) )
        )
       );
    
    //Creating a property_map for the indices of a vertex
    typename property_map<Graph, vertex_index_t>::type index_map = get(vertex_index, g);
    
    //Sets the color and priority to their initial status
    unsigned cdeg;    
    typename graph_traits<Graph>::vertex_iterator ui, ui_end;
    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)
    {
        put(color, *ui, Color::white());
        cdeg=get(degree, *ui)+1;
        put(priority, *ui, W1*dist[index_map[*ui]]-W2*cdeg );  
    }
    
    //Priority list
    typedef indirect_cmp<PriorityMap, std::greater<Degree> > Compare;
    Compare comp(priority);
    std::list<Vertex> priority_list;

    //Some more declarations
    typename graph_traits<Graph>::out_edge_iterator ei, ei_end, ei2, ei2_end;
    Vertex u, v, w;

    put(color, s, Color::green());      //Sets the color of the starting vertex to gray
    priority_list.push_front(s);                 //Puts s into the priority_list
    
    while ( !priority_list.empty() ) 
    {  
      priority_list.sort(comp);         //Orders the elements in the priority list in an ascending manner
      
      u = priority_list.front();           //Accesses the last element in the priority list
      priority_list.pop_front();               //Removes the last element in the priority list
      
      if(get(color, u) == Color::green() )
      {
        //for-loop over all out-edges of vertex u
        for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) 
        {
          v = target(*ei, g);
          
          put( priority, v, get(priority, v) + W2 ); //updates the priority
          
          if (get(color, v) == Color::white() )      //test if the vertex is inactive
          {
            put(color, v, Color::green() );        //giving the vertex a preactive status
            priority_list.push_front(v);                     //writing the vertex in the priority_queue
          }           
        }
      }
      
      //Here starts step 8
      *permutation++ = u;                      //Puts u to the first position in the permutation-vector
      put(color, u, Color::black() );          //Gives u an inactive status
      
      //for loop over all the adjacent vertices of u
      for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {
        
        v = target(*ei, g);     
        
        if (get(color, v) == Color::green() ) {      //tests if the vertex is inactive
          
          put(color, v, Color::red() );        //giving the vertex an active status
          put(priority, v, get(priority, v)+W2);  //updates the priority        
          
          //for loop over alll adjacent vertices of v
          for (tie(ei2, ei2_end) = out_edges(v, g); ei2 != ei2_end; ++ei2) {
            w = target(*ei2, g);
            
            if(get(color, w) != Color::black() ) {     //tests if vertex is postactive
              
              put(priority, w, get(priority, w)+W2);  //updates the priority
              
              if(get(color, w) == Color::white() ){
                
                put(color, w, Color::green() );   // gives the vertex a preactive status
                priority_list.push_front(w);           // puts the vertex into the priority queue
                
              } //end if
              
            } //end if
            
          } //end for
          
        } //end if
        
      } //end for
      
    } //end while
    
    
    return permutation;
  }  
Example #24
0
 Weight weight( const LinkIndex& j) const { return weight( source(j), target(j) ); }
Example #25
0
// static
void
xgGtkElement::EventAfter (GtkWidget *widget, GdkEvent *event, gpointer userData)
{
    static GdkEventType  last_type  = GDK_NOTHING;
    static GdkEvent     *last_event = NULL;

    if (event == last_event && event->type == last_type) {
        return;
    }

    if (event->type != GDK_FOCUS_CHANGE) {
	return;
    }

    xgGtkElement *self = reinterpret_cast<xgGtkElement *> (userData);
    if (!self) {
	return;
    }

    nsresult rv;
    nsCOMPtr<nsIDOMElement> elem;
    rv = self->mWrapper->GetElementNode (getter_AddRefs (elem));
    if (NS_FAILED (rv)) {
	return;
    }

    nsCOMPtr<nsIDOMDocument> doc;
    rv = elem->GetOwnerDocument (getter_AddRefs (doc));
    if (NS_FAILED (rv)) {
	return;
    }

    nsCOMPtr<nsIDOMDocumentEvent> docEvent (do_QueryInterface (doc, &rv));
    if (NS_FAILED (rv)) {
	return;
    }

    nsCOMPtr<nsIDOMEvent> evt;
    rv = docEvent->CreateEvent (NS_LITERAL_STRING ("UIEvent"),
				getter_AddRefs (evt));
    if (NS_FAILED (rv)) {
	return;
    }

    nsCOMPtr<nsIDOMUIEvent> uiEvt (do_QueryInterface (evt, &rv));
    if (NS_FAILED (rv)) {
	return;
    }

    rv = uiEvt->InitUIEvent (event->focus_change.in
			     ? NS_LITERAL_STRING ("DOMFocusIn")
			     : NS_LITERAL_STRING ("DOMFocusOut"),
			     PR_TRUE, PR_FALSE, NULL, 0);
    if (NS_FAILED (rv)) {
	return;
    }

    last_type  = event->type;
    last_event = event;

    nsCOMPtr<nsIDOMEventTarget> target (do_QueryInterface (elem, &rv));
    if (NS_FAILED (rv)) {
	return;
    }
    
    PRBool doDefault;
    rv = target->DispatchEvent (evt, &doDefault);
    if (NS_FAILED (rv)) {
	return;
    }
}
Example #26
0
/*
	BHandler *Target(BLooper **looper) const
	@case 5			this is initialized to remote target with specific handler,
					looper is NULL
	@results		should return NULL.
 */
void TargetTester::TargetTest5()
{
	RemoteSMTarget target(false);
	BMessenger messenger(target.Messenger());
	CHK(messenger.Target(NULL) == NULL);
}
Example #27
0
/* { dg-do compile } */
/* { dg-options "-msse" } */

typedef float V
  __attribute__ ((__vector_size__ (16), __may_alias__));

V __attribute__((target("sse"))) f(const V *ptr) { return *ptr; }

V g(const V *ptr) { return *ptr; }
Example #28
0
/*
	bool IsTargetLocal() const
	@case 5			this is initialized to remote target with specific handler
	@results		should return false.
 */
void TargetTester::IsTargetLocalTest5()
{
	RemoteSMTarget target(false);
	BMessenger messenger(target.Messenger());
	CHK(messenger.IsTargetLocal() == false);
}
Example #29
0
  typename graph_traits<VertexListGraph>::degree_size_type
  edge_connectivity(VertexListGraph& g, OutputIterator disconnecting_set)
  {
    //-------------------------------------------------------------------------
    // Type Definitions
    typedef graph_traits<VertexListGraph> Traits;
    typedef typename Traits::vertex_iterator vertex_iterator;
    typedef typename Traits::edge_iterator edge_iterator;
    typedef typename Traits::out_edge_iterator out_edge_iterator;
    typedef typename Traits::vertex_descriptor vertex_descriptor;
    typedef typename Traits::degree_size_type degree_size_type;
    typedef color_traits<default_color_type> Color;

    typedef adjacency_list_traits<vecS, vecS, directedS> Tr;
    typedef typename Tr::edge_descriptor Tr_edge_desc;
    typedef adjacency_list<vecS, vecS, directedS, no_property, 
      property<edge_capacity_t, degree_size_type,
	property<edge_residual_capacity_t, degree_size_type,
	  property<edge_reverse_t, Tr_edge_desc> > > > 
      FlowGraph;
    typedef typename graph_traits<FlowGraph>::edge_descriptor edge_descriptor;

    //-------------------------------------------------------------------------
    // Variable Declarations
    vertex_descriptor u, v, p, k;
    edge_descriptor e1, e2;
    bool inserted;
    vertex_iterator vi, vi_end;
    edge_iterator ei, ei_end;
    degree_size_type delta, alpha_star, alpha_S_k;
    std::set<vertex_descriptor> S, neighbor_S;
    std::vector<vertex_descriptor> S_star, non_neighbor_S;
    std::vector<default_color_type> color(num_vertices(g));
    std::vector<edge_descriptor> pred(num_vertices(g));

    //-------------------------------------------------------------------------
    // Create a network flow graph out of the undirected graph
    FlowGraph flow_g(num_vertices(g));

    typename property_map<FlowGraph, edge_capacity_t>::type
      cap = get(edge_capacity, flow_g);
    typename property_map<FlowGraph, edge_residual_capacity_t>::type
      res_cap = get(edge_residual_capacity, flow_g);
    typename property_map<FlowGraph, edge_reverse_t>::type
      rev_edge = get(edge_reverse, flow_g);

    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
      u = source(*ei, g), v = target(*ei, g);
      tie(e1, inserted) = add_edge(u, v, flow_g);
      cap[e1] = 1;
      tie(e2, inserted) = add_edge(v, u, flow_g);
      cap[e2] = 1; // not sure about this
      rev_edge[e1] = e2;
      rev_edge[e2] = e1;
    }

    //-------------------------------------------------------------------------
    // The Algorithm

    tie(p, delta) = detail::min_degree_vertex(g);
    S_star.push_back(p);
    alpha_star = delta;
    S.insert(p);
    neighbor_S.insert(p);
    detail::neighbors(g, S.begin(), S.end(), 
		      std::inserter(neighbor_S, neighbor_S.begin()));

    std::set_difference(vertices(g).first, vertices(g).second,
			neighbor_S.begin(), neighbor_S.end(),
			std::back_inserter(non_neighbor_S));

    while (!non_neighbor_S.empty()) { // at most n - 1 times
      k = non_neighbor_S.front();

      alpha_S_k = edmunds_karp_max_flow
	(flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]);

      if (alpha_S_k < alpha_star) {
	alpha_star = alpha_S_k;
	S_star.clear();
	for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi)
	  if (color[*vi] != Color::white())
	    S_star.push_back(*vi);
      }
      S.insert(k);
      neighbor_S.insert(k);
      detail::neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin()));
      non_neighbor_S.clear();
      std::set_difference(vertices(g).first, vertices(g).second,
			  neighbor_S.begin(), neighbor_S.end(),
			  std::back_inserter(non_neighbor_S));
    }
    //-------------------------------------------------------------------------
    // Compute edges of the cut [S*, ~S*]
    std::vector<bool> in_S_star(num_vertices(g), false);
    typename std::vector<vertex_descriptor>::iterator si;
    for (si = S_star.begin(); si != S_star.end(); ++si)
      in_S_star[*si] = true;

    degree_size_type c = 0;
    for (si = S_star.begin(); si != S_star.end(); ++si) {
      out_edge_iterator ei, ei_end;
      for (tie(ei, ei_end) = out_edges(*si, g); ei != ei_end; ++ei)
	if (!in_S_star[target(*ei, g)]) {
	  *disconnecting_set++ = *ei;
	  ++c;
	}
    }
    return c;
  }
Example #30
0
void
compute_adjacencies_with_polygon
    (const Matrix &X,
     const Vector &weights,
     const Matrix &polygon,
     std::vector<std::vector<Segment>> &adjedges,
     std::vector<std::vector<size_t>> &adjverts)
{
  auto rt = MA::details::make_regular_triangulation(X,weights);

  int Np = polygon.rows();
  int Nv = X.rows();
  adjedges.assign(Nv, std::vector<Segment>());
  adjverts.assign(Nv, std::vector<size_t>());

  for (int p = 0; p < Np; ++p)
    {
      int pnext = (p + 1) % Np;
      //int pprev = (p + Np - 1) % Np;
      Point source(polygon(p,0), polygon(p,1));
      Point target(polygon(pnext,0), polygon(pnext,1));

      auto u = rt.nearest_power_vertex(source);
      auto v = rt.nearest_power_vertex(target);

      adjverts[u->info()].push_back(p);
      Point pointprev = source;

      auto  uprev = u;
      while (u != v)
	{
	  // find next vertex intersecting with  segment
	  auto c = rt.incident_edges(u), done(c);
	  do
	    {
	      if (rt.is_infinite(c))
		continue;

	      // we do not want to go back to the previous vertex!
	      auto unext = (c->first)->vertex(rt.ccw(c->second));
	      if (unext == uprev)
		continue;

	      // check whether dual edge (which can be a ray, a line
	      // or a segment) intersects with the constraint
	      Point point;
	      if (!edge_dual_and_segment_isect(rt.dual(c),
					       Segment(source,target),
					       point))
		continue;

	      adjedges[u->info()].push_back(Segment(pointprev,point));
	      pointprev = point;
	      uprev = u;
	      u = unext;

	      break;
	    }
	  while(++c != done);
	}

      adjverts[v->info()].push_back(pnext);
      adjedges[v->info()].push_back(Segment(pointprev, target));
    }
}