<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Test.h"
#include "SkRegion.h"
#include "SkRandom.h"

static void test_empties(skiatest::Reporter* reporter) {
    SkRegion valid(SkIRect::MakeWH(10, 10));
    SkRegion empty, empty2;

    REPORTER_ASSERT(reporter, empty.isEmpty());
    REPORTER_ASSERT(reporter, !valid.isEmpty());

    // test intersects
    REPORTER_ASSERT(reporter, !empty.intersects(empty2));
    REPORTER_ASSERT(reporter, !valid.intersects(empty));

    // test contains
    REPORTER_ASSERT(reporter, !empty.contains(empty2));
    REPORTER_ASSERT(reporter, !valid.contains(empty));
    REPORTER_ASSERT(reporter, !empty.contains(valid));
}

enum {
    W = 256,
    H = 256
};

static SkIRect randRect(SkRandom& rand) {
    int x = rand.nextU() % W;
    int y = rand.nextU() % H;
    int w = rand.nextU() % W;
    int h = rand.nextU() % H;
    return SkIRect::MakeXYWH(x, y, w >> 1, h >> 1);
}

static void randRgn(SkRandom& rand, SkRegion* rgn, int n) {
    rgn->setEmpty();
    for (int i = 0; i < n; ++i) {
        rgn->op(randRect(rand), SkRegion::kUnion_Op);
    }
}

static bool slow_contains(const SkRegion& outer, const SkRegion& inner) {
    SkRegion tmp;
    tmp.op(outer, inner, SkRegion::kUnion_Op);
    return outer == tmp;
}

static bool slow_intersects(const SkRegion& outer, const SkRegion& inner) {
    SkRegion tmp;
    return tmp.op(outer, inner, SkRegion::kIntersect_Op);
}

static void contains_proc(skiatest::Reporter* reporter,
                          const SkRegion& a, const SkRegion& b) {
    bool c0 = a.contains(b);
    bool c1 = slow_contains(a, b);
    REPORTER_ASSERT(reporter, c0 == c1);
}

static void intersects_proc(skiatest::Reporter* reporter,
                          const SkRegion& a, const SkRegion& b) {
    bool c0 = a.intersects(b);
    bool c1 = slow_intersects(a, b);
    REPORTER_ASSERT(reporter, c0 == c1);
}

static void test_proc(skiatest::Reporter* reporter,
                      void (*proc)(skiatest::Reporter*,
                                   const SkRegion& a, const SkRegion&)) {
    SkRandom rand;
    for (int i = 0; i < 10000; ++i) {
        SkRegion outer;
        randRgn(rand, &outer, 8);
        SkRegion inner;
        randRgn(rand, &inner, 2);
        proc(reporter, outer, inner);
    }
}

static void rand_rect(SkIRect* rect, SkRandom& rand) {
    int bits = 6;
    int shift = 32 - bits;
    rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
              rand.nextU() >> shift, rand.nextU() >> shift);
    rect->sort();
}

static bool test_rects(const SkIRect rect[], int count) {
    SkRegion rgn0, rgn1;

    for (int i = 0; i < count; i++) {
        rgn0.op(rect[i], SkRegion::kUnion_Op);
    }
    rgn1.setRects(rect, count);

    if (rgn0 != rgn1) {
        SkDebugf("\n");
        for (int i = 0; i < count; i++) {
            SkDebugf(" { %d, %d, %d, %d },\n",
                     rect[i].fLeft, rect[i].fTop,
                     rect[i].fRight, rect[i].fBottom);
        }
        SkDebugf("\n");
        return false;
    }
    return true;
}

static void TestRegion(skiatest::Reporter* reporter) {
    const SkIRect r2[] = {
        { 0, 0, 1, 1 },
        { 2, 2, 3, 3 },
    };
    REPORTER_ASSERT(reporter, test_rects(r2, SK_ARRAY_COUNT(r2)));

    const SkIRect rects[] = {
        { 0, 0, 1, 2 },
        { 2, 1, 3, 3 },
        { 4, 0, 5, 1 },
        { 6, 0, 7, 4 },
    };
    REPORTER_ASSERT(reporter, test_rects(rects, SK_ARRAY_COUNT(rects)));

    SkRandom rand;
    for (int i = 0; i < 1000; i++) {
        SkRegion rgn0, rgn1;

        const int N = 8;
        SkIRect rect[N];
        for (int j = 0; j < N; j++) {
            rand_rect(&rect[j], rand);
        }
        REPORTER_ASSERT(reporter, test_rects(rect, N));
    }

    test_proc(reporter, contains_proc);
    test_proc(reporter, intersects_proc);
    test_empties(reporter);
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("Region", RegionTestClass, TestRegion)
<commit_msg>add more tests around contains for rects and regions<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Test.h"
#include "SkRegion.h"
#include "SkRandom.h"

static void test_empties(skiatest::Reporter* reporter) {
    SkRegion valid(SkIRect::MakeWH(10, 10));
    SkRegion empty, empty2;

    REPORTER_ASSERT(reporter, empty.isEmpty());
    REPORTER_ASSERT(reporter, !valid.isEmpty());

    // test intersects
    REPORTER_ASSERT(reporter, !empty.intersects(empty2));
    REPORTER_ASSERT(reporter, !valid.intersects(empty));

    // test contains
    REPORTER_ASSERT(reporter, !empty.contains(empty2));
    REPORTER_ASSERT(reporter, !valid.contains(empty));
    REPORTER_ASSERT(reporter, !empty.contains(valid));
}

enum {
    W = 256,
    H = 256
};

static SkIRect randRect(SkRandom& rand) {
    int x = rand.nextU() % W;
    int y = rand.nextU() % H;
    int w = rand.nextU() % W;
    int h = rand.nextU() % H;
    return SkIRect::MakeXYWH(x, y, w >> 1, h >> 1);
}

static void randRgn(SkRandom& rand, SkRegion* rgn, int n) {
    rgn->setEmpty();
    for (int i = 0; i < n; ++i) {
        rgn->op(randRect(rand), SkRegion::kUnion_Op);
    }
}

static bool slow_contains(const SkRegion& outer, const SkRegion& inner) {
    SkRegion tmp;
    tmp.op(outer, inner, SkRegion::kUnion_Op);
    return outer == tmp;
}

static bool slow_contains(const SkRegion& outer, const SkIRect& r) {
    SkRegion tmp;
    tmp.op(outer, SkRegion(r), SkRegion::kUnion_Op);
    return outer == tmp;
}

static bool slow_intersects(const SkRegion& outer, const SkRegion& inner) {
    SkRegion tmp;
    return tmp.op(outer, inner, SkRegion::kIntersect_Op);
}

static void test_contains_iter(skiatest::Reporter* reporter, const SkRegion& rgn) {
    SkRegion::Iterator iter(rgn);
    while (!iter.done()) {
        SkIRect r = iter.rect();
        REPORTER_ASSERT(reporter, rgn.contains(r));
        r.inset(-1, -1);
        REPORTER_ASSERT(reporter, !rgn.contains(r));
        iter.next();
    }
}

static void contains_proc(skiatest::Reporter* reporter,
                          const SkRegion& a, const SkRegion& b) {
    // test rgn
    bool c0 = a.contains(b);
    bool c1 = slow_contains(a, b);
    REPORTER_ASSERT(reporter, c0 == c1);

    // test rect
    SkIRect r = a.getBounds();
    r.inset(r.width()/4, r.height()/4);
    c0 = a.contains(r);
    c1 = slow_contains(a, r);
    REPORTER_ASSERT(reporter, c0 == c1);

    test_contains_iter(reporter, a);
    test_contains_iter(reporter, b);
}

static void intersects_proc(skiatest::Reporter* reporter,
                          const SkRegion& a, const SkRegion& b) {
    bool c0 = a.intersects(b);
    bool c1 = slow_intersects(a, b);
    REPORTER_ASSERT(reporter, c0 == c1);
}

static void test_proc(skiatest::Reporter* reporter,
                      void (*proc)(skiatest::Reporter*,
                                   const SkRegion& a, const SkRegion&)) {
    SkRandom rand;
    for (int i = 0; i < 10000; ++i) {
        SkRegion outer;
        randRgn(rand, &outer, 8);
        SkRegion inner;
        randRgn(rand, &inner, 2);
        proc(reporter, outer, inner);
    }
}

static void rand_rect(SkIRect* rect, SkRandom& rand) {
    int bits = 6;
    int shift = 32 - bits;
    rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
              rand.nextU() >> shift, rand.nextU() >> shift);
    rect->sort();
}

static bool test_rects(const SkIRect rect[], int count) {
    SkRegion rgn0, rgn1;

    for (int i = 0; i < count; i++) {
        rgn0.op(rect[i], SkRegion::kUnion_Op);
    }
    rgn1.setRects(rect, count);

    if (rgn0 != rgn1) {
        SkDebugf("\n");
        for (int i = 0; i < count; i++) {
            SkDebugf(" { %d, %d, %d, %d },\n",
                     rect[i].fLeft, rect[i].fTop,
                     rect[i].fRight, rect[i].fBottom);
        }
        SkDebugf("\n");
        return false;
    }
    return true;
}

