Example #1
0
void RenderPassManager::_insertSort(Vector<RenderBinManager*>& list, RenderBinManager* mgr, bool renderOrder)
{
   U32 i;
   for (i = 0; i < list.size(); i++)
   {
      bool renderCompare = mgr->getRenderOrder() < list[i]->getRenderOrder();
      bool processAddCompare = mgr->getProcessAddOrder() < list[i]->getProcessAddOrder();
      if ((renderOrder && renderCompare) || (!renderOrder && processAddCompare))      
      {
         list.insert(i);
         list[i] = mgr;
         return;
      }
   }

   list.push_back(mgr);
}
	TAnimationCurve<T> TAnimationCurve<T>::split(float start, float end)
	{
		Vector<TKeyframe<T>> keyFrames;

		start = Math::clamp(start, mStart, mEnd);
		end = Math::clamp(end, mStart, mEnd);

		if (Math::approxEquals(end - start, 0.0f))
			return TAnimationCurve<T>();

		UINT32 startKeyIdx = findKey(start);
		UINT32 endKeyIdx = findKey(end);

		keyFrames.reserve(endKeyIdx - startKeyIdx + 2);

		const KeyFrame& startKey = mKeyframes[startKeyIdx];
		const KeyFrame& endKey = mKeyframes[endKeyIdx];

		if (!Math::approxEquals(startKey.time, start))
		{
			keyFrames.push_back(evaluateKey(startKey, mKeyframes[startKeyIdx + 1], start));

			if (start > startKey.time)
				startKeyIdx++;
		}
		else
		{
			keyFrames.push_back(startKey);
			startKeyIdx++;
		}

		if(!Math::approxEquals(endKey.time, end))
		{
			keyFrames.push_back(evaluateKey(endKey, mKeyframes[endKeyIdx + 1], end));

			if (end < endKey.time)
				endKeyIdx--;
		}

		keyFrames.insert(keyFrames.begin() + 1, mKeyframes.begin() + startKeyIdx, mKeyframes.begin() + endKeyIdx + 1);

		for (auto& entry : keyFrames)
			entry.time -= start;

		return TAnimationCurve<T>(keyFrames);
	}
Example #3
0
void CharacterClassConstructor::addSortedRange(Vector<CharacterClassRange>& ranges, UChar lo, UChar hi)
{
    unsigned end = ranges.size();
    
    // Simple linear scan - I doubt there are that many ranges anyway...
    // feel free to fix this with something faster (eg binary chop).
    for (unsigned i = 0; i < end; ++i) {
        // does the new range fall before the current position in the array
        if (hi < ranges[i].begin) {
            // optional optimization: concatenate appending ranges? - may not be worthwhile.
            if (hi == (ranges[i].begin - 1)) {
                ranges[i].begin = lo;
                return;
            }
            CharacterClassRange r = {lo, hi};
            ranges.insert(i, r);
            return;
        }
        // Okay, since we didn't hit the last case, the end of the new range is definitely at or after the begining
        // If the new range start at or before the end of the last range, then the overlap (if it starts one after the
        // end of the last range they concatenate, which is just as good.
        if (lo <= (ranges[i].end + 1)) {
            // found an intersect! we'll replace this entry in the array.
            ranges[i].begin = std::min(ranges[i].begin, lo);
            ranges[i].end = std::max(ranges[i].end, hi);

            // now check if the new range can subsume any subsequent ranges.
            unsigned next = i+1;
            // each iteration of the loop we will either remove something from the list, or break the loop.
            while (next < ranges.size()) {
                if (ranges[next].begin <= (ranges[i].end + 1)) {
                    // the next entry now overlaps / concatenates this one.
                    ranges[i].end = std::max(ranges[i].end, ranges[next].end);
                    ranges.remove(next);
                } else
                    break;
            }
            
            return;
        }
    }

    // Range comes after all existing ranges.
    CharacterClassRange r = {lo, hi};
    ranges.append(r);
}
static void updateFromStyle(Vector<LayoutUnit>& snapOffsets, const RenderStyle& style, ScrollEventAxis axis, LayoutUnit viewSize, LayoutUnit scrollSize, Vector<LayoutUnit>& snapOffsetSubsequence)
{
    std::sort(snapOffsetSubsequence.begin(), snapOffsetSubsequence.end());
    if (snapOffsetSubsequence.isEmpty())
        snapOffsetSubsequence.append(0);

    auto* points = (axis == ScrollEventAxis::Horizontal) ? style.scrollSnapPointsX() : style.scrollSnapPointsY();
    bool hasRepeat = points ? points->hasRepeat : false;
    LayoutUnit repeatOffset = points ? valueForLength(points->repeatOffset, viewSize) : LayoutUnit::fromPixel(1);
    repeatOffset = std::max<LayoutUnit>(repeatOffset, LayoutUnit::fromPixel(1));
    
    LayoutUnit destinationOffset = destinationOffsetForViewSize(axis, style.scrollSnapDestination(), viewSize);
    LayoutUnit curSnapPositionShift = 0;
    LayoutUnit maxScrollOffset = scrollSize - viewSize;
    LayoutUnit lastSnapPosition = curSnapPositionShift;
    do {
        for (auto& snapPosition : snapOffsetSubsequence) {
            LayoutUnit potentialSnapPosition = curSnapPositionShift + snapPosition - destinationOffset;
            if (potentialSnapPosition < 0)
                continue;

            if (potentialSnapPosition >= maxScrollOffset)
                break;

            // Don't add another zero offset value.
            if (potentialSnapPosition)
                snapOffsets.append(potentialSnapPosition);

            lastSnapPosition = potentialSnapPosition + destinationOffset;
        }
        curSnapPositionShift = lastSnapPosition + repeatOffset;
    } while (hasRepeat && curSnapPositionShift < maxScrollOffset);

    if (snapOffsets.isEmpty())
        return;

    // Always put a snap point on the zero offset.
    if (snapOffsets.first())
        snapOffsets.insert(0, 0);

    // Always put a snap point on the maximum scroll offset.
    // Not a part of the spec, but necessary to prevent unreachable content when snapping.
    if (snapOffsets.last() != maxScrollOffset)
        snapOffsets.append(maxScrollOffset);
}
Example #5
0
int main(int argc, char** argv)
{
    enum {total, unique} mode = total;
    for (int c; (c = getopt(argc, argv, "tu")) != -1;)
    {
        switch(c)
        {
            case 't': mode = total; break;
            case 'u': mode = unique; break;
        }
    }

    argc -= optind;
    argv += optind;
    string word;
    Vector <string> words;

    int count = 0;
    while (cin >> word)
    {
        count += 1;
        bool repeated = false;
        for (auto it=words.begin(); it<words.end(); ++it)
        {

            if ((*it) == word)
            {
                repeated = true;
            }
        }
        if (!repeated)
        {
            words.insert(words.end(), word);
        }
    }
    switch (mode)
    {
        case total: cout << "Total: " << count << endl; break;
        case unique: cout << "Unique: " << words.size() << endl; break;
    }

    return 0;
}
Example #6
0
TEST(small_vector, NoHeap) {
  typedef folly::small_vector<std::string,10,
    std::size_t,folly::small_vector_policy::NoHeap> Vector;

  Vector v;
  static_assert(v.max_size() == 10, "max_size is incorrect");

  for (int i = 0; i < 10; ++i) {
    v.push_back(folly::to<std::string>(i));
    EXPECT_EQ(v.size(), i + 1);
  }

  bool caught = false;
  try {
    v.insert(v.begin(), "ha");
  } catch (const std::length_error&) {
    caught = true;
  }
  EXPECT_TRUE(caught);

  // Check max_size works right with various policy combinations.
  folly::small_vector<std::string,32,uint32_t> v4;
  EXPECT_EQ(v4.max_size(), (1ul << 31) - 1);

  /*
   * Test that even when we ask for a small number inlined it'll still
   * inline at least as much as it takes to store the value_type
   * pointer.
   */
  folly::small_vector<char,1,NoHeap> notsosmall;
  static_assert(notsosmall.max_size() == sizeof(char*),
                "max_size is incorrect");
  caught = false;
  try {
    notsosmall.push_back(12);
    notsosmall.push_back(13);
    notsosmall.push_back(14);
  } catch (const std::length_error&) {
    caught = true;
  }
  EXPECT_FALSE(caught);
}
        /**
         * Test the vector size.
         */
        void test_size()
        {
            Vector<int> a;
            Vector<int> b(10);
            Vector<int> c(20, 8);

            TS_ASSERT(a.size() == 0);
            TS_ASSERT(b.size() == 10);
            TS_ASSERT(c.size() == 20);

            // Should double the capacity
            for (unsigned int i = 0; i < 5; ++i, a.insert(0, 1));
            TS_ASSERT(a.size() == 5);

            for (unsigned int i = 0; i < b.size(); b[i] = 10, ++i);
            TS_ASSERT(b.size() == 10);

            for (unsigned int i = 0; i < 5; ++i, c.erase(0));
            TS_ASSERT(c.size() == 15);
        }