static void TestRegion(skiatest::Reporter* reporter) {
    const SkIRect r2[] = {
        { 0, 0, 1, 1 },
        { 2, 2, 3, 3 },
    };
    REPORTER_ASSERT(reporter, test_rects(r2, SK_ARRAY_COUNT(r2)));

    const SkIRect rects[] = {
        { 0, 0, 1, 2 },
        { 2, 1, 3, 3 },
        { 4, 0, 5, 1 },
        { 6, 0, 7, 4 },
    };
    REPORTER_ASSERT(reporter, test_rects(rects, SK_ARRAY_COUNT(rects)));

    SkRandom rand;
    for (int i = 0; i < 1000; i++) {
        SkRegion rgn0, rgn1;

        const int N = 8;
        SkIRect rect[N];
        for (int j = 0; j < N; j++) {
            rand_rect(&rect[j], rand);
        }
        REPORTER_ASSERT(reporter, test_rects(rect, N));
    }

    test_proc(reporter, contains_proc);
    test_proc(reporter, intersects_proc);
    test_empties(reporter);
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("Region", RegionTestClass, TestRegion)
<|endoftext|>


<commit_before>/*
 * Copyright 2011-2012 Gregory Banks
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef __np_spiegel_dwarf_reader_hxx__
#define __np_spiegel_dwarf_reader_hxx__ 1

#include "np/spiegel/common.hxx"

namespace np {
namespace spiegel {
namespace dwarf {

class reader_t
{
public:
    reader_t()
     :  p_(0), end_(0), base_(0) {}

    reader_t(const void *base, size_t len)
     :  p_((unsigned char *)base),
        end_(((unsigned char *)base) + len),
        base_((unsigned char *)base)
    {}

    reader_t initial_subset(size_t len) const
    {
	size_t remain = (end_ - p_);
	if (len > remain)
	    len = remain;
	return reader_t((void *)p_, len);
    }

    unsigned long get_offset() const
    {
	return p_ - base_;
    }
    unsigned long get_remains() const
    {
	return end_ - p_;
    }

    bool seek(size_t n)
    {
	if (base_ + n > end_)
	    return false;
	p_ = base_ + n;
	return true;
    }

    bool skip(size_t n)
    {
	if (p_ + n > end_)
	    return false;
	p_ += n;
	return true;
    }

    bool read_u32(uint32_t &v)
    {
	if (p_ + 4 > end_)
	    return false;
	v = ((uint32_t)p_[0]) |
	    ((uint32_t)p_[1] << 8) |
	    ((uint32_t)p_[2] << 16) |
	    ((uint32_t)p_[3] << 24);
	p_ += 4;
	return true;
    }

    bool read_u64(uint64_t &v)
    {
	if (p_ + 8 > end_)
	    return false;
	v = ((uint64_t)p_[0]) |
	    ((uint64_t)p_[1] << 8) |
	    ((uint64_t)p_[2] << 16) |
	    ((uint64_t)p_[3] << 24) |
	    ((uint64_t)p_[4] << 32) |
	    ((uint64_t)p_[5] << 40) |
	    ((uint64_t)p_[6] << 48) |
	    ((uint64_t)p_[7] << 56);
	p_ += 8;
	return true;
    }

    bool read_addr(np::spiegel::addr_t &v)
    {
#if _NP_ADDRSIZE == 4
	return read_u32(v);
#elif _NP_ADDRSIZE == 8
	return read_u64(v);
#else
#error "Unknown address size"
#endif
    }

    bool read_uleb128(uint32_t &v)
    {
	const unsigned char *pp = p_;
	uint32_t vv = 0;
	unsigned shift = 0;
	do
	{
	    if (pp == end_)
		return false;
	    vv |= ((*pp) & 0x7f) << shift;
	    shift += 7;
	} while ((*pp++) & 0x80);
	p_ = pp;
	v = vv;
	return true;
    }

    bool read_sleb128(int32_t &v)
    {
	const unsigned char *pp = p_;
	uint32_t vv = 0;
	unsigned shift = 0;

	do
	{
	    if (pp == end_)
		return false;
	    vv |= ((*pp) & 0x7f) << shift;
	    shift += 7;
	} while ((*pp++) & 0x80);

	// sign extend the result, from the last encoded bit
	if (pp[-1] & 0x40)
	    v = vv | (~0U << shift);
	else
	    v = vv;
	p_ = pp;
	return true;
    }

    bool read_u16(uint16_t &v)
    {
	if (p_ + 2 > end_)
	    return false;
	v = ((uint16_t)p_[0]) |
	    ((uint16_t)p_[1] << 8);
	p_ += 2;
	return true;
    }

    bool read_u8(uint8_t &v)
    {
	if (p_ >= end_)
	    return false;
	v = *p_++;
	return true;
    }

    bool read_string(const char *&v)
    {
	const unsigned char *e =
	    (const unsigned char *)memchr(p_, '\0', (end_ - p_));
	if (!e)
	    return false;
	v = (const char *)p_;
	p_ = e + 1;
	return true;
    }

    bool read_bytes(const unsigned char *&v, size_t len)
    {
	const unsigned char *e = p_ + len;
	if (e >= end_)
	    return false;
	v = (const unsigned char *)p_;
	p_ = e;
	return true;
    }

private:
    const unsigned char *p_;
    const unsigned char *end_;
    const unsigned char *base_;
};

// close namespaces
}; }; };

#endif // __np_spiegel_dwarf_reader_hxx__
<commit_msg>Whitespace fixes in reader.hxx<commit_after>/*
 * Copyright 2011-2012 Gregory Banks
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef __np_spiegel_dwarf_reader_hxx__
#define __np_spiegel_dwarf_reader_hxx__ 1

#include "np/spiegel/common.hxx"

namespace np {
namespace spiegel {
namespace dwarf {

class reader_t
{
public:
    reader_t()
     :  p_(0), end_(0), base_(0) {}

    reader_t(const void *base, size_t len)
     :  p_((unsigned char *)base),
	end_(((unsigned char *)base) + len),
	base_((unsigned char *)base)
    {}

    reader_t initial_subset(size_t len) const
    {
	size_t remain = (end_ - p_);
	if (len > remain)
	    len = remain;
	return reader_t((void *)p_, len);
    }

    unsigned long get_offset() const
    {
	return p_ - base_;
    }
    unsigned long get_remains() const
    {
	return end_ - p_;
    }

    bool seek(size_t n)
    {
	if (base_ + n > end_)
	    return false;
	p_ = base_ + n;
	return true;
    }

    bool skip(size_t n)
    {
	if (p_ + n > end_)
	    return false;
	p_ += n;
	return true;
    }

    bool read_u32(uint32_t &v)
    {
	if (p_ + 4 > end_)
	    return false;
	v = ((uint32_t)p_[0]) |
	    ((uint32_t)p_[1] << 8) |
	    ((uint32_t)p_[2] << 16) |
	    ((uint32_t)p_[3] << 24);
	p_ += 4;
	return true;
    }

    bool read_u64(uint64_t &v)
    {
	if (p_ + 8 > end_)
	    return false;
	v = ((uint64_t)p_[0]) |
	    ((uint64_t)p_[1] << 8) |
	    ((uint64_t)p_[2] << 16) |
	    ((uint64_t)p_[3] << 24) |
	    ((uint64_t)p_[4] << 32) |
	    ((uint64_t)p_[5] << 40) |
	    ((uint64_t)p_[6] << 48) |
	    ((uint64_t)p_[7] << 56);
	p_ += 8;
	return true;
    }

    bool read_addr(np::spiegel::addr_t &v)
    {
#if _NP_ADDRSIZE == 4
	return read_u32(v);
#elif _NP_ADDRSIZE == 8
	return read_u64(v);
#else
#error "Unknown address size"
#endif
    }

    bool read_uleb128(uint32_t &v)
    {
	const unsigned char *pp = p_;
	uint32_t vv = 0;
	unsigned shift = 0;
	do
	{
	    if (pp == end_)
		return false;
	    vv |= ((*pp) & 0x7f) << shift;
	    shift += 7;
	} while ((*pp++) & 0x80);
	p_ = pp;
	v = vv;
	return true;
    }

    bool read_sleb128(int32_t &v)
    {
	const unsigned char *pp = p_;
	uint32_t vv = 0;
	unsigned shift = 0;

	do
	{
	    if (pp == end_)
		return false;
	    vv |= ((*pp) & 0x7f) << shift;
	    shift += 7;
	} while ((*pp++) & 0x80);

	// sign extend the result, from the last encoded bit
	if (pp[-1] & 0x40)
	    v = vv | (~0U << shift);
	else
	    v = vv;
	p_ = pp;
	return true;
    }

    bool read_u16(uint16_t &v)
    {
	if (p_ + 2 > end_)
	    return false;
	v = ((uint16_t)p_[0]) |
	    ((uint16_t)p_[1] << 8);
	p_ += 2;
	return true;
    }

    bool read_u8(uint8_t &v)
    {
	if (p_ >= end_)
	    return false;
	v = *p_++;
	return true;
    }

    bool read_string(const char *&v)
    {
	const unsigned char *e =
	    (const unsigned char *)memchr(p_, '\0', (end_ - p_));
	if (!e)
	    return false;
	v = (const char *)p_;
	p_ = e + 1;
	return true;
    }

    bool read_bytes(const unsigned char *&v, size_t len)
    {
	const unsigned char *e = p_ + len;
	if (e >= end_)
	    return false;
	v = (const unsigned char *)p_;
	p_ = e;
	return true;
    }

private:
    const unsigned char *p_;
    const unsigned char *end_;
    const unsigned char *base_;
};

// close namespaces
}; }; };

#endif // __np_spiegel_dwarf_reader_hxx__
<|endoftext|>


<commit_before>#include <cybozu/benchmark.hpp>
//cybozu::CpuClock g_clk;
#include <stdio.h>
#include <mcl/bitint.hpp>
#include <cybozu/test.hpp>
#include <cybozu/xorshift.hpp>
#include <gmpxx.h>
#include <iostream>

#define PUT(x) std::cout << #x "=" << (x) << std::endl;

using namespace mcl::bint;
typedef mcl::Unit Unit;

template<class RG>
void setRand(Unit *x, size_t n, RG& rg)
{
	for (size_t i = 0; i < n; i++) {
		x[i] = (Unit)rg.get64();
	}
}

void setArray(mpz_class& z, const Unit *buf, size_t n)
{
	mpz_import(z.get_mpz_t(), n, -1, sizeof(*buf), 0, 0, buf);
}
void divmod(mpz_class& q, mpz_class& r, const mpz_class& x, const mpz_class& y)
{
	mpz_divmod(q.get_mpz_t(), r.get_mpz_t(), x.get_mpz_t(), y.get_mpz_t());
}

CYBOZU_TEST_AUTO(cmpT)
{
	const Unit x[] = { 1, 2, 4, 5 };
	const Unit y[] = { 1, 2, 3, 8 };

	CYBOZU_TEST_ASSERT(!cmpEqT<3>(x, y));
	CYBOZU_TEST_ASSERT(cmpEqT<3>(x, x));
	CYBOZU_TEST_ASSERT(cmpEqT<2>(x, y));

	CYBOZU_TEST_ASSERT(cmpGeT<3>(x, y));
	CYBOZU_TEST_ASSERT(cmpGeT<3>(x, x));
	CYBOZU_TEST_ASSERT(!cmpGeT<3>(y, x));
	CYBOZU_TEST_ASSERT(cmpGeT<2>(x, y));
	CYBOZU_TEST_ASSERT(!cmpGeT<4>(x, y));

	CYBOZU_TEST_ASSERT(cmpGtT<3>(x, y));
	CYBOZU_TEST_ASSERT(!cmpGtT<3>(x, x));
	CYBOZU_TEST_ASSERT(!cmpGtT<3>(y, x));

	CYBOZU_TEST_ASSERT(!cmpLeT<3>(x, y));
	CYBOZU_TEST_ASSERT(cmpLeT<3>(x, x));
	CYBOZU_TEST_ASSERT(cmpLeT<3>(y, x));
	CYBOZU_TEST_ASSERT(cmpLeT<2>(x, x));
	CYBOZU_TEST_ASSERT(cmpLeT<4>(x, y));
}

CYBOZU_TEST_AUTO(addT)
{
	const Unit x[] = { 9, 2, 3 };
	const Unit y[] = { Unit(-1), 5, 4 };
	const Unit ok[] = { 8, 8, 7 };
	Unit z[3], CF;
	z[0] = 9;
	z[1] = 10;
	CF = addT<1>(z, x, y);
	CYBOZU_TEST_EQUAL(z[0], ok[0]);
	CYBOZU_TEST_EQUAL(CF, 1);
	CYBOZU_TEST_EQUAL(z[1], 10); // not changed

	CF = addT<1>(z, x + 1, y + 1);
	CYBOZU_TEST_EQUAL(z[0], x[1] + y[1]);
	CYBOZU_TEST_EQUAL(CF, 0);
	CYBOZU_TEST_EQUAL(z[1], 10); // not changed

	CF = addT<3>(z, x, y);
	CYBOZU_TEST_EQUAL_ARRAY(z, ok, 3);
	CYBOZU_TEST_EQUAL(CF, 0);
}

CYBOZU_TEST_AUTO(subT)
{
	const size_t N = 4;
	Unit x[N], y[N], z[N], x2[N];
	cybozu::XorShift rg;
	mpz_class mx, my, mz;
	for (int i = 0; i < 100; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		Unit CF = addT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(my, y, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx + my, mz + (mpz_class(CF) << (sizeof(x) * 8)));
		Unit CF2 = subT<N>(x2, z, y);
		CYBOZU_TEST_EQUAL_ARRAY(x, x2, N);
		CYBOZU_TEST_EQUAL(CF, CF2);

	}
}

CYBOZU_TEST_AUTO(mulUnitT)
{
	const size_t N = 4;
	Unit x[N], z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		Unit u = mulUnitT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx * y, mz + (mpz_class(u) << (sizeof(x) * 8)));
	}
}

CYBOZU_TEST_AUTO(mulUnitAddT)
{
	const size_t N = 4;
	Unit x[N], z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz, mt;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(z, N, rg);
		setArray(mx, x, N);
		setArray(mz, z, N);
		setRand(&y, 1, rg);
		Unit u = mulUnitAddT<N>(z, x, y);
		setArray(mt, z, N);
		CYBOZU_TEST_EQUAL(mz + mx * y, mt + (mpz_class(u) << (sizeof(x) * 8)));
	}
}

CYBOZU_TEST_AUTO(mulT)
{
	const size_t N = 4;
	Unit x[N], y[N], z[N * 2];
	cybozu::XorShift rg;
	mpz_class mx, my, mz;
	for (int i = 0; i < 100; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		mulT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(my, y, N);
		setArray(mz, z, N * 2);
		CYBOZU_TEST_EQUAL(mx * my, mz);
	}
}

CYBOZU_TEST_AUTO(shlT)
{
	const size_t N = 4;
	Unit x[N], z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		y &= sizeof(Unit) * 8 - 1;
		if (y == 0) y = 1;
		Unit u = shlT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx << y, mz + (mpz_class(u) << (sizeof(x) * 8)));
	}
}

CYBOZU_TEST_AUTO(shrT)
{
	const size_t N = 4;
	Unit x[N], z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		y &= sizeof(Unit) * 8 - 1;
		if (y == 0) y = 1;
		shrT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx >> y, mz);
	}
}

CYBOZU_TEST_AUTO(addUnit)
{
	const size_t N = 2;
	const struct {
		Unit x[N];
		Unit y;
	} tbl[] = {
		{ { 1, 2 }, 3 },
		{ { 1, Unit(-1) }, 5 },
		{ { Unit(-1), Unit(-2) }, 7 },
	};
	mpz_class mx, mz;
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		const Unit *x = tbl[i].x;
		Unit y = tbl[i].y;
		Unit z[N];
		Unit u = addUnit(z, x, N, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx + y, mz + (mpz_class(u) << (sizeof(Unit) * N * 8)));
		Unit x2[N];
		Unit u2 = subUnit(x2, z, N, y);
		CYBOZU_TEST_EQUAL_ARRAY(x2, x, N);
		CYBOZU_TEST_EQUAL(u, u2);
	}
}

CYBOZU_TEST_AUTO(divUnit)
{
	const size_t N = 4;
	Unit x[N], q[N];
	cybozu::XorShift rg;
	mpz_class mx, mq;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		if (y == 0) y = 1;
		Unit r = divUnit(q, x, N, y);
		setArray(mx, x, N);
		setArray(mq, q, N);
		CYBOZU_TEST_EQUAL(mx, mq * y + r);
		Unit r2 = modUnit(x, N, y);
		CYBOZU_TEST_EQUAL(r, r2);
	}
}

template<size_t xN, class RG, class F>
void setRandAndTest(RG& rg, const F& f, Unit *q, size_t qn, const Unit *y)
{
	Unit x[xN];
	setRand(x, xN, rg);
	f(q, qn, x, xN, y);
}

CYBOZU_TEST_AUTO(divFullBitT)
{
	const size_t xN = 8;
	const size_t yN = 4;
	const size_t qN = xN - yN + 1;
	Unit x[xN], y[yN], q[qN];
	cybozu::XorShift rg;
	mpz_class mx, my, mq, mr;
	for (int i = 0; i < 100; i++) {
		setRand(x, xN, rg);
		setRand(y, yN, rg);
		y[yN - 1] |= Unit(1) << (sizeof(Unit) * 8 - 1); // full bit
		setArray(mx, x, xN);
		setArray(my, y, yN);
		size_t rn = divFullBitT<yN>(q, qN, x, xN, y);
		setArray(mq, q, qN);
		setArray(mr, x, rn);
		CYBOZU_TEST_EQUAL(mq, mx / my);
		CYBOZU_TEST_EQUAL(mr, mx % my);
	}
#ifdef NDEBUG
//g_clk.clear();
	const int C = 1000;
	CYBOZU_BENCH_C("gmp ", C, divmod, mq, mr, mx, my);
	CYBOZU_BENCH_C("full", C, setRandAndTest<xN>, rg, divFullBitT<yN>, q, qN, y);
//printf("count=%d\n", g_clk.getCount());
//g_clk.put();
#endif
}

CYBOZU_TEST_AUTO(divSmallT)
{
	const size_t N = 4;
	Unit x[N], y[N], q;
	cybozu::XorShift rg;
	mpz_class mx, my, mr;
	for (int i = 0; i < 100; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		y[N - 1] |= Unit(1) << (sizeof(Unit) * 8 / 2); // at least half
		setArray(mx, x, N);
		setArray(my, y, N);
		bool done = divSmallT<N>(&q, 1, x, N, y);
		CYBOZU_TEST_ASSERT(done);
		setArray(mr, x, N);
		CYBOZU_TEST_EQUAL(q * my + mr, mx);
	}
#ifdef NDEBUG
	mpz_class mq;
	const int C = 1000;
	CYBOZU_BENCH_C("gmp  ", C, divmod, mq, mr, mx, my);
	CYBOZU_BENCH_C("small", C, setRandAndTest<N>, rg, divSmallT<N>, &q, 1, y);
#endif
}

CYBOZU_TEST_AUTO(divT)
{
	const size_t xN = 8;
	const size_t yN = 4;
	const size_t qN = xN - yN + 1;
	Unit x[xN], y[yN], q[qN];
	cybozu::XorShift rg;
	mpz_class mx, my, mq, mr;
	for (int i = 0; i < 100; i++) {
		setRand(x, xN, rg);
		setRand(y, yN, rg);
		setArray(mx, x, xN);
		setArray(my, y, yN);
		size_t xn = divT<yN>(q, qN, x, xN, y);
		setArray(mq, q, qN);
		setArray(mr, x, xn);
		CYBOZU_TEST_EQUAL(mq * my + mr, mx);
	}
#ifdef NDEBUG
	const int C = 1000;
	CYBOZU_BENCH_C("gmp", C, divmod, mq, mr, mx, my);
	CYBOZU_BENCH_C("div", C, setRandAndTest<xN>, rg, divT<yN>, q, qN, y);
#endif
}
<commit_msg>add bench of mulUnitT<commit_after>#include <cybozu/benchmark.hpp>
//cybozu::CpuClock g_clk;
#include <stdio.h>
#include <mcl/bitint.hpp>
#include <cybozu/test.hpp>
#include <cybozu/xorshift.hpp>
#include <gmpxx.h>
#include <iostream>

#define PUT(x) std::cout << #x "=" << (x) << std::endl;

using namespace mcl::bint;
typedef mcl::Unit Unit;

template<class RG>
void setRand(Unit *x, size_t n, RG& rg)
{
	for (size_t i = 0; i < n; i++) {
		x[i] = (Unit)rg.get64();
	}
}

void setArray(mpz_class& z, const Unit *buf, size_t n)
{
	mpz_import(z.get_mpz_t(), n, -1, sizeof(*buf), 0, 0, buf);
}
void divmod(mpz_class& q, mpz_class& r, const mpz_class& x, const mpz_class& y)
{
	mpz_divmod(q.get_mpz_t(), r.get_mpz_t(), x.get_mpz_t(), y.get_mpz_t());
}

CYBOZU_TEST_AUTO(cmpT)
{
	const Unit x[] = { 1, 2, 4, 5 };
	const Unit y[] = { 1, 2, 3, 8 };

	CYBOZU_TEST_ASSERT(!cmpEqT<3>(x, y));
	CYBOZU_TEST_ASSERT(cmpEqT<3>(x, x));
	CYBOZU_TEST_ASSERT(cmpEqT<2>(x, y));

	CYBOZU_TEST_ASSERT(cmpGeT<3>(x, y));
	CYBOZU_TEST_ASSERT(cmpGeT<3>(x, x));
	CYBOZU_TEST_ASSERT(!cmpGeT<3>(y, x));
	CYBOZU_TEST_ASSERT(cmpGeT<2>(x, y));
	CYBOZU_TEST_ASSERT(!cmpGeT<4>(x, y));

	CYBOZU_TEST_ASSERT(cmpGtT<3>(x, y));
	CYBOZU_TEST_ASSERT(!cmpGtT<3>(x, x));
	CYBOZU_TEST_ASSERT(!cmpGtT<3>(y, x));

	CYBOZU_TEST_ASSERT(!cmpLeT<3>(x, y));
	CYBOZU_TEST_ASSERT(cmpLeT<3>(x, x));
	CYBOZU_TEST_ASSERT(cmpLeT<3>(y, x));
	CYBOZU_TEST_ASSERT(cmpLeT<2>(x, x));
	CYBOZU_TEST_ASSERT(cmpLeT<4>(x, y));
}

CYBOZU_TEST_AUTO(addT)
{
	const Unit x[] = { 9, 2, 3 };
	const Unit y[] = { Unit(-1), 5, 4 };
	const Unit ok[] = { 8, 8, 7 };
	Unit z[3], CF;
	z[0] = 9;
	z[1] = 10;
	CF = addT<1>(z, x, y);
	CYBOZU_TEST_EQUAL(z[0], ok[0]);
	CYBOZU_TEST_EQUAL(CF, 1);
	CYBOZU_TEST_EQUAL(z[1], 10); // not changed

	CF = addT<1>(z, x + 1, y + 1);
	CYBOZU_TEST_EQUAL(z[0], x[1] + y[1]);
	CYBOZU_TEST_EQUAL(CF, 0);
	CYBOZU_TEST_EQUAL(z[1], 10); // not changed

	CF = addT<3>(z, x, y);
	CYBOZU_TEST_EQUAL_ARRAY(z, ok, 3);
	CYBOZU_TEST_EQUAL(CF, 0);
}

CYBOZU_TEST_AUTO(subT)
{
	const size_t N = 4;
	Unit x[N], y[N], z[N], x2[N];
	cybozu::XorShift rg;
	mpz_class mx, my, mz;
	for (int i = 0; i < 100; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		Unit CF = addT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(my, y, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx + my, mz + (mpz_class(CF) << (sizeof(x) * 8)));
		Unit CF2 = subT<N>(x2, z, y);
		CYBOZU_TEST_EQUAL_ARRAY(x, x2, N);
		CYBOZU_TEST_EQUAL(CF, CF2);

	}
}

CYBOZU_TEST_AUTO(mulUnitT)
{
	const size_t N = 4;
	Unit x[N], y, z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz;
	for (int i = 0; i < 100; i++) {
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		Unit u = mulUnitT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx * y, mz + (mpz_class(u) << (sizeof(x) * 8)));
	}
#ifdef NDEBUG
	const int C = 1000;
	CYBOZU_BENCH_C("mulUnit", C, mulUnitT<N>, z, x, y);
#endif
}

CYBOZU_TEST_AUTO(mulUnitAddT)
{
	const size_t N = 4;
	Unit x[N], z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz, mt;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(z, N, rg);
		setArray(mx, x, N);
		setArray(mz, z, N);
		setRand(&y, 1, rg);
		Unit u = mulUnitAddT<N>(z, x, y);
		setArray(mt, z, N);
		CYBOZU_TEST_EQUAL(mz + mx * y, mt + (mpz_class(u) << (sizeof(x) * 8)));
	}
}

CYBOZU_TEST_AUTO(mulT)
{
	const size_t N = 4;
	Unit x[N], y[N], z[N * 2];
	cybozu::XorShift rg;
	mpz_class mx, my, mz;
	for (int i = 0; i < 100; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		mulT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(my, y, N);
		setArray(mz, z, N * 2);
		CYBOZU_TEST_EQUAL(mx * my, mz);
	}
}

CYBOZU_TEST_AUTO(shlT)
{
	const size_t N = 4;
	Unit x[N], z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		y &= sizeof(Unit) * 8 - 1;
		if (y == 0) y = 1;
		Unit u = shlT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx << y, mz + (mpz_class(u) << (sizeof(x) * 8)));
	}
}

CYBOZU_TEST_AUTO(shrT)
{
	const size_t N = 4;
	Unit x[N], z[N];
	cybozu::XorShift rg;
	mpz_class mx, mz;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		y &= sizeof(Unit) * 8 - 1;
		if (y == 0) y = 1;
		shrT<N>(z, x, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx >> y, mz);
	}
}

CYBOZU_TEST_AUTO(addUnit)
{
	const size_t N = 2;
	const struct {
		Unit x[N];
		Unit y;
	} tbl[] = {
		{ { 1, 2 }, 3 },
		{ { 1, Unit(-1) }, 5 },
		{ { Unit(-1), Unit(-2) }, 7 },
	};
	mpz_class mx, mz;
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		const Unit *x = tbl[i].x;
		Unit y = tbl[i].y;
		Unit z[N];
		Unit u = addUnit(z, x, N, y);
		setArray(mx, x, N);
		setArray(mz, z, N);
		CYBOZU_TEST_EQUAL(mx + y, mz + (mpz_class(u) << (sizeof(Unit) * N * 8)));
		Unit x2[N];
		Unit u2 = subUnit(x2, z, N, y);
		CYBOZU_TEST_EQUAL_ARRAY(x2, x, N);
		CYBOZU_TEST_EQUAL(u, u2);
	}
}

CYBOZU_TEST_AUTO(divUnit)
{
	const size_t N = 4;
	Unit x[N], q[N];
	cybozu::XorShift rg;
	mpz_class mx, mq;
	for (int i = 0; i < 100; i++) {
		Unit y;
		setRand(x, N, rg);
		setRand(&y, 1, rg);
		if (y == 0) y = 1;
		Unit r = divUnit(q, x, N, y);
		setArray(mx, x, N);
		setArray(mq, q, N);
		CYBOZU_TEST_EQUAL(mx, mq * y + r);
		Unit r2 = modUnit(x, N, y);
		CYBOZU_TEST_EQUAL(r, r2);
	}
}

template<size_t xN, class RG, class F>
void setRandAndTest(RG& rg, const F& f, Unit *q, size_t qn, const Unit *y)
{
	Unit x[xN];
	setRand(x, xN, rg);
	f(q, qn, x, xN, y);
}

CYBOZU_TEST_AUTO(divFullBitT)
{
	const size_t xN = 8;
	const size_t yN = 4;
	const size_t qN = xN - yN + 1;
	Unit x[xN], y[yN], q[qN];
	cybozu::XorShift rg;
	mpz_class mx, my, mq, mr;
	for (int i = 0; i < 100; i++) {
		setRand(x, xN, rg);
		setRand(y, yN, rg);
		y[yN - 1] |= Unit(1) << (sizeof(Unit) * 8 - 1); // full bit
		setArray(mx, x, xN);
		setArray(my, y, yN);
		size_t rn = divFullBitT<yN>(q, qN, x, xN, y);
		setArray(mq, q, qN);
		setArray(mr, x, rn);
		CYBOZU_TEST_EQUAL(mq, mx / my);
		CYBOZU_TEST_EQUAL(mr, mx % my);
	}
#ifdef NDEBUG
//g_clk.clear();
	const int C = 1000;
	CYBOZU_BENCH_C("gmp ", C, divmod, mq, mr, mx, my);
	CYBOZU_BENCH_C("full", C, setRandAndTest<xN>, rg, divFullBitT<yN>, q, qN, y);
//printf("count=%d\n", g_clk.getCount());
//g_clk.put();
#endif
}

CYBOZU_TEST_AUTO(divSmallT)
{
	const size_t N = 4;
	Unit x[N], y[N], q;
	cybozu::XorShift rg;
	mpz_class mx, my, mr;
	for (int i = 0; i < 100; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		y[N - 1] |= Unit(1) << (sizeof(Unit) * 8 / 2); // at least half
		setArray(mx, x, N);
		setArray(my, y, N);
		bool done = divSmallT<N>(&q, 1, x, N, y);
		CYBOZU_TEST_ASSERT(done);
		setArray(mr, x, N);
		CYBOZU_TEST_EQUAL(q * my + mr, mx);
	}
#ifdef NDEBUG
	mpz_class mq;
	const int C = 1000;
	CYBOZU_BENCH_C("gmp  ", C, divmod, mq, mr, mx, my);
	CYBOZU_BENCH_C("small", C, setRandAndTest<N>, rg, divSmallT<N>, &q, 1, y);
#endif
}

CYBOZU_TEST_AUTO(divT)
{
	const size_t xN = 8;
	const size_t yN = 4;
	const size_t qN = xN - yN + 1;
	Unit x[xN], y[yN], q[qN];
	cybozu::XorShift rg;
	mpz_class mx, my, mq, mr;
	for (int i = 0; i < 100; i++) {
		setRand(x, xN, rg);
		setRand(y, yN, rg);
		setArray(mx, x, xN);
		setArray(my, y, yN);
		size_t xn = divT<yN>(q, qN, x, xN, y);
		setArray(mq, q, qN);
		setArray(mr, x, xn);
		CYBOZU_TEST_EQUAL(mq * my + mr, mx);
	}
#ifdef NDEBUG
	const int C = 1000;
	CYBOZU_BENCH_C("gmp", C, divmod, mq, mr, mx, my);
	CYBOZU_BENCH_C("div", C, setRandAndTest<xN>, rg, divT<yN>, q, qN, y);
#endif
}
<|endoftext|>


<commit_before><commit_msg>Fixed integrate_nearest normalization - removes incorrect red pixels from incomplete samples<commit_after><|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "dragtool.h"

#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"
#include "itemutilfunctions.h"
#include <customdraganddrop.h>
#include <metainfo.h>
#include <rewritingexception.h>

#include "resizehandleitem.h"

#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QtDebug>
#include <QMessageBox>
#include <QTimer>

namespace QmlDesigner {

namespace Internal {
void TimerHandler::clearMoveDelay()
{
    m_dragTool->clearMoveDelay();
}

}

DragTool::DragTool(FormEditorView *editorView)
    : AbstractFormEditorTool(editorView),
    m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView),
    m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
    m_timerHandler(new Internal::TimerHandler(this)),
    m_blockMove(false),
    m_Aborted(false)
{
}

DragTool::~DragTool()
{

}

void DragTool::clear()
{
    m_moveManipulator.clear();
    m_selectionIndicator.clear();
    m_movingItem.clear();
}

void DragTool::mousePressEvent(const QList<QGraphicsItem*> &,
                                            QGraphicsSceneMouseEvent *)
{

}

void DragTool::mouseMoveEvent(const QList<QGraphicsItem*> &,
                                           QGraphicsSceneMouseEvent *)
{

}

void DragTool::hoverMoveEvent(const QList<QGraphicsItem*> &,
                        QGraphicsSceneMouseEvent * /*event*/)
{

}

void DragTool::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape) {
        abort();
        event->accept();
        view()->changeToSelectionTool();
    }
}

void DragTool::keyReleaseEvent(QKeyEvent *)
{

}

void DragTool::mouseReleaseEvent(const QList<QGraphicsItem*> &/*itemList*/,
                                 QGraphicsSceneMouseEvent *)
{

}

void DragTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> & /*itemList*/,
                                              QGraphicsSceneMouseEvent * /*event*/)
{

}

void DragTool::itemsAboutToRemoved(const QList<FormEditorItem*> & /* removedItemList */)
{

}

void DragTool::selectedItemsChanged(const QList<FormEditorItem*> &)
{

}

void DragTool::updateMoveManipulator()
{
    if (m_moveManipulator.isActive())
        return;
}

void DragTool::beginWithPoint(const QPointF &beginPoint)
{
    m_movingItem = scene()->itemForQmlItemNode(m_dragNode);

    m_moveManipulator.setItem(m_movingItem.data());
    m_moveManipulator.begin(beginPoint);
}

void DragTool::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, QmlItemNode parentNode, QPointF scenePos)
{
    MetaInfo metaInfo = MetaInfo::global();

    FormEditorItem *parentItem = scene()->itemForQmlItemNode(parentNode);
    QPointF pos = parentItem->mapFromScene(scenePos);

    m_dragNode = view()->createQmlItemNode(itemLibraryEntry, pos, parentNode);

    Q_ASSERT(m_dragNode.modelNode().isValid());

    QList<QmlItemNode> nodeList;
    nodeList.append(m_dragNode);
    m_selectionIndicator.setItems(scene()->itemsForQmlItemNodes(nodeList));
}