bool PoroElasticity::finalizeElement (LocalIntegral& elmInt, const TimeDomain&, size_t)
{
  ElmMats& elMat = static_cast<ElmMats&>(elmInt);

  Vector prevSol;

  MixedElmMats* mMat = dynamic_cast<MixedElmMats*>(&elmInt);
  if (mMat) {
    mMat->makeNewtonMatrix(elMat.A[Kprev], false);
    prevSol = elmInt.vec[U];
    prevSol.insert(prevSol.end(),elmInt.vec[P].begin(),elmInt.vec[P].end());
  } else {
    NonMixedElmMats* mMat = dynamic_cast<NonMixedElmMats*>(&elmInt);
    mMat->makeNewtonMatrix(elMat.A[Kprev], false);
    utl::interleave(elmInt.vec[U], elmInt.vec[P], prevSol, nsd, 1);
  }

  elMat.b[Fprev] = elMat.A[Kprev]*prevSol;

  return true;
}
Example #9
0
	void check(Matrix a, Vector x, Vector p, double lambda) {
		p.insert(p.begin(), -1);
		Matrix R1 = a * transpose(x) - transpose(x) * lambda;
		double R2 = 0, cc = 1;
		for (int i = 0; i < p.size(); ++i) {
			R2 += p[p.size() - i - 1] * cc;
			cc *= lambda;
		}

		cout << "Polynom coeffs:" << endl;
		print(p);
		cout << "lambda_max:" << endl;
		cout << lambda << endl;
		cout << "Eigenvector:" << endl;
		print(x);
		cout << "Matrix residual norm:" << endl;
		print(R1);
		cout << "Polynom residual:" << endl;
		cout << R2 << endl;
		cout << "Matrix residual norm:" << endl;
		cout << norm(R1) << endl << endl;
	}
Example #10
0
void subtractExclusionIntervals(const Vector<ExclusionInterval>& v1, const Vector<ExclusionInterval>& v2, Vector<ExclusionInterval>& rv)
{
    size_t v1Size = v1.size();
    size_t v2Size = v2.size();

    if (!v1Size)
        return;

    if (!v2Size)
        rv.appendRange(v1.begin(), v1.end());
    else {
        size_t i1 = 0, i2 = 0;
        rv.appendRange(v1.begin(), v1.end());

        while (i1 < rv.size() && i2 < v2Size) {
            ExclusionInterval& interval1 = rv[i1];
            const ExclusionInterval& interval2 = v2[i2];

            if (interval2.x1 <= interval1.x1 && interval2.x2 >= interval1.x2)
                rv.remove(i1);
            else if (interval2.x2 < interval1.x1)
                i2 += 1;
            else if (interval2.x1 > interval1.x2)
                i1 += 1;
            else if (interval2.x1 > interval1.x1 && interval2.x2 < interval1.x2) {
                rv.insert(i1, ExclusionInterval(interval1.x1, interval2.x1));
                interval1.x1 = interval2.x2;
                i2 += 1;
            } else if (interval2.x1 <= interval1.x1) {
                interval1.x1 = interval2.x2;
                i2 += 1;
            } else  { // (interval2.x2 >= interval1.x2)
                interval1.x2 = interval2.x1;
                i1 += 1;
            }
        }
    }
}
Example #11
0
spark::detail::LogFilter::LogFilter(LogLevel level, LogCategoryFilters filters) :
        level_(LOG_LEVEL_NONE) { // Fallback level that will be used in case of construction errors
    // Store category names
    Vector<String> cats;
    if (!cats.reserve(filters.size())) {
        return;
    }
    for (LogCategoryFilter &filter: filters) {
        cats.append(std::move(filter.cat_));
    }
    // Process category filters
    Vector<Node> nodes;
    for (int i = 0; i < cats.size(); ++i) {
        const char *category = cats.at(i).c_str();
        if (!category) {
            continue; // Invalid usage or string allocation error
        }
        Vector<Node> *pNodes = &nodes; // Root nodes
        const char *name = nullptr; // Subcategory name
        size_t size = 0; // Name length
        while ((name = nextSubcategoryName(category, size))) {
            bool found = false;
            const int index = nodeIndex(*pNodes, name, size, found);
            if (!found && !pNodes->insert(index, Node(name, size))) { // Add node
                return;
            }
            Node &node = pNodes->at(index);
            if (!*category) { // Check if it's last subcategory
                node.level = filters.at(i).level_;
            }
            pNodes = &node.nodes;
        }
    }
    using std::swap;
    swap(cats_, cats);
    swap(nodes_, nodes);
    level_ = level;
}
Example #12
0
void EditorFileDialog::_save_to_recent() {

	String dir = get_current_dir();
	Vector<String> recent = EditorSettings::get_singleton()->get_recent_dirs();

	const int max = 20;
	int count = 0;
	bool res = dir.begins_with("res://");

	for (int i = 0; i < recent.size(); i++) {
		bool cres = recent[i].begins_with("res://");
		if (recent[i] == dir || (res == cres && count > max)) {
			recent.remove(i);
			i--;
		} else {
			count++;
		}
	}

	recent.insert(0, dir);

	EditorSettings::get_singleton()->set_recent_dirs(recent);
}
Example #13
0
int main()
{
    Vector<double> v;           // ok: defaultkonstruktor ger vektor med flyttal
    Vector<char> *a = new Vector<char>[3];  // dynamiskt allokerade ser ut så här
    delete [] a;

    assert(v.size() == 0);      // tom från början
    v.push_back(3.14);          // lägg till ett element sist 
    assert(v.size() == 1);      // nu ligger ett element i vektorn
    v.insert(0, 2.10);          // lägg till före element 0, dvs först
    assert(v[0] == 2.10 &&      // hamnade de rätt?
	   v[1] == 3.14);       
    assert(v.size() == 2);      // nu ligger två element i vektorn
    v.sort(false);              // sortera i fallande ordning
    assert(v[0] == 3.14 &&      // hamnade de rätt?
	   v[1] == 2.10);       
    assert(v.size() == 2);      // ingenting ändrat?
    v[1] = 2.11;                // tilldelning av enstaka element;

    const Vector<double> &vc = v;  // skapa konstant referens
    assert(vc.size() == 2);     // ok: ändrar ej vektorn som är konstant
    assert(vc[0] == 3.14 &&     // ok: ändrar ej vektorn som är konstant
	   vc[1] == 2.11);
    
    v.erase(0);                 // ta bort första elementet               
    assert(v.size() == 1);      // rätt antal elelment
    v.clear();                  // töm hela vektorn
    assert(v.size() == 0);      // tom när alla element är borttagna
    
    
    // kontrollera att följande rader inte går att kompilera
    //vc[0] = 3.1415;             // fel: tilldelning av konstant objekt
    //Vector<char> c = v;         // fel: tilldelning av olika typer
    //vc.sort();                  // fel: ändrar konstant objekt

    return 0;
}
void EditorSettings::AddLastOpenedFile(const String & pathToFile)
{
    Vector<String> filesList;
    
    int32 count = GetLastOpenedCount();
    for(int32 i = 0; i < count; ++i)
    {
        String path = settings->GetString(Format("LastOpenedFile_%d", i), "");
        if(path != pathToFile)
        {
            filesList.push_back(path);
        }
    }

    filesList.insert(filesList.begin(), pathToFile);
    count = 0;
    for(;(count < (int32)filesList.size()) && (count < RESENT_FILES_COUNT); ++count)
    {
        settings->SetString(Format("LastOpenedFile_%d", count), filesList[count]);
    }
    settings->SetInt32("LastOpenedFilesCount", count);
    
    Save();
}
Example #15
0
    VkBool32 set(const K& key, const V& value)
    {
        for (size_t i = 0; i < allKeys.size(); i++)
        {
            if (key == allKeys[i])
            {
                allValues[i] = value;

                return VK_TRUE;
            }
            else if (key < allKeys[i])
            {
                allKeys.insert(i, key);
                allValues.insert(i, value);

                return VK_TRUE;
            }
        }

        allKeys.append(key);
        allValues.append(value);

        return VK_TRUE;
    }