void DragTool::createQmlItemNodeFromImage(const QString &imageName, QmlItemNode parentNode, QPointF scenePos)
{
    if (!parentNode.isValid())
        return;

    MetaInfo metaInfo = MetaInfo::global();

    FormEditorItem *parentItem = scene()->itemForQmlItemNode(parentNode);
    QPointF pos = parentItem->mapFromScene(scenePos);

    m_dragNode = view()->createQmlItemNodeFromImage(imageName, pos, parentNode);

    QList<QmlItemNode> nodeList;
    nodeList.append(m_dragNode);
    m_selectionIndicator.setItems(scene()->itemsForQmlItemNodes(nodeList));
}

FormEditorItem* DragTool::calculateContainer(const QPointF &point, FormEditorItem * currentItem)
{
    QList<QGraphicsItem *> list = scene()->items(point);
    foreach (QGraphicsItem *item, list) {
         FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
         if (formEditorItem && formEditorItem != currentItem && formEditorItem->isContainer())
             return formEditorItem;
    }

    if (scene()->rootFormEditorItem())
        return scene()->rootFormEditorItem();
    return 0;
}

void DragTool::formEditorItemsChanged(const QList<FormEditorItem*> & itemList)
{
    if (m_movingItem && itemList.contains(m_movingItem.data())) {
        QList<FormEditorItem*> updateItemList;
        updateItemList.append(m_movingItem.data());
        m_selectionIndicator.updateItems(updateItemList);
    }
}

void DragTool::instancesCompleted(const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem* item, itemList)
        if (item->qmlItemNode() == m_dragNode)
            clearMoveDelay();
    QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::hide();
}

void DragTool::instancesParentChanged(const QList<FormEditorItem *> &itemList)
{
    m_moveManipulator.synchronizeInstanceParent(itemList);
}

void DragTool::clearMoveDelay()
{
    if (!m_blockMove)
        return;
    m_blockMove = false;
    if  (m_dragNode.isValid())
        beginWithPoint(m_startPoint);
}

void DragTool::abort()
{
    if (m_Aborted)
        return;

    m_Aborted = true;

    if (m_dragNode.isValid())
        m_dragNode.destroy();

    QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::hide();

    if (m_rewriterTransaction.isValid())
        m_rewriterTransaction.commit();

}

void DragTool::dropEvent(QGraphicsSceneDragDropEvent * event)
{
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
       event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        event->accept();
        end(event->scenePos());
        //Q_ASSERT(m_token.isValid());
        try {
            m_rewriterTransaction.commit();
        } catch (RewritingException &e) {
            QMessageBox::warning(0, "Error", e.description());
        }
        if (m_dragNode.isValid()) {
            QList<QmlItemNode> nodeList;
            nodeList.append(m_dragNode);
            view()->setSelectedQmlItemNodes(nodeList);
        }
        m_dragNode = ModelNode();
        view()->changeToSelectionTool();
    }
}

static ItemLibraryEntry itemLibraryEntryFromData(const QByteArray &data)
{
    QDataStream stream(data);

    ItemLibraryEntry itemLibraryEntry;
    stream >> itemLibraryEntry;

    return itemLibraryEntry;
}

void DragTool::dragEnterEvent(QGraphicsSceneDragDropEvent * event)
{
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
        event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        QList<Import> importToBeAddedList;
        m_blockMove = false;
        if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo")) {
            view()->widget()->setFocus();
            m_Aborted = false;
            Q_ASSERT(!event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo").isEmpty());
            ItemLibraryEntry itemLibraryEntry = itemLibraryEntryFromData(event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo"));
            if (!itemLibraryEntry.requiredImport().isEmpty()) {
                const QString newImportUrl = itemLibraryEntry.requiredImport();
                const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));
                Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

                if (!view()->model()->hasImport(newImport, true, true)) {
                    importToBeAddedList.append(newImport);
                }

            }
        }

        view()->model()->changeImports(importToBeAddedList, QList<Import>());

        if (!m_rewriterTransaction.isValid()) {
            view()->clearSelectedModelNodes();
            m_rewriterTransaction = view()->beginRewriterTransaction();
        }
    }
}

void DragTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * event)
{
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
       event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        event->accept();
        if (m_dragNode.isValid())
            m_dragNode.destroy();
        end(event->scenePos());

        try {
            m_rewriterTransaction.commit();
        } catch (RewritingException &e) {
            QMessageBox::warning(0, "Error", e.description());
        }

        QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::show();
        QList<QmlItemNode> nodeList;
        view()->setSelectedQmlItemNodes(nodeList);
        view()->changeToSelectionTool();
    }
}

void DragTool::dragMoveEvent(QGraphicsSceneDragDropEvent * event)
{
    if (m_blockMove)
        return;

    if (m_Aborted) {
        event->ignore();
        return;
    }
    if (QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::isAnimated())
        return;
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
       event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        event->accept();
        QPointF scenePos = event->scenePos();
        if  (m_dragNode.isValid()) {

            FormEditorItem *parentItem = calculateContainer(event->scenePos() + QPoint(2, 2));
            if (!parentItem) {      //if there is no parent any more - the use left the scene
                end(event->scenePos());
                QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::show();
                m_dragNode.destroy(); //delete the node then
                return;
            }
            //move
            move(event->scenePos());
        } else {
            //create new node  if container
            if (m_dragNode.modelNode().isValid())
                return;

            FormEditorItem *parentItem = calculateContainer(scenePos);
            if (!parentItem)
                return;
            QmlItemNode parentNode;
            if (parentItem)
                parentNode = parentItem->qmlItemNode();

            if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo")) {
                Q_ASSERT(!event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo").isEmpty());
                ItemLibraryEntry itemLibraryEntry = itemLibraryEntryFromData(event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo"));
                createQmlItemNode(itemLibraryEntry, parentNode, event->scenePos());
            } else if (event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
                Q_ASSERT(!event->mimeData()->data("application/vnd.bauhaus.libraryresource").isEmpty());
                QString imageName = QString::fromLatin1((event->mimeData()->data("application/vnd.bauhaus.libraryresource")));
                createQmlItemNodeFromImage(imageName, parentNode, event->scenePos());
            } else Q_ASSERT(false);
            m_blockMove = true;
            m_startPoint = event->scenePos();
            QTimer::singleShot(1000, m_timerHandler.data(), SLOT(clearMoveDelay()));
        }
    }

    if (event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
    }
}

void  DragTool::end(QPointF scenePos)
{
    m_moveManipulator.end(scenePos);
    clear();
}

void  DragTool::move(QPointF scenePos)
{
    if (!m_movingItem)
        return;

    FormEditorItem *containerItem = calculateContainer(scenePos - QPoint(2, 2), m_movingItem.data());
    if (containerItem &&
       containerItem != m_movingItem->parentItem()) {

        m_moveManipulator.reparentTo(containerItem);
    }

    //MoveManipulator::Snapping useSnapping = MoveManipulator::NoSnapping;
    MoveManipulator::Snapping useSnapping = MoveManipulator::UseSnapping;
   /* if (event->modifiers().testFlag(Qt::ControlModifier) != view()->isSnapButtonChecked())
        useSnapping = MoveManipulator::UseSnapping;*/

    m_moveManipulator.update(scenePos, useSnapping, MoveManipulator::UseBaseState);
}

}
<commit_msg>QmlDesigner.dragTool: improve usablity of drag and drop<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "dragtool.h"

#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"
#include "itemutilfunctions.h"
#include <customdraganddrop.h>
#include <metainfo.h>
#include <rewritingexception.h>

#include "resizehandleitem.h"

#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QtDebug>
#include <QMessageBox>
#include <QTimer>

namespace QmlDesigner {

namespace Internal {
void TimerHandler::clearMoveDelay()
{
    m_dragTool->clearMoveDelay();
}

}

DragTool::DragTool(FormEditorView *editorView)
    : AbstractFormEditorTool(editorView),
    m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView),
    m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
    m_timerHandler(new Internal::TimerHandler(this)),
    m_blockMove(false),
    m_Aborted(false)
{
}

DragTool::~DragTool()
{

}

void DragTool::clear()
{
    m_moveManipulator.clear();
    m_selectionIndicator.clear();
    m_movingItem.clear();
}

void DragTool::mousePressEvent(const QList<QGraphicsItem*> &,
                                            QGraphicsSceneMouseEvent *)
{

}

void DragTool::mouseMoveEvent(const QList<QGraphicsItem*> &,
                                           QGraphicsSceneMouseEvent *)
{

}

void DragTool::hoverMoveEvent(const QList<QGraphicsItem*> &,
                        QGraphicsSceneMouseEvent * /*event*/)
{

}

void DragTool::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape) {
        abort();
        event->accept();
        view()->changeToSelectionTool();
    }
}

void DragTool::keyReleaseEvent(QKeyEvent *)
{

}

void DragTool::mouseReleaseEvent(const QList<QGraphicsItem*> &/*itemList*/,
                                 QGraphicsSceneMouseEvent *)
{

}

void DragTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> & /*itemList*/,
                                              QGraphicsSceneMouseEvent * /*event*/)
{

}

void DragTool::itemsAboutToRemoved(const QList<FormEditorItem*> & /* removedItemList */)
{

}

void DragTool::selectedItemsChanged(const QList<FormEditorItem*> &)
{

}

void DragTool::updateMoveManipulator()
{
    if (m_moveManipulator.isActive())
        return;
}

void DragTool::beginWithPoint(const QPointF &beginPoint)
{
    m_movingItem = scene()->itemForQmlItemNode(m_dragNode);

    m_moveManipulator.setItem(m_movingItem.data());
    m_moveManipulator.begin(beginPoint);
}

void DragTool::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, QmlItemNode parentNode, QPointF scenePos)
{
    MetaInfo metaInfo = MetaInfo::global();

    FormEditorItem *parentItem = scene()->itemForQmlItemNode(parentNode);
    QPointF pos = parentItem->mapFromScene(scenePos);

    m_dragNode = view()->createQmlItemNode(itemLibraryEntry, pos, parentNode);

    Q_ASSERT(m_dragNode.modelNode().isValid());

    QList<QmlItemNode> nodeList;
    nodeList.append(m_dragNode);
    m_selectionIndicator.setItems(scene()->itemsForQmlItemNodes(nodeList));
}

void DragTool::createQmlItemNodeFromImage(const QString &imageName, QmlItemNode parentNode, QPointF scenePos)
{
    if (!parentNode.isValid())
        return;

    MetaInfo metaInfo = MetaInfo::global();

    FormEditorItem *parentItem = scene()->itemForQmlItemNode(parentNode);
    QPointF pos = parentItem->mapFromScene(scenePos);

    m_dragNode = view()->createQmlItemNodeFromImage(imageName, pos, parentNode);

    QList<QmlItemNode> nodeList;
    nodeList.append(m_dragNode);
    m_selectionIndicator.setItems(scene()->itemsForQmlItemNodes(nodeList));
}

FormEditorItem* DragTool::calculateContainer(const QPointF &point, FormEditorItem * currentItem)
{
    QList<QGraphicsItem *> list = scene()->items(point);
    foreach (QGraphicsItem *item, list) {
         FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
         if (formEditorItem && formEditorItem != currentItem && formEditorItem->isContainer())
             return formEditorItem;
    }

    if (scene()->rootFormEditorItem())
        return scene()->rootFormEditorItem();
    return 0;
}

void DragTool::formEditorItemsChanged(const QList<FormEditorItem*> & itemList)
{
    if (m_movingItem && itemList.contains(m_movingItem.data())) {
        QList<FormEditorItem*> updateItemList;
        updateItemList.append(m_movingItem.data());
        m_selectionIndicator.updateItems(updateItemList);
    }
}

void DragTool::instancesCompleted(const QList<FormEditorItem*> &itemList)
{
    foreach (FormEditorItem* item, itemList)
        if (item->qmlItemNode() == m_dragNode)
            clearMoveDelay();
    QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::hide();
}

void DragTool::instancesParentChanged(const QList<FormEditorItem *> &itemList)
{
    m_moveManipulator.synchronizeInstanceParent(itemList);
}

void DragTool::clearMoveDelay()
{
    if (!m_blockMove)
        return;
    m_blockMove = false;
    if  (m_dragNode.isValid())
        beginWithPoint(m_startPoint);
}

void DragTool::abort()
{
    if (m_Aborted)
        return;

    m_Aborted = true;

    if (m_dragNode.isValid())
        m_dragNode.destroy();

    QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::hide();

    if (m_rewriterTransaction.isValid())
        m_rewriterTransaction.commit();

}

void DragTool::dropEvent(QGraphicsSceneDragDropEvent * event)
{
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
       event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        event->accept();
        end(event->scenePos());
        //Q_ASSERT(m_token.isValid());
        try {
            m_rewriterTransaction.commit();
        } catch (RewritingException &e) {
            QMessageBox::warning(0, "Error", e.description());
        }
        if (m_dragNode.isValid()) {
            QList<QmlItemNode> nodeList;
            nodeList.append(m_dragNode);
            view()->setSelectedQmlItemNodes(nodeList);
        }
        m_dragNode = ModelNode();
        view()->changeToSelectionTool();
    }
}

static ItemLibraryEntry itemLibraryEntryFromData(const QByteArray &data)
{
    QDataStream stream(data);

    ItemLibraryEntry itemLibraryEntry;
    stream >> itemLibraryEntry;

    return itemLibraryEntry;
}

void DragTool::dragEnterEvent(QGraphicsSceneDragDropEvent * event)
{
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
        event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        QList<Import> importToBeAddedList;
        m_blockMove = false;
        if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo")) {
            view()->widget()->setFocus();
            m_Aborted = false;
            Q_ASSERT(!event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo").isEmpty());
            ItemLibraryEntry itemLibraryEntry = itemLibraryEntryFromData(event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo"));
            if (!itemLibraryEntry.requiredImport().isEmpty()) {
                const QString newImportUrl = itemLibraryEntry.requiredImport();
                const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));
                Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

                if (!view()->model()->hasImport(newImport, true, true)) {
                    importToBeAddedList.append(newImport);
                }

            }
        }

        view()->model()->changeImports(importToBeAddedList, QList<Import>());

        if (!m_rewriterTransaction.isValid()) {
            view()->clearSelectedModelNodes();
            m_rewriterTransaction = view()->beginRewriterTransaction();
        }
    }
}

void DragTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * event)
{
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
       event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        event->accept();
        if (m_dragNode.isValid())
            m_dragNode.destroy();
        end(event->scenePos());

        try {
            m_rewriterTransaction.commit();
        } catch (RewritingException &e) {
            QMessageBox::warning(0, "Error", e.description());
        }

        QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::show();
        QList<QmlItemNode> nodeList;
        view()->setSelectedQmlItemNodes(nodeList);
        view()->changeToSelectionTool();
    }
}

void DragTool::dragMoveEvent(QGraphicsSceneDragDropEvent * event)
{
    if (m_blockMove)
        return;

    if (m_Aborted) {
        event->ignore();
        return;
    }
    if (QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::isAnimated())
        return;
    if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo") ||
       event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
        event->accept();
        QPointF scenePos = event->scenePos();
        if  (m_dragNode.isValid()) {

            FormEditorItem *parentItem = calculateContainer(event->scenePos() + QPoint(2, 2));
            if (!parentItem) {      //if there is no parent any more - the use left the scene
                end(event->scenePos());
                QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::show();
                m_dragNode.destroy(); //delete the node then
                return;
            }
            //move
            move(event->scenePos());
        } else {
            //create new node  if container
            if (m_dragNode.modelNode().isValid())
                return;

            FormEditorItem *parentItem = calculateContainer(scenePos);
            if (!parentItem)
                return;
            QmlItemNode parentNode;
            if (parentItem)
                parentNode = parentItem->qmlItemNode();

            if (event->mimeData()->hasFormat("application/vnd.bauhaus.itemlibraryinfo")) {
                Q_ASSERT(!event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo").isEmpty());
                ItemLibraryEntry itemLibraryEntry = itemLibraryEntryFromData(event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo"));
                createQmlItemNode(itemLibraryEntry, parentNode, event->scenePos());
            } else if (event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
                Q_ASSERT(!event->mimeData()->data("application/vnd.bauhaus.libraryresource").isEmpty());
                QString imageName = QString::fromLatin1((event->mimeData()->data("application/vnd.bauhaus.libraryresource")));
                createQmlItemNodeFromImage(imageName, parentNode, event->scenePos());
            } else Q_ASSERT(false);
            m_blockMove = true;
            m_startPoint = event->scenePos();
            QTimer::singleShot(1000, m_timerHandler.data(), SLOT(clearMoveDelay()));
        }
    }

    if (event->mimeData()->hasFormat("application/vnd.bauhaus.libraryresource")) {
    }
}

void  DragTool::end(QPointF scenePos)
{
    m_moveManipulator.end(scenePos);
    clear();
}

void  DragTool::move(QPointF scenePos)
{
    if (!m_movingItem)
        return;

    FormEditorItem *containerItem = calculateContainer(scenePos - QPoint(2, 2), m_movingItem.data());
    if (containerItem && m_movingItem->parentItem() &&
       containerItem != m_movingItem->parentItem()) {

        m_moveManipulator.reparentTo(containerItem);
    }

    //MoveManipulator::Snapping useSnapping = MoveManipulator::NoSnapping;
    MoveManipulator::Snapping useSnapping = MoveManipulator::UseSnapping;
   /* if (event->modifiers().testFlag(Qt::ControlModifier) != view()->isSnapButtonChecked())
        useSnapping = MoveManipulator::UseSnapping;*/

    m_moveManipulator.update(scenePos, useSnapping, MoveManipulator::UseBaseState);
}

}
<|endoftext|>


<commit_before>//
// Name: StartupDlg.cpp
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
#pragma implementation "StartupDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"

#ifndef WX_PRECOMP
#  include "wx/wx.h"
#endif

#if defined(UNIX)
#  include <X11/Xlib.h>
#  include <X11/Xutil.h>
#  include <GL/glx.h>
#endif

#include "vtlib/vtlib.h"	// mostly for gl.h

#include "StartupDlg.h"
#include "../Options.h"
#include "vtdata/vtLog.h"
#include "vtui/Helper.h"	// for AddFilenamesToComboBox

#include "app.h"
#include "TParamsDlg.h"
#include "TerrManDlg.h"

DECLARE_APP(vtApp);

//
// Helper: find the largest texture size supported by OpenGL
//
#ifdef WIN32
static void ShowOGLInfo(bool bLog, HDC hdc)
#else
static void ShowOGLInfo(bool bLog)
#endif
{
#if defined(WIN32)
	PIXELFORMATDESCRIPTOR pfd =
	{
		sizeof(PIXELFORMATDESCRIPTOR),   // size of this pfd
		1,					// version number
		PFD_DRAW_TO_WINDOW |	// support window
		PFD_SUPPORT_OPENGL |	// support OpenGL
		PFD_DOUBLEBUFFER,	  // double buffered
		PFD_TYPE_RGBA,		// RGBA type
		24,				  // 24-bit color depth
		0, 0, 0, 0, 0, 0,	  // color bits ignored
		0, 0, 0,				// no alpha buffer
		0, 0, 0, 0,		  // accum bits ignored
		32, 0, 0,			  // 32-bit z-buffer
		PFD_MAIN_PLANE,	  // main layer
		0, 0, 0, 0			// reserved, layer masks ignored
	};
	int  iPixelFormat;

	// get the best available match of pixel format for the device context
	iPixelFormat = ChoosePixelFormat(hdc, &pfd);
	// make that the pixel format of the device context
	SetPixelFormat(hdc, iPixelFormat, &pfd);

	HGLRC device = wglCreateContext(hdc);
	if (device == NULL)
	{
		DWORD lasterror = GetLastError();
		// 2000 The pixel format is invalid.  ERROR_INVALID_PIXEL_FORMAT
	}
	wglMakeCurrent(hdc, device);
#elif defined(UNIX)
	static int dblBuf[] =  {GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 1,
		GLX_DOUBLEBUFFER, None};
	Display *dpy;
	Window win;
	XVisualInfo *vi;
	Colormap cmap;
	XSetWindowAttributes swa;
	GLXContext cx;
	XEvent event;
	Bool needRedraw = False, recalcModelView = True;
	int dummy;

	dpy = XOpenDisplay(NULL);
	if (dpy == NULL)
		wxFatalError( "could not open display" );

	if (!glXQueryExtension(dpy, &dummy, &dummy))
		wxFatalError( "X server has no OpenGL GLX extension" );

	vi = glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf);
	if (vi == NULL)
		wxFatalError( "no RGB visual with double and depth buffer" );
	if (vi->c_class != TrueColor)
		wxFatalError( "TrueColor visual required for this program" );

	cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen),
			vi->visual, AllocNone);
	swa.colormap = cmap;
	swa.border_pixel = 0;
	swa.event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask;
	win = XCreateWindow(dpy, RootWindow(dpy, vi->screen),
			0, 0, 300, 300, 0, vi->depth,
			InputOutput, vi->visual,
			CWBorderPixel | CWColormap | CWEventMask, &swa);

	XSetStandardProperties(dpy, win, "test", "test",
		None, NULL, 0, NULL);

	cx = glXCreateContext(dpy, vi, None, True);
	if (cx == NULL)
		wxFatalError( "could not create rendering context" );

	glXMakeCurrent(dpy, win, cx);