Example #16
0
void TemplateVectorTest::onEnter()
{
    UnitTestDemo::onEnter();

    Vector<Node*> vec;
    CCASSERT(vec.empty(), "");
    CCASSERT(vec.capacity() == 0, "");
    CCASSERT(vec.size() == 0, "");
    CCASSERT(vec.max_size() > 0, "");

    auto node1 = Node::create();
    node1->setTag(1);
    vec.pushBack(node1);
    CCASSERT(node1->getReferenceCount() == 2, "");

    auto node2 = Node::create();
    node2->setTag(2);
    vec.pushBack(node2);
    CCASSERT(vec.getIndex(node1) == 0, "");
    CCASSERT(vec.getIndex(node2) == 1, "");

    auto node3 = Node::create();
    node3->setTag(3);
    vec.insert(1, node3);
    CCASSERT(vec.at(0)->getTag() == 1, "");
    CCASSERT(vec.at(1)->getTag() == 3, "");
    CCASSERT(vec.at(2)->getTag() == 2, "");

    // Test copy constructor
    Vector<Node*> vec2(vec);
    CCASSERT(vec2.size() == vec.size(), "");
    ssize_t size = vec.size();
    for (ssize_t i = 0; i < size; ++i)
    {
        CCASSERT(vec2.at(i) == vec.at(i), "");
        CCASSERT(vec.at(i)->getReferenceCount() == 3, "");
        CCASSERT(vec2.at(i)->getReferenceCount() == 3, "");
    }

    // Test copy assignment operator
    Vector<Node*> vec3;
    vec3 = vec2;
    CCASSERT(vec3.size() == vec2.size(), "");
    size = vec3.size();
    for (ssize_t i = 0; i < size; ++i)
    {
        CCASSERT(vec3.at(i) == vec2.at(i), "");
        CCASSERT(vec3.at(i)->getReferenceCount() == 4, "");
        CCASSERT(vec2.at(i)->getReferenceCount() == 4, "");
        CCASSERT(vec.at(i)->getReferenceCount() == 4, "");
    }

    // Test move constructor

    auto createVector = [this]() {
        Vector<Node*> ret;

        for (int i = 0; i < 20; i++)
        {
            ret.pushBack(Node::create());
        }

        int j = 1000;
        for (auto& child : ret)
        {
            child->setTag(j++);
        }

        return ret;
    };

    Vector<Node*> vec4(createVector());
    for (const auto& child : vec4)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // Test init Vector<T> with capacity
    Vector<Node*> vec5(10);
    CCASSERT(vec5.capacity() == 10, "");
    vec5.reserve(20);
    CCASSERT(vec5.capacity() == 20, "");

    CCASSERT(vec5.size() == 0, "");
    CCASSERT(vec5.empty(), "");

    auto toRemovedNode = Node::create();
    vec5.pushBack(toRemovedNode);
    CCASSERT(toRemovedNode->getReferenceCount() == 2, "");

    // Test move assignment operator
    vec5 = createVector();
    CCASSERT(toRemovedNode->getReferenceCount() == 1, "");
    CCASSERT(vec5.size() == 20, "size should be 20");

    for (const auto& child : vec5)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // Test Vector<T>::find
    CCASSERT(vec.find(node3) == (vec.begin() + 1), "");
    CCASSERT(std::find(std::begin(vec), std::end(vec), node2) == (vec.begin() + 2), "");

    CCASSERT(vec.front()->getTag() == 1, "");
    CCASSERT(vec.back()->getTag() == 2, "");

    CCASSERT(vec.getRandomObject(), "");
    CCASSERT(!vec.contains(Node::create()), "");
    CCASSERT(vec.contains(node1), "");
    CCASSERT(vec.contains(node2), "");
    CCASSERT(vec.contains(node3), "");
    CCASSERT(vec.equals(vec2), "");
    CCASSERT(vec.equals(vec3), "");

    // Insert
    vec5.insert(2, node1);
    CCASSERT(vec5.at(2)->getTag() == 1, "");
    CCASSERT(vec5.size() == 21, "");
    vec5.back()->setTag(100);
    vec5.popBack();
    CCASSERT(vec5.size() == 20, "");
    CCASSERT(vec5.back()->getTag() != 100, "");

    // Erase and clear
    Vector<Node*> vec6 = createVector();
    Vector<Node*> vec7 = vec6;  // Copy for check

    CCASSERT(vec6.size() == 20, "");
    vec6.erase(vec6.begin() + 1);  //
    CCASSERT(vec6.size() == 19, "");
    CCASSERT((*(vec6.begin() + 1))->getTag() == 1002, "");
    vec6.erase(vec6.begin() + 2, vec6.begin() + 10);
    CCASSERT(vec6.size() == 11, "");
    CCASSERT(vec6.at(0)->getTag() == 1000, "");
    CCASSERT(vec6.at(1)->getTag() == 1002, "");
    CCASSERT(vec6.at(2)->getTag() == 1011, "");
    CCASSERT(vec6.at(3)->getTag() == 1012, "");
    vec6.erase(3);
    CCASSERT(vec6.at(3)->getTag() == 1013, "");
    vec6.eraseObject(vec6.at(2));
    CCASSERT(vec6.at(2)->getTag() == 1013, "");
    vec6.clear();

    auto objA = Node::create(); // retain count is 1
    auto objB = Node::create();
    auto objC = Node::create();
    {
        Vector<Node*> array1;
        Vector<Node*> array2;

        // push back objA 3 times
        array1.pushBack(objA); // retain count is 2
        array1.pushBack(objA); // retain count is 3
        array1.pushBack(objA); // retain count is 4

        array2.pushBack(objA); // retain count is 5
        array2.pushBack(objB);
        array2.pushBack(objC);

        for (auto obj : array1) {
            array2.eraseObject(obj);
        }
        CCASSERT(objA->getReferenceCount() == 4, "");
    }
    CCASSERT(objA->getReferenceCount() == 1, "");

    {
        Vector<Node*> array1;
        // push back objA 3 times
        array1.pushBack(objA); // retain count is 2
        array1.pushBack(objA); // retain count is 3
        array1.pushBack(objA); // retain count is 4
        CCASSERT(objA->getReferenceCount() == 4, "");
        array1.eraseObject(objA, true); // Remove all occurrences in the Vector.
        CCASSERT(objA->getReferenceCount() == 1, "");

        array1.pushBack(objA); // retain count is 2
        array1.pushBack(objA); // retain count is 3
        array1.pushBack(objA); // retain count is 4

        array1.eraseObject(objA, false);
        CCASSERT(objA->getReferenceCount() == 3, ""); // Only remove the first occurrence in the Vector.
    }

    // Check the retain count in vec7
    CCASSERT(vec7.size() == 20, "");
    for (const auto& child : vec7)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // Sort
    Vector<Node*> vecForSort = createVector();
    std::sort(vecForSort.begin(), vecForSort.end(), [](Node* a, Node* b) {
        return a->getTag() >= b->getTag();
    });

    for (int i = 0; i < 20; ++i)
    {
        CCASSERT(vecForSort.at(i)->getTag() - 1000 == (19 - i), "");
    }

    // Reverse
    vecForSort.reverse();
    for (int i = 0; i < 20; ++i)
    {
        CCASSERT(vecForSort.at(i)->getTag() - 1000 == i, "");
    }

    // Swap
    Vector<Node*> vecForSwap = createVector();
    vecForSwap.swap(2, 4);
    CCASSERT(vecForSwap.at(2)->getTag() == 1004, "");
    CCASSERT(vecForSwap.at(4)->getTag() == 1002, "");
    vecForSwap.swap(vecForSwap.at(2), vecForSwap.at(4));
    CCASSERT(vecForSwap.at(2)->getTag() == 1002, "");
    CCASSERT(vecForSwap.at(4)->getTag() == 1004, "");

    // shrinkToFit
    Vector<Node*> vecForShrink = createVector();
    vecForShrink.reserve(100);
    CCASSERT(vecForShrink.capacity() == 100, "");
    vecForShrink.pushBack(Node::create());
    vecForShrink.shrinkToFit();
    CCASSERT(vecForShrink.capacity() == 21, "");

    // get random object
    // Set the seed by time
    srand((unsigned)time(nullptr));
    Vector<Node*> vecForRandom = createVector();
    log("<--- begin ---->");
    for (int i = 0; i < vecForRandom.size(); ++i)
    {
        log("Vector: random object tag = %d", vecForRandom.getRandomObject()->getTag());
    }
    log("<---- end  ---->");

    // Self assignment
    Vector<Node*> vecSelfAssign = createVector();
    vecSelfAssign = vecSelfAssign;
    CCASSERT(vecSelfAssign.size() == 20, "");

    for (const auto& child : vecSelfAssign)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    vecSelfAssign = std::move(vecSelfAssign);
    CCASSERT(vecSelfAssign.size() == 20, "");

    for (const auto& child : vecSelfAssign)
    {
        CC_UNUSED_PARAM(child);
        CCASSERT(child->getReferenceCount() == 2, "");
    }

    // const at
    Vector<Node*> vecConstAt = createVector();
    constFunc(vecConstAt);
}
Example #17
0
void batched_append(Vector &v, SRange const& s) {
  std::size_t news = v.size()+s.size();
  v.reserve(news);
  v.insert(v.end(), s.begin(), s.end());
}
void TestPushAndInsert()
{
    Vector* vector = VectorInit(DEFAULT_CAPACITY);
    vector->set_clean(vector, CleanElement);
    void* dummy;

    /* Push elements ranging from SML to (SML * 2) to the vector tail. */
    unsigned num = SIZE_SML_TEST;
    unsigned i;
    for (i = 0 ; i < SIZE_SML_TEST ; ++i) {
        Tuple* tuple = (Tuple*)malloc(sizeof(Tuple));
        tuple->first = num;
        tuple->second = num;
        CU_ASSERT(vector->push_back(vector, tuple) == true);
        ++num;
    }
    num = SIZE_SML_TEST;
    for (i = 0 ; i < SIZE_SML_TEST ; ++i) {
        void* tuple;
        CU_ASSERT(vector->get(vector, i, &tuple) == true);
        CU_ASSERT_EQUAL(((Tuple*)tuple)->first, num);
        ++num;
    }
    CU_ASSERT(vector->get(vector, SIZE_SML_TEST << 1, &dummy) == false);
    CU_ASSERT(vector->get(vector, SIZE_MID_TEST, &dummy) == false);

    /* Insert elements ranging from 0 to SML to the vector head. */
    num = SIZE_SML_TEST - 1;
    for (i = 0 ; i < SIZE_SML_TEST ; ++i) {
        Tuple* tuple = (Tuple*)malloc(sizeof(Tuple));
        tuple->first = num;
        tuple->second = num;
        CU_ASSERT(vector->insert(vector, 0, tuple) == true);
        --num;
    }
    for (i = 0 ; i < SIZE_SML_TEST ; ++i) {
        void* tuple;
        CU_ASSERT(vector->get(vector, i, &tuple) == true);
        CU_ASSERT_EQUAL(((Tuple*)tuple)->first, i);
    }
    CU_ASSERT(vector->insert(vector, SIZE_MID_TEST, dummy) == false);

    /* Insert elements ranging from (SML * 2) to (SML * 3) to the vector tail. */
    num = SIZE_SML_TEST << 1;
    for (i = 0 ; i < SIZE_SML_TEST ; ++i) {
        Tuple* tuple = (Tuple*)malloc(sizeof(Tuple));
        tuple->first = num;
        tuple->second = num;
        CU_ASSERT(vector->insert(vector, num, tuple) == true);
        ++num;
    }
    for (i = 0 ; i < SIZE_SML_TEST * 3 ; ++i) {
        void* tuple;
        CU_ASSERT(vector->get(vector, i, &tuple) == true);
        CU_ASSERT_EQUAL(((Tuple*)tuple)->first, i);
    }

    CU_ASSERT_EQUAL(vector->size(vector), SIZE_SML_TEST * 3);
    CU_ASSERT_EQUAL(vector->capacity(vector), SIZE_MID_TEST);

    VectorDeinit(vector);
}
bool CollisionPolygonEditor::forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event) {

	if (!node)
		return false;

	Transform gt = node->get_global_transform();
	Transform gi = gt.affine_inverse();
	float depth = node->get_depth()*0.5;
	Vector3 n = gt.basis.get_axis(2).normalized();
	Plane p(gt.origin+n*depth,n);


	switch(p_event.type) {

		case InputEvent::MOUSE_BUTTON: {

			const InputEventMouseButton &mb=p_event.mouse_button;



			Vector2 gpoint=Point2(mb.x,mb.y);
			Vector3 ray_from = p_camera->project_ray_origin(gpoint);
			Vector3 ray_dir = p_camera->project_ray_normal(gpoint);

			Vector3 spoint;

			if (!p.intersects_ray(ray_from,ray_dir,&spoint))
				break;

			spoint = gi.xform(spoint);

			Vector2 cpoint(spoint.x,spoint.y);

			cpoint=CanvasItemEditor::get_singleton()->snap_point(cpoint);

			Vector<Vector2> poly = node->get_polygon();

			//first check if a point is to be added (segment split)
			real_t grab_treshold=EDITOR_DEF("poly_editor/point_grab_radius",8);

			switch(mode) {


				case MODE_CREATE: {

					if (mb.button_index==BUTTON_LEFT && mb.pressed) {


						if (!wip_active) {

							wip.clear();
							wip.push_back( cpoint );
							wip_active=true;
							edited_point_pos=cpoint;
							_polygon_draw();
							edited_point=1;
							return true;
						} else {


							if (wip.size()>1 && p_camera->unproject_position(gt.xform(Vector3(wip[0].x,wip[0].y,depth))).distance_to(gpoint)<grab_treshold) {
								//wip closed
								_wip_close();

								return true;
							} else {

								wip.push_back( cpoint );
								edited_point=wip.size();
								_polygon_draw();
								return true;

								//add wip point
							}
						}
					} else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
						_wip_close();
					}



				} break;

				case MODE_EDIT: {

					if (mb.button_index==BUTTON_LEFT) {
						if (mb.pressed) {

							if (mb.mod.control) {


								if (poly.size() < 3) {

									undo_redo->create_action("Edit Poly");
									undo_redo->add_undo_method(node,"set_polygon",poly);
									poly.push_back(cpoint);
									undo_redo->add_do_method(node,"set_polygon",poly);
									undo_redo->add_do_method(this,"_polygon_draw");
									undo_redo->add_undo_method(this,"_polygon_draw");
									undo_redo->commit_action();
									return true;
								}

								//search edges
								int closest_idx=-1;
								Vector2 closest_pos;
								real_t closest_dist=1e10;
								for(int i=0;i<poly.size();i++) {

									Vector2 points[2] ={
										p_camera->unproject_position(gt.xform(Vector3(poly[i].x,poly[i].y,depth))),
										p_camera->unproject_position(gt.xform(Vector3(poly[(i+1)%poly.size()].x,poly[(i+1)%poly.size()].y,depth)))
									};

									Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
									if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
										continue; //not valid to reuse point

									real_t d = cp.distance_to(gpoint);
									if (d<closest_dist && d<grab_treshold) {
										closest_dist=d;
										closest_pos=cp;
										closest_idx=i;
									}


								}

								if (closest_idx>=0) {

									pre_move_edit=poly;
									poly.insert(closest_idx+1,cpoint);
									edited_point=closest_idx+1;
									edited_point_pos=cpoint;
									node->set_polygon(poly);
									_polygon_draw();
									return true;
								}
							} else {

								//look for points to move

								int closest_idx=-1;
								Vector2 closest_pos;
								real_t closest_dist=1e10;
								for(int i=0;i<poly.size();i++) {

									Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x,poly[i].y,depth)));

									real_t d = cp.distance_to(gpoint);
									if (d<closest_dist && d<grab_treshold) {
										closest_dist=d;
										closest_pos=cp;
										closest_idx=i;
									}

								}

								if (closest_idx>=0) {

									pre_move_edit=poly;
									edited_point=closest_idx;
									edited_point_pos=poly[closest_idx];
									_polygon_draw();
									return true;
								}
							}
						} else {

							if (edited_point!=-1) {

								//apply

								ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
								poly[edited_point]=edited_point_pos;
								undo_redo->create_action("Edit Poly");
								undo_redo->add_do_method(node,"set_polygon",poly);
								undo_redo->add_undo_method(node,"set_polygon",pre_move_edit);
								undo_redo->add_do_method(this,"_polygon_draw");
								undo_redo->add_undo_method(this,"_polygon_draw");
								undo_redo->commit_action();

								edited_point=-1;
								return true;
							}
						}
					} if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {



						int closest_idx=-1;
						Vector2 closest_pos;
						real_t closest_dist=1e10;
						for(int i=0;i<poly.size();i++) {

							Vector2 cp = p_camera->unproject_position(gt.xform(Vector3(poly[i].x,poly[i].y,depth)));

							real_t d = cp.distance_to(gpoint);
							if (d<closest_dist && d<grab_treshold) {
								closest_dist=d;
								closest_pos=cp;
								closest_idx=i;
							}

						}

						if (closest_idx>=0) {


							undo_redo->create_action("Edit Poly (Remove Point)");
							undo_redo->add_undo_method(node,"set_polygon",poly);
							poly.remove(closest_idx);
							undo_redo->add_do_method(node,"set_polygon",poly);
							undo_redo->add_do_method(this,"_polygon_draw");
							undo_redo->add_undo_method(this,"_polygon_draw");
							undo_redo->commit_action();
							return true;
						}

					}



				} break;
			}



		} break;
		case InputEvent::MOUSE_MOTION: {

			const InputEventMouseMotion &mm=p_event.mouse_motion;

			if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {

				Vector2 gpoint = Point2(mm.x,mm.y);

				Vector3 ray_from = p_camera->project_ray_origin(gpoint);
				Vector3 ray_dir = p_camera->project_ray_normal(gpoint);

				Vector3 spoint;

				if (!p.intersects_ray(ray_from,ray_dir,&spoint))
					break;

				spoint = gi.xform(spoint);

				Vector2 cpoint(spoint.x,spoint.y);

				cpoint=CanvasItemEditor::get_singleton()->snap_point(cpoint);
				edited_point_pos = cpoint;

				_polygon_draw();

			}

		} break;
	}

	return false;
}
Example #20
0
void   testVector(int testSize) {
   printf("\n  ==== Test %2d. Generate a random vector\n", testID++);
   Vector<T> V;
   for (int i = 0; i < testSize; i++) V.insert(dice((Rank)i+1), dice((T)testSize*3)); //在[0, 3n)中选择n个数,随机插入向量
   PRINT(V);
   permute(V);
   PRINT(V)

   printf("\n  ==== Test %2d. Lowpass on\n", testID++); PRINT(V);
   int i = V.size(); while (0 < --i) { V[i-1] += V[i]; V[i-1] >>= 1; }    PRINT(V);

   printf("\n  ==== Test %2d. Increase\n", testID++); PRINT(V);
   increase(V); PRINT(V);

   printf("\n  ==== Test %2d. FIND in\n", testID++); PRINT(V);
   TestFind<T>(V, testSize);

   printf("\n  ==== Test %2d. Sort degenerate intervals each of size 1 in\n", testID++, 0, V.size()); PRINT(V);
   for (int i = 0; i < V.size(); i += V.size()/5) { V.sort(i, i); PRINT(V); } //element by element

   printf("\n  ==== Test %2d. Sort 5 intervals each of size %d in\n", testID++, V.size()/5); PRINT(V);
   for (int i = 0; i < V.size(); i += V.size()/5) { V.sort(i, min(V.size(), i+V.size()/5)); PRINT(V); } //interval by interval

   printf("\n  ==== Test %2d. Sort the entire vector of\n", testID++, 0, V.size()); PRINT(V);
   V.sort();   PRINT(V);

   printf("\n  ==== Test %2d. FIND in\n", testID++); PRINT(V);
   TestFind<T>(V, testSize);

   printf("\n  ==== Test %2d. SEARCH in\n", testID++); PRINT(V);
   TestSearch<T>(V);

   printf("\n  ==== Test %2d. Unsort interval [%d, %d) in\n", testID++, V.size()/4, 3*V.size()/4); PRINT(V);
   V.unsort(V.size()/4, 3*V.size()/4);   PRINT(V);

   printf("\n  ==== Test %2d. Unsort interval [%d, %d) in\n", testID++, 0, V.size()); PRINT(V);
   V.unsort();   PRINT(V);

   printf("\n  ==== Test %2d. Copy interval [%d, %d) from\n", testID++, V.size()/4, 3*V.size()/4); PRINT(V);
   Vector<T> U(V, V.size()/4, 3*V.size()/4);
   PRINT(U);

   printf("\n  ==== Test %2d. Copy from\n", testID++); PRINT(V);
   Vector<T> W(V);
   PRINT(W);

   printf("\n  ==== Test %2d. Clone from\n", testID++); PRINT(U);
   W = U;
   PRINT(W);

   printf("\n  ==== Test %2d. Remove redundancy in unsorted\n", testID++); PRINT(V);
   printf("%d node(s) removed\n", V.deduplicate());   PRINT(V);

   printf("\n  ==== Test %2d. Sort interval [%d, %d) in\n", testID++, 0, V.size()); PRINT(V);
   V.sort();   PRINT(V);

   printf("\n  ==== Test %2d. FIND in V[%d]\n", testID++); PRINT(V);
   TestFind<T>(V, testSize);

   printf("\n  ==== Test %2d. SEARCH & INSERT in\n", testID++); PRINT(V);
   TestOrderedInsertion<T>(V, testSize);  PRINT(V);

   printf("\n  ==== Test %2d. Remove redundancy in sorted\n", testID++); PRINT(V);
   printf("%d node(s) removed\n", V.uniquify());   PRINT(V);
}
Example #21
0
 void push_back(std::size_t iter)
 {
     index_.push_back(iter);
     record_.insert(record_.end(), result_.begin(), result_.end());
 }