#else
#  error "I don't know this platform."
#endif

	GLint value;
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value);
	GLenum error = glGetError();
	if (error == GL_INVALID_OPERATION)
		value = 0;

	if (bLog)
	{
		VTLOG("\tOpenGL Version: %hs\n\tVendor: %hs\n\tRenderer: %hs\n"
			"\tMaximum Texture Dimension: %d\n",
			glGetString(GL_VERSION), glGetString(GL_VENDOR),
			glGetString(GL_RENDERER), value);
	}
	else
	{
		wxString2 str;
		str.Printf(_T("OpenGL Version: %hs\nVendor: %hs\nRenderer: %hs\n")
			_T("Maximum Texture Dimension: %d\nExtensions: %hs"),
			glGetString(GL_VERSION), glGetString(GL_VENDOR),
			glGetString(GL_RENDERER), value, glGetString(GL_EXTENSIONS));

		wxDialog dlg(NULL, -1, _T("OpenGL Info"), wxDefaultPosition);
		TextDialogFunc(&dlg, true);
		wxTextCtrl* pText = (wxTextCtrl*) dlg.FindWindow( ID_TEXT );
		pText->SetValue(str);

		dlg.ShowModal();
	}

#ifdef WIN32
	wglDeleteContext(device);
#elif defined(UNIX)
	glXDestroyContext(dpy, cx);
	XDestroyWindow(dpy, win);
	XCloseDisplay(dpy);
#endif
}

// WDR: class implementations

//----------------------------------------------------------------------------
// StartupDlg
//----------------------------------------------------------------------------

void StartupDlg::GetOptionsFrom(EnviroOptions &opt)
{
	m_bStartEarth = opt.m_bEarthView;
	m_bStartTerrain = !opt.m_bEarthView;
	m_strImage = wxString::FromAscii((const char *)opt.m_strImage);
	m_strTName.from_utf8(opt.m_strInitTerrain);
	m_bFullscreen = opt.m_bFullscreen;
	m_bHtmlpane = opt.m_bHtmlpane;
	m_bFloatingToolbar = opt.m_bFloatingToolbar;
	m_bTextureCompression = opt.m_bTextureCompression;
	m_bSpeedTest = opt.m_bSpeedTest;
	m_fPlantScale = opt.m_fPlantScale;
	m_bShadows = opt.m_bShadows;
}

void StartupDlg::PutOptionsTo(EnviroOptions &opt)
{
	opt.m_bEarthView = m_bStartEarth;
	opt.m_strImage = m_strImage.mb_str();
	opt.m_strInitTerrain = m_strTName.to_utf8();
	opt.m_bFullscreen = m_bFullscreen;
	opt.m_bHtmlpane = m_bHtmlpane;
	opt.m_bFloatingToolbar = m_bFloatingToolbar;
	opt.m_bTextureCompression = m_bTextureCompression;
	opt.m_bSpeedTest = m_bSpeedTest;
	opt.m_fPlantScale = m_fPlantScale;
	opt.m_bShadows = m_bShadows;
}

void StartupDlg::UpdateState()
{
	m_psImage->Enable(m_bStartEarth);
	m_pImage->Enable(m_bStartEarth);
	GetTname()->Enable(m_bStartTerrain);
}

// WDR: event table for StartupDlg

BEGIN_EVENT_TABLE(StartupDlg,AutoDialog)
	EVT_BUTTON( wxID_OK, StartupDlg::OnOK )
	EVT_BUTTON( ID_OPENGL, StartupDlg::OnOpenGLInfo )
	EVT_RADIOBUTTON( ID_EARTHVIEW, StartupDlg::OnEarthView )
	EVT_RADIOBUTTON( ID_TERRAIN, StartupDlg::OnTerrain )
	EVT_BUTTON( ID_EDITPROP, StartupDlg::OnEditProp )
	EVT_BUTTON( ID_TERRMAN, StartupDlg::OnTerrMan )
	EVT_CHOICE( ID_TNAME, StartupDlg::OnTnameChoice )
END_EVENT_TABLE()

StartupDlg::StartupDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
		AutoDialog( parent, id, title, position, size, style )
{
	VTLOG("Constructing StartupDlg.\n");
	StartupDialogFunc( this, TRUE );
}

void StartupDlg::RefreshTerrainChoices()
{
	GetTname()->Clear();

	vtApp &app = wxGetApp();
	wxString2 ws;

	for (unsigned int i = 0; i < app.terrain_files.size(); i++)
	{
		ws.from_utf8(app.terrain_names[i]);
		GetTname()->Append(ws);
	}
}

// WDR: handler implementations for StartupDlg

void StartupDlg::OnTnameChoice( wxCommandEvent &event )
{
	m_strTName = GetTname()->GetStringSelection();
}

void StartupDlg::OnTerrMan( wxCommandEvent &event )
{
	TerrainManagerDlg dlg(this, -1, _T("Terrain Manager"), wxDefaultPosition);
	if (dlg.ShowModal() == wxID_OK)
	{
		g_Options.Write();
		wxGetApp().RefreshTerrainList();
		RefreshTerrainChoices();
		int sel = GetTname()->FindString(m_strTName);
		if (sel != -1)
			GetTname()->Select(sel);
	}
}

void StartupDlg::OnEditProp( wxCommandEvent &event )
{
	vtString name_old = m_strTName.to_utf8();
	vtString path_to_ini = wxGetApp().GetIniFileForTerrain(name_old);
	if (path_to_ini == "")
		return;

	int res = EditTerrainParameters(this, path_to_ini);
	if (res == wxID_OK)
	{
		// Name might have changed
		TParams params;
		if (params.LoadFromXML(path_to_ini))
		{
			vtString name_new = params.GetValueString(STR_NAME);
			if (name_new != name_old)
				m_strTName.from_utf8(name_new);
		}

		wxGetApp().RefreshTerrainList();
		RefreshTerrainChoices();
		int sel = GetTname()->FindString(m_strTName);
		if (sel != -1)
			GetTname()->Select(sel);
	}
}

void StartupDlg::OnTerrain( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateState();
}

void StartupDlg::OnEarthView( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateState();
}

void StartupDlg::OnOpenGLInfo( wxCommandEvent &event )
{
	// display OpenGL info, including max texture size
#ifdef WIN32
	wxClientDC wdc(this);
	HDC hdc = (HDC) wdc.GetHDC();
	ShowOGLInfo(false, hdc);
#else
	ShowOGLInfo(false);
#endif
}

void StartupDlg::OnOK( wxCommandEvent &event )
{
	VTLOG("StartupDlg pressed OK.\n");
	wxDialog::OnOK(event);
}

void StartupDlg::OnInitDialog(wxInitDialogEvent& event)
{
	int sel;

	VTLOG("StartupDlg Init.\n");

	// display OpenGL info, including max texture size
#ifdef WIN32
	wxClientDC wdc(this);
	HDC hdc = (HDC) wdc.GetHDC();
	ShowOGLInfo(true, hdc);
#else
	ShowOGLInfo(true);
#endif

/*  vtTerrain *pTerr = GetTerrainScene()->FindTerrainByName(m_strTName.to_utf8());
	if (pTerr)
		m_strTName = wxString::FromAscii(pTerr->GetName());
	else
		m_strTName = _T("none");
*/
	m_psImage = GetImagetext();
	m_pImage = GetImage();

	vtStringArray &paths = g_Options.m_DataPaths;
	for (unsigned int i = 0; i < paths.size(); i++)
	{
		vtString path = paths[i];
		path += "WholeEarth/";
		AddFilenamesToComboBox(m_pImage, path, "*_0106.png", 9);
		AddFilenamesToComboBox(m_pImage, path, "*_0106.jpg", 9);
	}
	sel = m_pImage->FindString(m_strImage);
	if (sel != -1)
		m_pImage->SetSelection(sel);

	UpdateState();

	AddValidator(ID_EARTHVIEW, &m_bStartEarth);
	AddValidator(ID_TERRAIN, &m_bStartTerrain);

	AddValidator(ID_FULLSCREEN, &m_bFullscreen);
	AddValidator(ID_HTML_PANE, &m_bHtmlpane);
	AddValidator(ID_FLOATING, &m_bFloatingToolbar);
	AddValidator(ID_TEXTURE_COMPRESSION, &m_bTextureCompression);
	AddValidator(ID_SHADOWS, &m_bShadows);

	// Terrain choices
	RefreshTerrainChoices();
	sel = GetTname()->FindString(m_strTName);
	if (sel != -1)
		GetTname()->Select(sel);

	AddValidator(ID_IMAGE, &m_strImage);
	AddNumValidator(ID_PLANTSIZE, &m_fPlantScale, 2);

	wxWindow::OnInitDialog(event);
}

<commit_msg>fixed ini vs. xml issue<commit_after>//
// Name: StartupDlg.cpp
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
#pragma implementation "StartupDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"

#ifndef WX_PRECOMP
#  include "wx/wx.h"
#endif

#if defined(UNIX)
#  include <X11/Xlib.h>
#  include <X11/Xutil.h>
#  include <GL/glx.h>
#endif

#include "vtlib/vtlib.h"	// mostly for gl.h

#include "StartupDlg.h"
#include "../Options.h"
#include "vtdata/vtLog.h"
#include "vtui/Helper.h"	// for AddFilenamesToComboBox

#include "app.h"
#include "TParamsDlg.h"
#include "TerrManDlg.h"

DECLARE_APP(vtApp);

//
// Helper: find the largest texture size supported by OpenGL
//
#ifdef WIN32
static void ShowOGLInfo(bool bLog, HDC hdc)
#else
static void ShowOGLInfo(bool bLog)
#endif
{
#if defined(WIN32)
	PIXELFORMATDESCRIPTOR pfd =
	{
		sizeof(PIXELFORMATDESCRIPTOR),   // size of this pfd
		1,					// version number
		PFD_DRAW_TO_WINDOW |	// support window
		PFD_SUPPORT_OPENGL |	// support OpenGL
		PFD_DOUBLEBUFFER,	  // double buffered
		PFD_TYPE_RGBA,		// RGBA type
		24,				  // 24-bit color depth
		0, 0, 0, 0, 0, 0,	  // color bits ignored
		0, 0, 0,				// no alpha buffer
		0, 0, 0, 0,		  // accum bits ignored
		32, 0, 0,			  // 32-bit z-buffer
		PFD_MAIN_PLANE,	  // main layer
		0, 0, 0, 0			// reserved, layer masks ignored
	};
	int  iPixelFormat;

	// get the best available match of pixel format for the device context
	iPixelFormat = ChoosePixelFormat(hdc, &pfd);
	// make that the pixel format of the device context
	SetPixelFormat(hdc, iPixelFormat, &pfd);

	HGLRC device = wglCreateContext(hdc);
	if (device == NULL)
	{
		DWORD lasterror = GetLastError();
		// 2000 The pixel format is invalid.  ERROR_INVALID_PIXEL_FORMAT
	}
	wglMakeCurrent(hdc, device);
#elif defined(UNIX)
	static int dblBuf[] =  {GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 1,
		GLX_DOUBLEBUFFER, None};
	Display *dpy;
	Window win;
	XVisualInfo *vi;
	Colormap cmap;
	XSetWindowAttributes swa;
	GLXContext cx;
	XEvent event;
	Bool needRedraw = False, recalcModelView = True;
	int dummy;

	dpy = XOpenDisplay(NULL);
	if (dpy == NULL)
		wxFatalError( "could not open display" );

	if (!glXQueryExtension(dpy, &dummy, &dummy))
		wxFatalError( "X server has no OpenGL GLX extension" );

	vi = glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf);
	if (vi == NULL)
		wxFatalError( "no RGB visual with double and depth buffer" );
	if (vi->c_class != TrueColor)
		wxFatalError( "TrueColor visual required for this program" );

	cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen),
			vi->visual, AllocNone);
	swa.colormap = cmap;
	swa.border_pixel = 0;
	swa.event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask;
	win = XCreateWindow(dpy, RootWindow(dpy, vi->screen),
			0, 0, 300, 300, 0, vi->depth,
			InputOutput, vi->visual,
			CWBorderPixel | CWColormap | CWEventMask, &swa);

	XSetStandardProperties(dpy, win, "test", "test",
		None, NULL, 0, NULL);

	cx = glXCreateContext(dpy, vi, None, True);
	if (cx == NULL)
		wxFatalError( "could not create rendering context" );

	glXMakeCurrent(dpy, win, cx);