void TemplateVectorPerfTest::generateTestFunctions()
{
    auto createVector = [this](){
        Vector<Node*> ret;
        
        for( int i=0; i<quantityOfNodes; ++i)
        {
            auto node = Node::create();
            node->setTag(i);
            ret.pushBack(node);
        }
        return ret;
    };
    
    TestFunction testFunctions[] = {
        { "pushBack",    [=](){
            Vector<Node*> nodeVector;
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.pushBack(Node::create());
            CC_PROFILER_STOP(this->profilerName());
        } } ,
        { "insert",      [=](){
            Vector<Node*> nodeVector;
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.insert(0, Node::create());
            CC_PROFILER_STOP(this->profilerName());
        } } ,
        { "replace",     [=](){
            Vector<Node*> nodeVector = createVector();
            
            srand((unsigned)time(nullptr));
            ssize_t index = rand() % quantityOfNodes;
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.replace(index, Node::create());
            CC_PROFILER_STOP(this->profilerName());
        } } ,
        { "getIndex",    [=](){
            
            Vector<Node*> nodeVector = createVector();
            Node* objToGet = nodeVector.at(quantityOfNodes/3);
            ssize_t index = 0;
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                index = nodeVector.getIndex(objToGet);
            CC_PROFILER_STOP(this->profilerName());
            
            // Uses `index` to avoids `getIndex` invoking was optimized in release mode
            if (index == quantityOfNodes/3)
            {
                nodeVector.clear();
            }
        } } ,
        { "find",        [=](){
            Vector<Node*> nodeVector = createVector();
            Node* objToGet = nodeVector.at(quantityOfNodes/3);
            Vector<Node*>::iterator iter;
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                iter = nodeVector.find(objToGet);
            CC_PROFILER_STOP(this->profilerName());
            
            // Uses `iter` to avoids `find` invoking was optimized in release mode
            if (*iter == objToGet)
            {
                nodeVector.clear();
            }
            
        } } ,
        { "at",          [=](){
            Vector<Node*> nodeVector = createVector();
            Node* objToGet = nullptr;
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                objToGet = nodeVector.at(quantityOfNodes/3);
            CC_PROFILER_STOP(this->profilerName());
            
            // Uses `objToGet` to avoids `at` invoking was optimized in release mode
            if (nodeVector.getIndex(objToGet) == quantityOfNodes/3)
            {
                nodeVector.clear();
            }
        } } ,
        { "contains",    [=](){
            Vector<Node*> nodeVector = createVector();
            Node* objToGet = nodeVector.at(quantityOfNodes/3);
            
            bool ret = false;
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                ret = nodeVector.contains(objToGet);
            CC_PROFILER_STOP(this->profilerName());
            
            // Uses `ret` to avoids `contains` invoking was optimized in release mode
            if (ret)
            {
                nodeVector.clear();
            }
        } } ,
        { "eraseObject", [=](){
            Vector<Node*> nodeVector = createVector();
            Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes);
            
            for (int i = 0; i < quantityOfNodes; ++i)
            {
                nodes[i] = nodeVector.at(i);
            }
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.eraseObject(nodes[i]);
            CC_PROFILER_STOP(this->profilerName());
            
            CCASSERT(nodeVector.empty(), "nodeVector was not empty.");
            
            free(nodes);
        } } ,
        { "erase",       [=](){
            Vector<Node*> nodeVector = createVector();
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.erase(nodeVector.begin());
            CC_PROFILER_STOP(this->profilerName());
            
            CCASSERT(nodeVector.empty(), "nodeVector was not empty.");

        } } ,
        { "clear",       [=](){
            Vector<Node*> nodeVector = createVector();
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.clear();
            CC_PROFILER_STOP(this->profilerName());
            
            CCASSERT(nodeVector.empty(), "nodeVector was not empty.");
        } } ,
        { "swap by index",        [=](){
            Vector<Node*> nodeVector = createVector();
            
            int swapIndex1 = quantityOfNodes / 3;
            int swapIndex2 = quantityOfNodes / 3 * 2;
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.swap(swapIndex1, swapIndex2);
            CC_PROFILER_STOP(this->profilerName());
        } } ,
        
        { "swap by object",        [=](){
            Vector<Node*> nodeVector = createVector();
            
            Node* swapNode1 = nodeVector.at(quantityOfNodes / 3);
            Node* swapNode2 = nodeVector.at(quantityOfNodes / 3 * 2);
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.swap(swapNode1, swapNode2);
            CC_PROFILER_STOP(this->profilerName());
        } } ,
        
        { "reverse",     [=](){
            Vector<Node*> nodeVector = createVector();
            
            CC_PROFILER_START(this->profilerName());
            for( int i=0; i<quantityOfNodes; ++i)
                nodeVector.reverse();
            CC_PROFILER_STOP(this->profilerName());
        } } ,
        
        { "c++11 Range Loop",     [=](){
            Vector<Node*> nodeVector = createVector();
            
            CC_PROFILER_START(this->profilerName());
            for (const auto& e : nodeVector)
            {
                e->setTag(111);
            }
            CC_PROFILER_STOP(this->profilerName());
        } } ,
    };
    
    for (const auto& func : testFunctions)
    {
        _testFunctions.push_back(func);
    }
}
Example #23
0
void TestVector::increaseSize()
{
	tools->setFunctionName("increaseSize");
	{
		Vector<int> instance;
    tools->assertEquals( instance.getMaxSize(),(unsigned)10 );
		instance.insert(1,2);
    instance.insert(9,25);
    tools->description("insert(1,2)");
    tools->description("insert(9,25)");
		tools->assertEquals( instance.getSize(),(unsigned)2 );
		tools->assertEquals( instance.get(1),2 );
		tools->assertEquals( instance.get(9),25 );
		tools->assertEquals( instance.getSize(),(unsigned)2 );
		tools->assertEquals( instance.getMaxSize(),(unsigned)10 );
    instance.insert(15,35);
    tools->description("insert(15,35)");
		tools->assertEquals( instance.getSize(),(unsigned)3 );
		tools->assertEquals( instance.get(9),25 );
		tools->assertEquals( instance.getSize(),(unsigned)3 );
		tools->assertEquals( instance.get(15),35 );
		tools->assertEquals( instance.getSize(),(unsigned)3 );
		tools->assertEquals( instance.getMaxSize(),(unsigned)23 );
		/*
      new = ceil(old * 1.5)
      23 * 1.5 = 23 + 11.5 = 34.5 = 35
      35 * 1.5 = 35 + 17.5 = 52.5 = 53
      53 * 1.5 = 53 + 26.5 = 79.5 = 80
      80 * 1.5 = 80 + 40   = 120  = 120
		*/
		instance.insert(100,55);
    tools->description("insert(100,55)");
		tools->assertEquals( instance.getSize(),(unsigned)4 );
		tools->assertEquals( instance.getMaxSize(),(unsigned)120 );
		tools->assertEquals( instance.get(100) ,55 );

		tools->assertEquals( instance.getMaxSize(),(unsigned)120 );
		instance.clear();
    tools->description("clear()");
		tools->assertTrue( instance.empty() );
		tools->assertEquals( instance.getSize(),(unsigned)0 );
		tools->assertEquals( instance.getMaxSize(),(unsigned)120 );
	}
	{
    tools->description("loop insert");
    Vector<int> instance;
    int value;
    for(unsigned i = 0; i < 300; i++)
    {
      value = i*3;
      instance.insert(i,value);
      if(i == 10)
        tools->assertEquals(instance.get(10),30);
      if(i==100)
        tools->assertEquals(instance.get(100),300);

    }

    tools->assertEquals(instance.getSize(),(unsigned)300);
    tools->assertEquals(instance.getMaxSize(),(unsigned)540);
    tools->assertEquals(instance.get(1),3);
    tools->assertEquals(instance.get(10),30);
    tools->assertEquals(instance.get(100),300);

	}

}
Example #24
0
/*
 * Function: aStar
 * --------------------
 * This function implements aStar search (variation of dijkstras with a heuristic)
 *
 * Preconditions:
 *
 *  @param: graph: The graph to be searched
 *          start: The start vertex
 *          end:The end vertex
 *  @return: returns a vector of vertexes containing the path (empty if no path)
 */
Vector<Vertex*> aStar(BasicGraph& graph, Vertex* start, Vertex* end) {

    graph.resetData(); // reset
    Vector<Vertex*> path; // the return path
    Set<Vertex*> inQueue; // A vector holding the values that we have already put into the queue

    // INitialize every vertex to have infinite cost
    for(Vertex* s:graph.getVertexSet()){
        s->cost = POSITIVE_INFINITY;
    }

    PriorityQueue<Vertex*> pq; // A pq to see where to search next (cost+heuristic = priority)
    // Set start's cost to 0 + heuristicFxn val
    start->cost = 0 + heuristicFunction(start,end);
    // Enqueue start vertex
    pq.enqueue(start,0);
    start->setColor(YELLOW);
    inQueue.add(start);

    // While there are still elements in the pq to try
    while(!pq.isEmpty()){
        Vertex* v = pq.dequeue();
        inQueue.remove(v);

        v->visited = true;
        v->setColor(GREEN);

        // We can stop (reached end)
        if(v == end){
            // We have reached the end, deconstruct
            path.clear();

            Vertex* temp = v;
            path.insert(0,temp);

            while(temp->previous!=NULL){ // deconstruct
                temp = temp->previous;
                path.insert(0,temp);
            }
            break;
        }
        // For each unvisited neighbor of v vertex
        for (Vertex* n: graph.getNeighbors(v)){
            // And it's unvisited
            if(n->visited == false){
                // v's cost plus weight of edge
                Edge* e = graph.getEdge(v,n);
                double edgeCost = e->cost;
                double costToVertexN = v->cost + edgeCost;
                // If the costToVertexN < n->cost, we know this is a better way to get to
                // vertex n
                if(costToVertexN < n->cost){
                    n->cost = costToVertexN;
                    n->previous = v;
                    n->setColor(YELLOW);

                    // Check to see if pq already contains n
                    if(inQueue.contains(n)){ // Priority now includes heuristic
                        pq.changePriority(n,costToVertexN + heuristicFunction(n,end));
                    } else {
                        pq.enqueue(n,costToVertexN + heuristicFunction(n,end));
                    }
                }

            }
        }

    }
    return path;
}
Example #25
0
int main ()
{
Food f1("watermelon",46);
Food f2("potato",115);
Food f3("chocolate",210);
Food f4("chicken",142);
Food f5("milk",9);

Vector <Food> food;
	food.push_back(f1);
	food.push_back(f2);
	food.push_back(f3);
	food.push_back(f4);
	food.push_back(f5);

Vector<int> v1;
v1.push_back(0);
v1.push_back(1);
v1.push_back(1);
v1.push_back(2);
v1.push_back(18);
v1.push_back(3);
v1.push_back(400);
v1.push_back(5);
v1.push_back(8);
v1.erase(4);
v1.erase(5);
cout <<"The 7th Fibonacci number is " << v1.back() << endl; //8
v1.pop_back();
cout <<"The 6th Fibonacci number is " << v1.back() << endl; //5
cout <<"The 5th Fibonacci number is " << v1[4] << endl; //3
//Извежда 0 1 1 2 3 5 
cout << "The first 6 Fibonacci numbers are: ";
for (int i = 0; i < v1.size(); i++)
{
cout << v1[i] << " ";
}
cout <<endl;
cout << "-------------------------------------------------";
cout << endl;

Vector<string> SHINee;
SHINee.push_back("Onew");
SHINee.push_back("Key");
SHINee.push_back("Minho");
SHINee.push_back("Jonghyun");
SHINee.push_back("Taemin");
cout << "The members of SHINee are: "<<endl;
for (int i=0; i<SHINee.size();i++)
{
	cout << SHINee[i] << endl;
}
cout << "-------------------------------------------------";
cout << endl;

Vector<string> TVXQ;
TVXQ.push_back("Uknow Yunho");
TVXQ.push_back("Max Changmin");

TVXQ.insert(2, "Hero Jaejoong");
TVXQ.insert(3, "Micky Yoochun");
TVXQ.insert(4, "Xiah Junsu");

cout << "The members of TVXQ are: " << endl;
for (int i=0; i<TVXQ.size();i++)
{
	cout << TVXQ[i] << endl;
}

return 0;
}
Example #26
0
void exception_loop (int line, const char *fcall, bool capchg,
                     Vector &vec, const Vector::iterator &it,
                     int n, const UserClass *x,
                     const Iterator &first, const Iterator &last,
                     std::size_t *n_copy, std::size_t *n_asgn)
{
    std::size_t throw_after = 0;

    const std::size_t            size     = vec.size ();
    const std::size_t            capacity = vec.capacity ();
    const Vector::const_iterator begin    = vec.begin ();

#ifndef _RWSTD_NO_REPLACEABLE_NEW_DELETE

    rwt_free_store* const pst = rwt_get_free_store (0);

#endif   // _RWSTD_NO_REPLACEABLE_NEW_DELETE

    // iterate for`n=throw_after' starting at the next call to operator
    // new, forcing each call to throw an exception, until the insertion
    // finally succeeds (i.e, no exception is thrown)
    for ( ; ; ) {

        *n_copy = UserClass::n_total_copy_ctor_;
        *n_asgn = UserClass::n_total_op_assign_;

#ifndef _RWSTD_NO_EXCEPTIONS

        // detect objects constructed but not destroyed after an exception
        const std::size_t count = UserClass::count_;

#  ifndef _RWSTD_NO_REPLACEABLE_NEW_DELETE

        // disable out of memory exceptions before copying iterators
        // (InputIter ctors may dynamically allocate memory)
        *pst->throw_at_calls_ [0] = std::size_t (-1);
#  endif   // _RWSTD_NO_REPLACEABLE_NEW_DELETE
#endif   // _RWSTD_NO_EXCEPTIONS

        // create "deep" copies of the iterators to thwart
        // InpuIter's multi-pass detection
        const Iterator beg = copy_iter (first, (UserClass*)0);
        const Iterator end = copy_iter (last, (UserClass*)0);

#ifndef _RWSTD_NO_EXCEPTIONS
#  ifndef _RWSTD_NO_REPLACEABLE_NEW_DELETE

        *pst->throw_at_calls_ [0] = pst->new_calls_ [0] + throw_after + 1;

#  endif   // _RWSTD_NO_REPLACEABLE_NEW_DELETE
#endif   // _RWSTD_NO_EXCEPTIONS

        _TRY {
            if (-2 == n) {
                vec.insert (it, *x);
            }
            else if (-1 == n) {

#ifndef _RWSTD_NO_EXT_VECTOR_INSERT_IN_PLACE
#  ifndef _RWSTD_NO_REPLACEABLE_NEW_DELETE
                // disable exceptions if Iterator is not at least
                // a ForwardIterator since the extension doesn't
                // provide the strong exception safety guarantee
                // required in 23.2.4.3, p1
                if (!is_forward (beg)) {
                    *pst->throw_at_calls_ [0] = std::size_t (-1);
                }
#  endif   //_RWSTD_NO_REPLACEABLE_NEW_DELETE
#endif   // _RWSTD_NO_EXT_VECTOR_INSERT_IN_PLACE

                vec.insert (it, beg, end);
            }
            else {
                vec.insert (it, n, *x);
            }
            break;
        }
        _CATCH (...) {

#ifndef _RWSTD_NO_EXCEPTIONS

            // verify that an exception thrown during allocation
            // doesn't cause a change in the state of the vector

            rw_assert (vec.size () == size, 0, line,
                       "line %d: %s: size unexpectedly changed "
                       "from %zu to %zu after an exception",
                       __LINE__, fcall, size, vec.size ());

            rw_assert (vec.capacity () == capacity, 0, line,
                       "line %d: %s: capacity unexpectedly "
                       "changed from %zu to %zu after an exception",
                       __LINE__, fcall, capacity, vec.capacity ());

            
            rw_assert (vec.begin () == begin, 0, line,
                       "line %d: %s: begin() unexpectedly "
                       "changed from after an exception by %d",
                       __LINE__, fcall, vec.begin () - begin);


            rw_assert (count == UserClass::count_, 0, line,
                       "line %d: %s: leaked %d objects "
                       "after an exception",
                       __LINE__, fcall, UserClass::count_ - count);

            // increment to allow this call to operator new to succeed
            // and force the next one to fail, and try to insert again
            ++throw_after;

#endif   // _RWSTD_NO_EXCEPTIONS

        }   // catch
    }   // for
Example #27
0
int main () {
	Vector v = Vector("4., 5., 6., 9., 8., 7.");
		
	v.print();
	v.print(" .... ");
	v.print(" @@ ", stdout);
	
	assert(v == v);
	assert(v == Vector(" 4., 5., 6., 9., 8., 7."));
	assert(v != Vector(" 3., 4., 5."));
	assert(v.size() == 6);
	assert(v.sum() == 4 + 5 + 6 + 9 + 8 + 7);
	assert(v.prod() == 4 * 5 * 6 * 9 * 8 * 7);
	assert(v.max() == 9);
	assert(v.min() == 4);
	assert(v.which_max() == 3);
	assert(v.which_min() == 0);
	Real v_max, v_min;
	long which_max, which_min;
	v.minmax(v_min, v_max);
	assert(v_min == 4 && v_max == 9);
	v.which_minmax(which_min, which_max);
	assert(which_min == 0 && which_max == 3);
	v += 1;
	assert(v == Vector("5., 6., 7., 10., 9., 8."));
	v *= 2;
	assert(v == Vector("10., 12., 14., 20., 18., 16."));
	v.sort();
	assert(v == Vector("10., 12., 14., 16., 18., 20."));
	
	assert(v.pop_back() == 20.);
	assert(v == Vector(" 10., 12., 14., 16., 18."));
	v.push_back(12.);
	assert(v == Vector(" 10., 12., 14., 16., 18., 12."));
	
	{
		Vector x = v * (3 + v + 2) * v;
		assert(v == Vector("10., 12., 14., 16., 18., 12."));
		assert(x == Vector("1500., 2448., 3724., 5376., 7452., 2448."));
	}
	assert(v == Vector("10., 12., 14., 16., 18., 12."));
	
	Real temp[] = {2, 3, 5, 7, 11};
	{
		Vector w = Vector::view(temp, 5);
		assert(w == Vector("2., 3., 5., 7., 11."));
	}
	assert(temp[0] == 2 && temp[1] == 3 && temp[2] == 5 && temp[3] == 7 && temp[4] == 11);
	
	v.append(Vector("6 7"));
	assert(v == Vector(" 10., 12., 14., 16., 18., 12., 6., 7."));
	assert(v.contains(16.) && v.contains(6.));
	assert(!v.contains(2.));
	long pos = -1;
	assert(v.search(18., 3, pos));
	assert(pos == 4);
	assert(!v.search(18., 5, pos));
	assert(!v.search(9., 0));
	assert(!v.search(10., 1));
	v.sort();
	assert(v.binsearch(16., pos));
	assert(pos == 6);
	assert(!v.binsearch(4.));
	
	v.null();
	assert(v == Vector(" 0., 0., 0., 0., 0., 0., 0., 0."));
	assert(v.isnull());
	v.fill(-12.);
	assert(v == Vector(" -12., -12., -12., -12., -12., -12., -12., -12."));
	assert(!v.isnull());
	
	Vector x = Vector::seq(4, 10);
	assert(x == Vector(" 4., 5., 6., 7., 8., 9., 10."));
	assert(x[2] == 6.);
	x[2] = 13.;
	assert(x[2] == 13.);
	assert(x[3] == 7.);
	assert(x == Vector(" 4., 5., 13., 7., 8., 9., 10."));
	assert(x.e(2) == 13.);
	x.set(3, 14.);
	assert(x == Vector(" 4., 5., 13., 14., 8., 9., 10."));
	assert(*x.e_ptr(3) == 14.);
	*x.e_ptr(4) = 15.;
	assert(x == Vector(" 4., 5., 13., 14., 15., 9., 10."));
	assert(x.tail() == 10.);
	
	Real c[7];
	x.copy_to(c);
	assert(c[0] == 4. && c[1] == 5. && c[2] == 13. && c[3] == 14. && c[4] == 15. && c[5] == 9. && c[6] == 10.);
	x.resize(4);
	assert(x == Vector("4., 5., 13., 14."));
	Vector y = x;
	x.reverse();
	assert(x == Vector(" 14., 13., 5., 4."));
	assert(y == Vector("4., 5., 13., 14."));
	x.swap(y);
	assert(y == Vector("14., 13., 5., 4."));
	assert(x == Vector("4., 5., 13., 14."));
	y.remove(2);
	assert(y == Vector("14., 13., 4."));
	y.swap_elements(0, 1);
	assert(y == Vector("13., 14., 4."));
	x.resize(2);
	assert(x == Vector("4., 5."));
	y.insert(2, 64.);
	y.insert(1, 89.);
	assert(y == Vector("13., 89., 14., 64., 4."));
	{
		Vector u = x;
		assert(x == u);
		u.update(y);
		assert(u == y);
		assert(u == Vector("13., 89., 14., 64., 4."));
	}
	assert(x == Vector("4 5"));
	assert(y == Vector("13., 89., 14., 64., 4."));
	y.remove_section(2, 4);
	assert(y == Vector("13., 89., 4."));
	y.clear();
	assert(y.size() == 0);
	
	{
		igraph_vector_t v6;
		igraph_vector_init(&v6, 7);
		Vector v7(&v6);
		Vector v8=v7;
	}
	
	std::vector<int> sv;
	sv.clear();
	sv.push_back(4);
	sv.push_back(14);
	sv.push_back(5);
	sv.push_back(7);
	
	Vector r = Vector(sv.begin(), sv.end());
	assert(r == Vector("4 14 5 7"));
	sv[1] = 22;
	assert(sv.size() == 4 && sv[0] == 4 && sv[1] == 22 && sv[2] == 5 && sv[3] == 7);
	assert(r == Vector("4 14 5 7"));
	sv = std::vector<int>(r.begin(), r.end());
	assert(sv.size() == 4 && sv[0] == 4 && sv[1] == 14 && sv[2] == 5 && sv[3] == 7);
	r[1] = 22;
	assert(sv.size() == 4 && sv[0] == 4 && sv[1] == 14 && sv[2] == 5 && sv[3] == 7);
	assert(r == Vector("4 22 5 7"));
	std::sort(r.begin(), r.end());
	assert(r == Vector("4 5 7 22"));
	assert(std::inner_product(sv.begin(), sv.end(), r.begin(), 0) == 4*4+14*5+5*7+7*22);
	
	Real d[] = {1., 4., 9., 16., 25., 49.};
	r = Vector(d, 6);
	assert(r == Vector("1 4 9 16 25 49"));
	d[5] = 36;
	assert(r == Vector("1 4 9 16 25 49"));
	r[5] = 81;
	assert(d[5] == 36);
	r = Vector::view(d, 6);
	d[4] = 121;
	assert(r == Vector("1 4 9 16 121 36"));
	r[3] = 144;
	assert(d[3] == 144);
	
#if XXINTRNL_CXX0X
	assert(Vector("2 -4 6 12") == Vector({2, -4, 6, 12}));
#endif
	
	assert(Vector("1 1 1 1 1; 2 2 2; 3; 4 4 4 4; 5 5 5").distribution() == Vector("0, 0.3125, 0.1875, 0.0625, 0.25, 0.1875"));
	
	{
		Vector r ("1 4 6 12 11 4");
		Vector s ("6 -2 5 8 6 4");
		assert(r.maxdifference(s) == 6);
		
		r = Vector("1 4 6 12 11 4 124 4");
		r.remove_first_matching(4);
		assert(r == Vector("1 6 12 11 4 124 4"));
		r.remove_all_matching(4);
		assert(r == Vector("1 6 12 11 124"));
		r.sort();
		assert(r == Vector("1 6 11 12 124"));
		r.remove_first_matching_assume_sorted(11);
		assert(r == Vector("1 6 12 124"));
		r.remove_first_matching(4);
		assert(r == Vector("1 6 12 124"));
		r.remove_first_matching_assume_sorted(9);
		assert(r == Vector("1 6 12 124"));
	}
	
	assert(Vector("1 2 3 4 5 6 7").intersect_sorted(Vector("4 5 7 9 11")) == Vector("4 5 7"));
	assert(Vector("1 1 1 1 1 6 7 8").intersect_sorted(Vector("1 1 1 6 7 7 7")) == Vector("1 6 7"));
	assert(Vector("1 1 1 1 1 6 7 8").intersect_sorted(Vector("1 1 1 6 7 7 7"), Vector::NotUnique) == Vector("1 1 1 1, 1 1 1 1; 6 6; 7 7 7 7"));

	{
		Vector t ("1 8 2 7 3 6 4 5");
		t.move_interval(2, 4, 0);
		assert(t == Vector("2 7 2 7 3 6 4 5"));
		t.move_interval(3, 6, 4);
		assert(t == Vector("2 7 2 7 7 3 6 5"));
		assert(t.isininterval(1, 8));
		assert(!t.isininterval(3, 8));
		assert(t.isininterval(2, 7));
		assert(!t.isininterval(1, 5));
		assert(t.any_smaller(3));
		assert(!t.any_smaller(2));
		
		t -= t / 4;
		assert(t == "1.5,5.25,1.5,5.25,5.25,2.25,4.5,3.75");
		t /= Vector("1 2 4 8 -1 -2 -4 -8");
		assert(t == "1.5,2.625,0.375,0.65625,-5.25,-1.125,-1.125,-0.46875");
		t += t * 31;
		assert(t == "48.,84.,12.,21.,-168.,-36.,-36.,-15.");
		
		
		Vector u (12);
		assert(u.isnull());
		assert(u.size() == 12);
		assert(!v.empty());
		Vector v = Vector::n();
		assert(v.isnull());
		assert(v.empty());
		assert(v.size() == 0);
	}
	
	printf("vector.hpp is correct.\n");

	return 0;
}
bool CollisionPolygon2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) {

	if (!node)
		return false;

	Ref<InputEventMouseButton> mb;

	if (mb.is_valid()) {
		Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();

		Vector2 gpoint = mb->get_position();
		Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
		cpoint = canvas_item_editor->snap_point(cpoint);
		cpoint = node->get_global_transform().affine_inverse().xform(cpoint);

		Vector<Vector2> poly = node->get_polygon();

		//first check if a point is to be added (segment split)
		real_t grab_treshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);

		switch (mode) {

			case MODE_CREATE: {

				if (mb->get_button_index() == BUTTON_LEFT && mb->is_pressed()) {

					if (!wip_active) {

						wip.clear();
						wip.push_back(cpoint);
						wip_active = true;
						edited_point_pos = cpoint;
						canvas_item_editor->get_viewport_control()->update();
						edited_point = 1;
						return true;
					} else {

						if (wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_treshold) {
							//wip closed
							_wip_close();

							return true;
						} else {

							wip.push_back(cpoint);
							edited_point = wip.size();
							canvas_item_editor->get_viewport_control()->update();
							return true;

							//add wip point
						}
					}
				} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && wip_active) {
					_wip_close();
				}

			} break;

			case MODE_EDIT: {

				if (mb->get_button_index() == BUTTON_LEFT) {
					if (mb->is_pressed()) {

						if (mb->get_control()) {

							if (poly.size() < 3) {

								undo_redo->create_action(TTR("Edit Poly"));
								undo_redo->add_undo_method(node, "set_polygon", poly);
								poly.push_back(cpoint);
								undo_redo->add_do_method(node, "set_polygon", poly);
								undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
								undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
								undo_redo->commit_action();
								return true;
							}

							//search edges
							int closest_idx = -1;
							Vector2 closest_pos;
							real_t closest_dist = 1e10;
							for (int i = 0; i < poly.size(); i++) {

								Vector2 points[2] = { xform.xform(poly[i]),
									xform.xform(poly[(i + 1) % poly.size()]) };

								Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
								if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
									continue; //not valid to reuse point

								real_t d = cp.distance_to(gpoint);
								if (d < closest_dist && d < grab_treshold) {
									closest_dist = d;
									closest_pos = cp;
									closest_idx = i;
								}
							}

							if (closest_idx >= 0) {

								pre_move_edit = poly;
								poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos));
								edited_point = closest_idx + 1;
								edited_point_pos = xform.affine_inverse().xform(closest_pos);
								node->set_polygon(poly);
								canvas_item_editor->get_viewport_control()->update();
								return true;
							}
						} else {

							//look for points to move

							int closest_idx = -1;
							Vector2 closest_pos;
							real_t closest_dist = 1e10;
							for (int i = 0; i < poly.size(); i++) {

								Vector2 cp = xform.xform(poly[i]);

								real_t d = cp.distance_to(gpoint);
								if (d < closest_dist && d < grab_treshold) {
									closest_dist = d;
									closest_pos = cp;
									closest_idx = i;
								}
							}

							if (closest_idx >= 0) {

								pre_move_edit = poly;
								edited_point = closest_idx;
								edited_point_pos = xform.affine_inverse().xform(closest_pos);
								canvas_item_editor->get_viewport_control()->update();
								return true;
							}
						}
					} else {

						if (edited_point != -1) {

							//apply

							ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
							poly[edited_point] = edited_point_pos;
							undo_redo->create_action(TTR("Edit Poly"));
							undo_redo->add_do_method(node, "set_polygon", poly);
							undo_redo->add_undo_method(node, "set_polygon", pre_move_edit);
							undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
							undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
							undo_redo->commit_action();

							edited_point = -1;
							return true;
						}
					}
				} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && edited_point == -1) {

					int closest_idx = -1;
					Vector2 closest_pos;
					real_t closest_dist = 1e10;
					for (int i = 0; i < poly.size(); i++) {

						Vector2 cp = xform.xform(poly[i]);

						real_t d = cp.distance_to(gpoint);
						if (d < closest_dist && d < grab_treshold) {
							closest_dist = d;
							closest_pos = cp;
							closest_idx = i;
						}
					}

					if (closest_idx >= 0) {

						undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
						undo_redo->add_undo_method(node, "set_polygon", poly);
						poly.remove(closest_idx);
						undo_redo->add_do_method(node, "set_polygon", poly);
						undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
						undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
						undo_redo->commit_action();
						return true;
					}
				}

			} break;
		}
	}

	Ref<InputEventMouseMotion> mm = p_event;

	if (mm.is_valid()) {

		if (edited_point != -1 && (wip_active || mm->get_button_mask() & BUTTON_MASK_LEFT)) {

			Vector2 gpoint = mm->get_position();
			Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
			cpoint = canvas_item_editor->snap_point(cpoint);
			edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);

			canvas_item_editor->get_viewport_control()->update();
		}
	}

	return false;
}
bool LightOccluder2DEditor::forward_input_event(const InputEvent& p_event) {


	if (!node)
		return false;

	if (node->get_occluder_polygon().is_null()) {
		if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1 && p_event.mouse_button.pressed) {
			create_poly->set_text("No OccluderPolygon2D resource on this node.\nCreate and assign one?");
			create_poly->popup_centered_minsize();
		}
		return false;
	}
	switch(p_event.type) {

		case InputEvent::MOUSE_BUTTON: {

			const InputEventMouseButton &mb=p_event.mouse_button;

			Matrix32 xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();


			Vector2 gpoint = Point2(mb.x,mb.y);
			Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
			cpoint=snap_point(cpoint);
			cpoint = node->get_global_transform().affine_inverse().xform(cpoint);

			Vector<Vector2> poly = Variant(node->get_occluder_polygon()->get_polygon());

			//first check if a point is to be added (segment split)
			real_t grab_treshold=EDITOR_DEF("poly_editor/point_grab_radius",8);

			switch(mode) {


				case MODE_CREATE: {

					if (mb.button_index==BUTTON_LEFT && mb.pressed) {


						if (!wip_active) {

							wip.clear();
							wip.push_back( cpoint );
							wip_active=true;
							edited_point_pos=cpoint;
							canvas_item_editor->get_viewport_control()->update();
							edited_point=1;
							return true;
						} else {


							if (wip.size()>1 && xform.xform(wip[0]).distance_to(gpoint)<grab_treshold) {
								//wip closed
								_wip_close(true);

								return true;
							} else if (wip.size()>1 && xform.xform(wip[wip.size()-1]).distance_to(gpoint)<grab_treshold) {
									//wip closed
									_wip_close(false);
									return true;

							} else {

								wip.push_back( cpoint );
								edited_point=wip.size();
								canvas_item_editor->get_viewport_control()->update();
								return true;

								//add wip point
							}
						}
					} else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
						_wip_close(true);
					}



				} break;

				case MODE_EDIT: {

					if (mb.button_index==BUTTON_LEFT) {
						if (mb.pressed) {

							if (mb.mod.control) {


								if (poly.size() < 3) {

									undo_redo->create_action("Edit Poly");
									undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
									poly.push_back(cpoint);
									undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
									undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
									undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
									undo_redo->commit_action();
									return true;
								}

								//search edges
								int closest_idx=-1;
								Vector2 closest_pos;
								real_t closest_dist=1e10;
								for(int i=0;i<poly.size();i++) {

									Vector2 points[2] ={ xform.xform(poly[i]),
										xform.xform(poly[(i+1)%poly.size()]) };

									Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
									if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
										continue; //not valid to reuse point

									real_t d = cp.distance_to(gpoint);
									if (d<closest_dist && d<grab_treshold) {
										closest_dist=d;
										closest_pos=cp;
										closest_idx=i;
									}


								}

								if (closest_idx>=0) {

									pre_move_edit=poly;
									poly.insert(closest_idx+1,xform.affine_inverse().xform(closest_pos));
									edited_point=closest_idx+1;
									edited_point_pos=xform.affine_inverse().xform(closest_pos);
									node->get_occluder_polygon()->set_polygon(Variant(poly));
									canvas_item_editor->get_viewport_control()->update();
									return true;
								}
							} else {

								//look for points to move

								int closest_idx=-1;
								Vector2 closest_pos;
								real_t closest_dist=1e10;
								for(int i=0;i<poly.size();i++) {

									Vector2 cp =xform.xform(poly[i]);

									real_t d = cp.distance_to(gpoint);
									if (d<closest_dist && d<grab_treshold) {
										closest_dist=d;
										closest_pos=cp;
										closest_idx=i;
									}

								}

								if (closest_idx>=0) {

									pre_move_edit=poly;
									edited_point=closest_idx;
									edited_point_pos=xform.affine_inverse().xform(closest_pos);
									canvas_item_editor->get_viewport_control()->update();
									return true;
								}
							}
						} else {

							if (edited_point!=-1) {

								//apply

								ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
								poly[edited_point]=edited_point_pos;
								undo_redo->create_action("Edit Poly");
								undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
								undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_polygon",pre_move_edit);
								undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
								undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
								undo_redo->commit_action();

								edited_point=-1;
								return true;
							}
						}
					} if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {



						int closest_idx=-1;
						Vector2 closest_pos;
						real_t closest_dist=1e10;
						for(int i=0;i<poly.size();i++) {

							Vector2 cp =xform.xform(poly[i]);

							real_t d = cp.distance_to(gpoint);
							if (d<closest_dist && d<grab_treshold) {
								closest_dist=d;
								closest_pos=cp;
								closest_idx=i;
							}

						}

						if (closest_idx>=0) {


							undo_redo->create_action("Edit Poly (Remove Point)");
							undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
							poly.remove(closest_idx);
							undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
							undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
							undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
							undo_redo->commit_action();
							return true;
						}

					}



				} break;
			}



		} break;
		case InputEvent::MOUSE_MOTION: {

			const InputEventMouseMotion &mm=p_event.mouse_motion;

			if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {

				Vector2 gpoint = Point2(mm.x,mm.y);
				Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
				cpoint=snap_point(cpoint);
				edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);

				canvas_item_editor->get_viewport_control()->update();

			}

		} break;
	}

	return false;
}
Example #30
0
int main()
{
	STRERR = stdout;
	STRLOG = stdout;
	
	FILE* strout = fopen("output.txt", "w");
	assert(strout != NULL);

	Vector a;
	for (int i = 0; i < 5 ; ++i)
	{
		a.push_back(rand() % RANDOM_RANGE);
		putc('\n', strout);
		printf("Size = %d, Memory = %d\n", a.get_size(), a.get_memory_size());
	}
	
	a.dump();
	a *= 10;
	a.dump();
	a.shift_left(2);
	a.dump();
	a.shift_right(1);
	a.dump();
	a.insert(3.1415, 3);
	a.dump();
	double data_a[] = {1, 2, 3};
	a.insert_array(data_a, 3, 1);
	a.dump();
	/*
	for (int i = 1; i < 20; ++i) a.push_back(i);

	a.print(strout);
	printf("\n%lg - module\n", a.module());

	a.reset();
	printf("Resetting...\n");
	a.print(strout);

	fputc('\n', strout);

	fprintf(strout, "Checking memory autoallocating...\n");
	for (int i = 0; i < 10; ++i)
	{
		a.push_back(rand() % RANDOM_RANGE);
		putc('\n', strout);
		printf("Size = %d, Memory = %d\n", a.get_size(), a.get_memory_size());
	}
	fprintf(strout, "\nDone\nResetting...\n\n");
	fprintf(strout, "Creating another vector. Testing copying \n");

	Vector b = a;
	a.dump(strout);
	putc('\n', strout);
	b.dump(strout);


	fprintf(strout, "Test done. Resetting and generating random vectors\n");
	a.reset();
	b.reset();
	
	for (int i = 0; i < 3; ++i) 
	{ 
		a.push_back(rand() % RANDOM_RANGE);
		b.push_back(rand() % RANDOM_RANGE);
	}
	b.push_back(rand() % RANDOM_RANGE);

	fprintf(strout, "Dumping first...\n\n");
	a.dump(strout);
	fprintf(strout, "Dumping second...\n\n");
	b.dump(strout);

	Vector c = a + b;
	fprintf(strout, "\nDumping sum...\n\n");
	c.dump(strout);
	
	Vector d = a - b;
	fprintf(strout, "\nDumping difference...\n\n");
	d.dump(strout);
	
	Vector e = a * 10;
	fprintf(strout, "\nDumping first * 10...\n\n");
	e.dump(strout);
	
	Vector f = (1/10.0) * e;
	fprintf(strout, "\nDumping (1/10) * last result...\n\n");
	f.dump(strout);

	double temp_data[] = {1, 2, 3, 4, 5};
	Vector g = {5, temp_data};
	fprintf(strout, "\nTesting creating vector from {1, 2, 3, 4, 5} array\n\n");
	g.dump(strout);

	fprintf(strout, "\nPrinting data using [] operands...\n\n");
	for (int i = 0; i < g.get_size(); ++i) fprintf(strout, "%lg\n", g[i]);
	*/
	system("PAUSE");
	return 0;
}