#else
#  error "I don't know this platform."
#endif

	GLint value;
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value);
	GLenum error = glGetError();
	if (error == GL_INVALID_OPERATION)
		value = 0;

	if (bLog)
	{
		VTLOG("\tOpenGL Version: %hs\n\tVendor: %hs\n\tRenderer: %hs\n"
			"\tMaximum Texture Dimension: %d\n",
			glGetString(GL_VERSION), glGetString(GL_VENDOR),
			glGetString(GL_RENDERER), value);
	}
	else
	{
		wxString2 str;
		str.Printf(_T("OpenGL Version: %hs\nVendor: %hs\nRenderer: %hs\n")
			_T("Maximum Texture Dimension: %d\nExtensions: %hs"),
			glGetString(GL_VERSION), glGetString(GL_VENDOR),
			glGetString(GL_RENDERER), value, glGetString(GL_EXTENSIONS));

		wxDialog dlg(NULL, -1, _T("OpenGL Info"), wxDefaultPosition);
		TextDialogFunc(&dlg, true);
		wxTextCtrl* pText = (wxTextCtrl*) dlg.FindWindow( ID_TEXT );
		pText->SetValue(str);

		dlg.ShowModal();
	}

#ifdef WIN32
	wglDeleteContext(device);
#elif defined(UNIX)
	glXDestroyContext(dpy, cx);
	XDestroyWindow(dpy, win);
	XCloseDisplay(dpy);
#endif
}

// WDR: class implementations

//----------------------------------------------------------------------------
// StartupDlg
//----------------------------------------------------------------------------

void StartupDlg::GetOptionsFrom(EnviroOptions &opt)
{
	m_bStartEarth = opt.m_bEarthView;
	m_bStartTerrain = !opt.m_bEarthView;
	m_strImage = wxString::FromAscii((const char *)opt.m_strImage);
	m_strTName.from_utf8(opt.m_strInitTerrain);
	m_bFullscreen = opt.m_bFullscreen;
	m_bHtmlpane = opt.m_bHtmlpane;
	m_bFloatingToolbar = opt.m_bFloatingToolbar;
	m_bTextureCompression = opt.m_bTextureCompression;
	m_bSpeedTest = opt.m_bSpeedTest;
	m_fPlantScale = opt.m_fPlantScale;
	m_bShadows = opt.m_bShadows;
}

void StartupDlg::PutOptionsTo(EnviroOptions &opt)
{
	opt.m_bEarthView = m_bStartEarth;
	opt.m_strImage = m_strImage.mb_str();
	opt.m_strInitTerrain = m_strTName.to_utf8();
	opt.m_bFullscreen = m_bFullscreen;
	opt.m_bHtmlpane = m_bHtmlpane;
	opt.m_bFloatingToolbar = m_bFloatingToolbar;
	opt.m_bTextureCompression = m_bTextureCompression;
	opt.m_bSpeedTest = m_bSpeedTest;
	opt.m_fPlantScale = m_fPlantScale;
	opt.m_bShadows = m_bShadows;
}

void StartupDlg::UpdateState()
{
	m_psImage->Enable(m_bStartEarth);
	m_pImage->Enable(m_bStartEarth);
	GetTname()->Enable(m_bStartTerrain);
}

// WDR: event table for StartupDlg

BEGIN_EVENT_TABLE(StartupDlg,AutoDialog)
	EVT_BUTTON( wxID_OK, StartupDlg::OnOK )
	EVT_BUTTON( ID_OPENGL, StartupDlg::OnOpenGLInfo )
	EVT_RADIOBUTTON( ID_EARTHVIEW, StartupDlg::OnEarthView )
	EVT_RADIOBUTTON( ID_TERRAIN, StartupDlg::OnTerrain )
	EVT_BUTTON( ID_EDITPROP, StartupDlg::OnEditProp )
	EVT_BUTTON( ID_TERRMAN, StartupDlg::OnTerrMan )
	EVT_CHOICE( ID_TNAME, StartupDlg::OnTnameChoice )
END_EVENT_TABLE()

StartupDlg::StartupDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
		AutoDialog( parent, id, title, position, size, style )
{
	VTLOG("Constructing StartupDlg.\n");
	StartupDialogFunc( this, TRUE );
}

void StartupDlg::RefreshTerrainChoices()
{
	GetTname()->Clear();

	vtApp &app = wxGetApp();
	wxString2 ws;

	for (unsigned int i = 0; i < app.terrain_files.size(); i++)
	{
		ws.from_utf8(app.terrain_names[i]);
		GetTname()->Append(ws);
	}
}

// WDR: handler implementations for StartupDlg

void StartupDlg::OnTnameChoice( wxCommandEvent &event )
{
	m_strTName = GetTname()->GetStringSelection();
}

void StartupDlg::OnTerrMan( wxCommandEvent &event )
{
	TerrainManagerDlg dlg(this, -1, _T("Terrain Manager"), wxDefaultPosition);
	if (dlg.ShowModal() == wxID_OK)
	{
		g_Options.Write();
		wxGetApp().RefreshTerrainList();
		RefreshTerrainChoices();
		int sel = GetTname()->FindString(m_strTName);
		if (sel != -1)
			GetTname()->Select(sel);
	}
}

void StartupDlg::OnEditProp( wxCommandEvent &event )
{
	vtString name_old = m_strTName.to_utf8();
	vtString path_to_ini = wxGetApp().GetIniFileForTerrain(name_old);
	if (path_to_ini == "")
		return;

	int res = EditTerrainParameters(this, path_to_ini);
	if (res == wxID_OK)
	{
		// Name might have changed
		TParams params;
		if (params.LoadFrom(path_to_ini))
		{
			vtString name_new = params.GetValueString(STR_NAME);
			if (name_new != name_old)
				m_strTName.from_utf8(name_new);
		}

		wxGetApp().RefreshTerrainList();
		RefreshTerrainChoices();
		int sel = GetTname()->FindString(m_strTName);
		if (sel != -1)
			GetTname()->Select(sel);
	}
}

void StartupDlg::OnTerrain( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateState();
}

void StartupDlg::OnEarthView( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateState();
}

void StartupDlg::OnOpenGLInfo( wxCommandEvent &event )
{
	// display OpenGL info, including max texture size
#ifdef WIN32
	wxClientDC wdc(this);
	HDC hdc = (HDC) wdc.GetHDC();
	ShowOGLInfo(false, hdc);
#else
	ShowOGLInfo(false);
#endif
}

void StartupDlg::OnOK( wxCommandEvent &event )
{
	VTLOG("StartupDlg pressed OK.\n");
	wxDialog::OnOK(event);
}

void StartupDlg::OnInitDialog(wxInitDialogEvent& event)
{
	int sel;

	VTLOG("StartupDlg Init.\n");

	// display OpenGL info, including max texture size
#ifdef WIN32
	wxClientDC wdc(this);
	HDC hdc = (HDC) wdc.GetHDC();
	ShowOGLInfo(true, hdc);
#else
	ShowOGLInfo(true);
#endif

/*  vtTerrain *pTerr = GetTerrainScene()->FindTerrainByName(m_strTName.to_utf8());
	if (pTerr)
		m_strTName = wxString::FromAscii(pTerr->GetName());
	else
		m_strTName = _T("none");
*/
	m_psImage = GetImagetext();
	m_pImage = GetImage();

	vtStringArray &paths = g_Options.m_DataPaths;
	for (unsigned int i = 0; i < paths.size(); i++)
	{
		vtString path = paths[i];
		path += "WholeEarth/";
		AddFilenamesToComboBox(m_pImage, path, "*_0106.png", 9);
		AddFilenamesToComboBox(m_pImage, path, "*_0106.jpg", 9);
	}
	sel = m_pImage->FindString(m_strImage);
	if (sel != -1)
		m_pImage->SetSelection(sel);

	UpdateState();

	AddValidator(ID_EARTHVIEW, &m_bStartEarth);
	AddValidator(ID_TERRAIN, &m_bStartTerrain);

	AddValidator(ID_FULLSCREEN, &m_bFullscreen);
	AddValidator(ID_HTML_PANE, &m_bHtmlpane);
	AddValidator(ID_FLOATING, &m_bFloatingToolbar);
	AddValidator(ID_TEXTURE_COMPRESSION, &m_bTextureCompression);
	AddValidator(ID_SHADOWS, &m_bShadows);

	// Terrain choices
	RefreshTerrainChoices();
	sel = GetTname()->FindString(m_strTName);
	if (sel != -1)
		GetTname()->Select(sel);

	AddValidator(ID_IMAGE, &m_strImage);
	AddNumValidator(ID_PLANTSIZE, &m_fPlantScale, 2);

	wxWindow::OnInitDialog(event);
}

<|endoftext|>


<commit_before>//
// LocalDatabuf.cpp: a wrapper for the Databuf class which is found either
//  in vtdata or libMini.
//
// Copyright (c) 2008 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "LocalDatabuf.h"

/////////////////////////////////////////////////////

#ifdef _MSC_VER
  #if _MSC_VER == 1500 // vc9
	  #pragma message( "Adding link with libMini-vc9.lib" )
	  #pragma comment( lib, "libMini-vc9.lib" )
  #elif _MSC_VER == 1400 // vc8
	  #pragma message( "Adding link with libMini-vc8.lib" )
	  #pragma comment( lib, "libMini-vc8.lib" )
  #else // vc71
	  #pragma message( "Adding link with libMini-vc7.lib" )
	  #pragma comment( lib, "libMini-vc7.lib" )
  #endif
  #pragma comment( lib, "glu32.lib" )
#endif

/////////////////////////////////////////////////////

#if USE_LIBMINI_DATABUF

// A useful method to set the extents (in local CRS) and the corners
//  (in Geo WGS84) at the same time.
bool vtMiniDatabuf::SetBounds(const vtProjection &proj, const DRECT &extents)
{
	// First, set the extent rectangle
	set_extents(extents.left, extents.right, extents.bottom, extents.top);

	// Create transform from local to Geo-WGS84
	vtProjection geo;
	geo.SetWellKnownGeogCS("WGS84");
	OCT *trans = CreateCoordTransform(&proj, &geo);

	if (!trans)
		return false;

	// Convert each corner as a point
	DPoint2 sw_corner, se_corner, nw_corner, ne_corner;

	sw_corner.Set(extents.left, extents.bottom);
	trans->Transform(1, &sw_corner.x, &sw_corner.y);

	se_corner.Set(extents.right, extents.bottom);
	trans->Transform(1, &se_corner.x, &se_corner.y);

	nw_corner.Set(extents.left, extents.top);
	trans->Transform(1, &nw_corner.x, &nw_corner.y);

	ne_corner.Set(extents.right, extents.top);
	trans->Transform(1, &ne_corner.x, &ne_corner.y);

	set_LLWGS84corners(sw_corner.x, sw_corner.y,
                       se_corner.x, se_corner.y,
                       nw_corner.x, nw_corner.y,
                       ne_corner.x, ne_corner.y);

	delete trans;
	return true;
}

#endif	// USE_LIBMINI_DATABUF
<commit_msg>don't use pragma, depend on cmake or project settings to link in libmini<commit_after>//
// LocalDatabuf.cpp: a wrapper for the Databuf class which is found either
//  in vtdata or libMini.
//
// Copyright (c) 2008 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "LocalDatabuf.h"

#if USE_LIBMINI_DATABUF

/////////////////////////////////////////////////////

#ifdef _MSC_VER
  #pragma comment( lib, "glu32.lib" )
#endif

// A useful method to set the extents (in local CRS) and the corners
//  (in Geo WGS84) at the same time.
bool vtMiniDatabuf::SetBounds(const vtProjection &proj, const DRECT &extents)
{
	// First, set the extent rectangle
	set_extents(extents.left, extents.right, extents.bottom, extents.top);

	// Create transform from local to Geo-WGS84
	vtProjection geo;
	geo.SetWellKnownGeogCS("WGS84");
	OCT *trans = CreateCoordTransform(&proj, &geo);

	if (!trans)
		return false;

	// Convert each corner as a point
	DPoint2 sw_corner, se_corner, nw_corner, ne_corner;

	sw_corner.Set(extents.left, extents.bottom);
	trans->Transform(1, &sw_corner.x, &sw_corner.y);

	se_corner.Set(extents.right, extents.bottom);
	trans->Transform(1, &se_corner.x, &se_corner.y);

	nw_corner.Set(extents.left, extents.top);
	trans->Transform(1, &nw_corner.x, &nw_corner.y);

	ne_corner.Set(extents.right, extents.top);
	trans->Transform(1, &ne_corner.x, &ne_corner.y);

	set_LLWGS84corners(sw_corner.x, sw_corner.y,
                       se_corner.x, se_corner.y,
                       nw_corner.x, nw_corner.y,
                       ne_corner.x, ne_corner.y);

	delete trans;
	return true;
}

#endif	// USE_LIBMINI_DATABUF
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkMaterialProperty.h"
#include "mitkBaseProperty.h"
#include "mitkBaseRenderer.h"
#include "mitkTestingMacros.h"
#include "mitkDataTreeNode.h"
#include <mitkVtkPropRenderer.h>

#include <iostream>

/**
*  Test for mitk::MaterialProperty
*
*  argc and argv are the command line parameters which were passed to
*  the ADD_TEST command in the CMakeLists.txt file. For the automatic
*  tests, argv is either empty for the simple tests or contains the filename
*  of a test image for the image tests (see CMakeLists.txt).
*/

int mitkMaterialPropertyTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("MaterialProperty")

 /*   mitk::MaterialProperty::Pointer myMP;

  {
    //static Pointer New(mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0)
    mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
    mitk::BaseRenderer::Pointer renderer = mitk::VtkPropRenderer::New("ContourRenderer", NULL);
    myMP = mitk::MaterialProperty::New(node, renderer);
    MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
      MITK_TEST_CONDITION( node == myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
      MITK_TEST_CONDITION( renderer == myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
  }*/

  /* {
  //static Pointer New( Color color, vtkFloatingPointType opacity = 1.0f, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0)
  mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
  mitk::BaseRenderer::Pointer renderer = new mitk::VtkPropRenderer();
  mitk::Color color;
  color.Set(0, 0, 0);
  vtkFloatingPointType opacity = 1.0f;
  myMP = mitk::MaterialProperty::New(color, opacity, node, renderer);
  MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
  MITK_TEST_CONDITION( node==myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
  MITK_TEST_CONDITION( renderer==myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
  MITK_TEST_CONDITION( color==myMP->GetColor(), "Testing if a Color object was set correctly" )
  MITK_TEST_CONDITION( opacity==myMP->GetOpacity(), "Testing if a Opacity object was set correctly" )
  }

  {
  //static Pointer New( vtkFloatingPointType red, vtkFloatingPointType green, vtkFloatingPointType blue, vtkFloatingPointType opacity = 1.0f, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0)
  mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
  mitk::BaseRenderer::Pointer renderer = new mitk::VtkPropRenderer();
  Color color;
  color.Set(0, 0, 0);
  vtkFloatingPointType opacity = 1.0f;
  vtkFloatingPointType rgb = 0;

  myMP = mitk::MaterialProperty::New(rgb, rgb, rgb, opacity, node, renderer);
  MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
  MITK_TEST_CONDITION( node==myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
  MITK_TEST_CONDITION( renderer==myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
  MITK_TEST_CONDITION( color==myMP->GetColor(), "Testing if a Color object was set correctly" )
  MITK_TEST_CONDITION( opacity==myMP->GetOpacity(), "Testing if a Opacity object was set correctly" )
  }*/

  /*{
  //static Pointer New( vtkFloatingPointType red, vtkFloatingPointType green, vtkFloatingPointType blue, vtkFloatingPointType colorCoefficient,  vtkFloatingPointType specularCoefficient, vtkFloatingPointType specularPower, vtkFloatingPointType opacity, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0 )
  mitk::DataTreeNode::Pointer node = DataTreeNode::New();
  mitk::BaseRenderer::Pointer renderer = BaseRenderer::New();
  Color color;
  color.Set(0, 0, 0);
  vtkFloatingPointType opacity = 1.0f;
  vtkFloatingPointType rgb = 0;
  vtkFloatingPointType colorCoefficient = 0;
  vtkFloatingPointType specularCoefficient = 0;
  vtkFloatingPointType specularPower = 0;

  myMP = MaterialProperty::New(rgb, rgb, rgb, colorCoefficient, specularCoefficient, specularPower, opacity, node, renderer);
  MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
  MITK_TEST_CONDITION( node==myMp->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
  MITK_TEST_CONDITION( renderer==myMp->GetRenderer(), "Testing if a Renderer object was set correctly" )
  MITK_TEST_CONDITION( color==myMp->GetColor(), "Testing if a Color object was set correctly" )
  MITK_TEST_CONDITION( opacity==myMp->GetOpacity(), "Testing if a Opacity object was set correctly" )
  MITK_TEST_CONDITION( specularCoefficient==myMp->GetSpecularCoefficient(), "Testing if a Coefficient object was set correctly" )
  MITK_TEST_CONDITION( specularPower==myMp->GetSpecularPower(), "Testing if a SpecularPower object was set correctly" )
  MITK_TEST_CONDITION( colorCoefficient==myMp->GetColorCoefficient(), "Testing if a colorCoefficient object was set correctly" )

  }

  {
  //static Pointer New( Color color, vtkFloatingPointType colorCoefficient, vtkFloatingPointType specularCoefficient, vtkFloatingPointType specularPower, vtkFloatingPointType opacity, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0 )
  mitk::DataTreeNode::Pointer node = DataTreeNode::New();
  mitk::BaseRenderer::Pointer renderer = BaseRenderer::New();
  Color color;
  color.Set(0, 0, 0);
  vtkFloatingPointType opacity = 1.0f;
  vtkFloatingPointType rgb = 0;
  vtkFloatingPointType colorCoefficient = 0;
  vtkFloatingPointType specularCoefficient = 0;
  vtkFloatingPointType specularPower = 0;

  myMP = MaterialProperty::New(rgb, rgb, rgb, colorCoefficient,
  specularCoefficient, specularPower, opacity, node, renderer);
  MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
  MITK_TEST_CONDITION( node==myMp->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
  MITK_TEST_CONDITION( renderer==myMp->GetRenderer(), "Testing if a Renderer object was set correctly" )
  MITK_TEST_CONDITION( color==myMp->GetColor(), "Testing if a Color object was set correctly" )
  MITK_TEST_CONDITION( opacity==myMp->GetOpacity(), "Testing if a Opacity object was set correctly" )
  MITK_TEST_CONDITION( specularCoefficient==myMp->GetSpecularCoefficient(), "Testing if a Coefficient object was set correctly" )
  MITK_TEST_CONDITION( specularPower==myMp->GetSpecularPower(), "Testing if a SpecularPower object was set correctly" )

  }*/

  // let's create an object of our class
  //mitk::MaterialProperty::Pointer myMP= mitk::MaterialProperty::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.

  // write your own tests here and use the macros from mitkTestingMacros.h !!!
  // do not write to std::cout and do not return from this function yourself!

  // always end with this!
  MITK_TEST_END      ()
}
<commit_msg>COMP: Fixed and tests run<commit_after>/*=========================================================================

 Program:   Medical Imaging & Interaction Toolkit
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/

#include "mitkMaterialProperty.h"
#include "mitkBaseProperty.h"
#include "mitkBaseRenderer.h"
#include "mitkTestingMacros.h"
#include "mitkDataTreeNode.h"
#include <mitkVtkPropRenderer.h>

#include <iostream>

/**
 *  Simple example for a test for the (non-existent) class "ClassName".
 *
 *  argc and argv are the command line parameters which were passed to
 *  the ADD_TEST command in the CMakeLists.txt file. For the automatic
 *  tests, argv is either empty for the simple tests or contains the filename
 *  of a test image for the image tests (see CMakeLists.txt).
 */

int
mitkMaterialPropertyTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("MaterialProperty")

      mitk::MaterialProperty::Pointer myMP;

        {
          //static Pointer New(mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0)
          mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
          mitk::BaseRenderer *renderer=NULL;
          myMP = mitk::MaterialProperty::New(node, renderer);
          MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
          MITK_TEST_CONDITION( node == myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
          MITK_TEST_CONDITION( renderer == myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
        }

       {
       //static Pointer New( Color color, vtkFloatingPointType opacity = 1.0f, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0)
       mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
       mitk::BaseRenderer *renderer=NULL;
       mitk::Color color;
       color.Set(0, 0, 0);
       vtkFloatingPointType opacity = 1.0f;
       myMP = mitk::MaterialProperty::New(color, opacity, node, renderer);
       MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
       MITK_TEST_CONDITION( node==myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
       MITK_TEST_CONDITION( renderer==myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
       MITK_TEST_CONDITION( color==myMP->GetColor(), "Testing if a Color object was set correctly" )
       MITK_TEST_CONDITION( opacity==myMP->GetOpacity(), "Testing if a Opacity object was set correctly" )
       }

      {
       //static Pointer New( vtkFloatingPointType red, vtkFloatingPointType green, vtkFloatingPointType blue, vtkFloatingPointType opacity = 1.0f, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0)
       mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
       mitk::BaseRenderer *renderer=NULL;
       mitk::MaterialProperty::Color color;
       color.Set(0, 0, 0);
       vtkFloatingPointType opacity = 1.0f;
       vtkFloatingPointType rgb = 0;

       myMP = mitk::MaterialProperty::New(rgb, rgb, rgb, opacity, node, renderer);
       MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
       MITK_TEST_CONDITION( node==myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
       MITK_TEST_CONDITION( renderer==myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
       MITK_TEST_CONDITION( color==myMP->GetColor(), "Testing if a Color object was set correctly" )
       MITK_TEST_CONDITION( opacity==myMP->GetOpacity(), "Testing if a Opacity object was set correctly" )
       }

      {
       //static Pointer New( vtkFloatingPointType red, vtkFloatingPointType green, vtkFloatingPointType blue, vtkFloatingPointType colorCoefficient,  vtkFloatingPointType specularCoefficient, vtkFloatingPointType specularPower, vtkFloatingPointType opacity, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0 )
       mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
       mitk::BaseRenderer *renderer=NULL;
       mitk::MaterialProperty::Color color;
       color.Set(0, 0, 0);
       vtkFloatingPointType opacity = 1.0f;
       vtkFloatingPointType rgb = 0;
       vtkFloatingPointType colorCoefficient = 0;
       vtkFloatingPointType specularCoefficient = 0;
       vtkFloatingPointType specularPower = 0;

       myMP = mitk::MaterialProperty::New(rgb, rgb, rgb, colorCoefficient, specularCoefficient, specularPower, opacity, node, renderer);
       MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
       MITK_TEST_CONDITION( node==myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
       MITK_TEST_CONDITION( renderer==myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
       MITK_TEST_CONDITION( color==myMP->GetColor(), "Testing if a Color object was set correctly" )
       MITK_TEST_CONDITION( opacity==myMP->GetOpacity(), "Testing if a Opacity object was set correctly" )
       MITK_TEST_CONDITION( specularCoefficient==myMP->GetSpecularCoefficient(), "Testing if a Coefficient object was set correctly" )
       MITK_TEST_CONDITION( specularPower==myMP->GetSpecularPower(), "Testing if a SpecularPower object was set correctly" )
       MITK_TEST_CONDITION( colorCoefficient==myMP->GetColorCoefficient(), "Testing if a colorCoefficient object was set correctly" )

       }

      {
       //static Pointer New( Color color, vtkFloatingPointType colorCoefficient, vtkFloatingPointType specularCoefficient, vtkFloatingPointType specularPower, vtkFloatingPointType opacity, mitk::DataTreeNode* node = 0, mitk::BaseRenderer* renderer = 0 )
       mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
       mitk::BaseRenderer *renderer=NULL;
       mitk::MaterialProperty::Color color;
       color.Set(0, 0, 0);
       vtkFloatingPointType opacity = 1.0f;
       vtkFloatingPointType rgb = 0;
       vtkFloatingPointType colorCoefficient = 0;
       vtkFloatingPointType specularCoefficient = 0;
       vtkFloatingPointType specularPower = 0;

       myMP = mitk::MaterialProperty::New(rgb, rgb, rgb, colorCoefficient,
       specularCoefficient, specularPower, opacity, node, renderer);
       MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(),"Testing instantiation")
       MITK_TEST_CONDITION( node==myMP->GetDataTreeNode(), "Testing if a DataTreeNode object was set correctly" )
       MITK_TEST_CONDITION( renderer==myMP->GetRenderer(), "Testing if a Renderer object was set correctly" )
       MITK_TEST_CONDITION( color==myMP->GetColor(), "Testing if a Color object was set correctly" )
       MITK_TEST_CONDITION( opacity==myMP->GetOpacity(), "Testing if a Opacity object was set correctly" )
       MITK_TEST_CONDITION( specularCoefficient==myMP->GetSpecularCoefficient(), "Testing if a Coefficient object was set correctly" )
       MITK_TEST_CONDITION( specularPower==myMP->GetSpecularPower(), "Testing if a SpecularPower object was set correctly" )

       }

      // first test: did this work?
      // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
      // it makes no sense to continue without an object.

      // write your own tests here and use the macros from mitkTestingMacros.h !!!
      // do not write to std::cout and do not return from this function yourself!

      // always end with this!
MITK_TEST_END    ()
  }
<|endoftext|>