<commit_before>#include <limits>
#include <stdexcept>
//test
#include <iostream>
#include <fstream>
#include <stdlib.h>

#include "visual.h"
#include "bvh_node.h"

BVHNode::BVHNode()
{
	this->left = NULL;
	this->right = NULL;
}

BVHNode::~BVHNode()
{
    // TODO
}

void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs)
{
	this->triangles.push_back(Triangle(&mesh, 0));
	Vec3f min = this->triangles.back().getAABBMin();
	Vec3f max = this->triangles.back().getAABBMax();

	for (unsigned int var = 1; var < faceIDs->size(); ++var)
	{
		this->triangles.push_back(Triangle(&mesh, var));

		for (int i = 0; i < 3; i++)
		{
			if (min[i] > this->triangles.back().getAABBMin()[i])
				min[i] = this->triangles.back().getAABBMin()[i];
			if (max[i] < this->triangles.back().getAABBMax()[i])
				max[i] = this->triangles.back().getAABBMax()[i];
		}
	}

	std::vector<Triangle> left;
	std::vector<Triangle> right;

	Vec3f middle = max;
	int axis = aabb.getLongestAxis();
	middle[axis] = (min[axis] + max[axis]) / 2;

	AABB half = AABB(min, middle);

	while (this->triangles.size() > 0)
	{
		if (half.inside(this->triangles.back().getCentroid()))
			left.push_back(this->triangles.back());
		else
			right.push_back(this->triangles.back());

		this->triangles.pop_back();
	}

    this->aabb = AABB(min, max);

	if (left.size() > MAX_LEAF_TRIANGLES)
	{
		this->left = new BVHNode();
		this->left->insert(&left);
	}

	if (right.size() > MAX_LEAF_TRIANGLES)
	{
		this->right = new BVHNode();
		this->right->insert(&right);
	}
}

void BVHNode::insert(std::vector<Triangle>* triangles)
{
	this->triangles.push_back(triangles->back());
	Vec3f min = this->triangles.back().getAABBMin();
	Vec3f max = this->triangles.back().getAABBMax();

	triangles->pop_back();

	for (unsigned int var = 2; var < triangles->size(); ++var)
	{
		this->triangles.push_back(triangles->back());
		triangles->pop_back();
		for (int i = 0; i < 3; i++)
		{
			if (min[i] > this->triangles.back().getAABBMin()[i])
				min[i] = this->triangles.back().getAABBMin()[i];
			if (max[i] < this->triangles.back().getAABBMax()[i])
				max[i] = this->triangles.back().getAABBMax()[i];
		}
	}

	this->aabb = AABB(min, max);

	if (this->triangles.size() <= MAX_LEAF_TRIANGLES)
		return;

	std::vector<Triangle> left;
	std::vector<Triangle> right;

	Vec3f middle = max;
	int axis = aabb.getLongestAxis();
	middle[axis] = (min[axis] + max[axis]) / 2;

	AABB half = AABB(min, middle);

	while (this->triangles.size() > 0)
	{
		if (half.inside(this->triangles.back().getCentroid()))
			left.push_back(this->triangles.back());
		else
			right.push_back(this->triangles.back());

		this->triangles.pop_back();
	}

	this->left = new BVHNode();
	this->left->insert(&left);

	this->right = new BVHNode();
	this->right->insert(&right);
}

bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const
{
	if (this->aabb.intersect(ray))
	{
		if (left == NULL && right == NULL)
			for (unsigned int var = 1; var < triangles.size(); ++var)
				if (triangles.at(var).intersect(ray, intersection))
					return true;
		else
			return left->intersect(ray, intersection) || right->intersect(ray, intersection);
	}
    return false;
}
<commit_msg>insert fixed (while triangles>0 statt for schleife),faktor 100 mehr nodes,mesh_bvh<commit_after>#include <limits>
#include <stdexcept>
//test
#include <iostream>
using namespace std;
#include <fstream>
#include <stdlib.h>

#include "visual.h"
#include "bvh_node.h"

BVHNode::BVHNode()
{
	this->left = NULL;
	this->right = NULL;
}

BVHNode::~BVHNode()
{
    // TODO
}

void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs)
{
	this->triangles.push_back(Triangle(&mesh, 0));
	Vec3f min = this->triangles.back().getAABBMin();
	Vec3f max = this->triangles.back().getAABBMax();

	for (unsigned int var = 1; var < faceIDs->size(); ++var)
	{
		this->triangles.push_back(Triangle(&mesh, var));

		for (int i = 0; i < 3; i++)
		{
			if (min[i] > this->triangles.back().getAABBMin()[i])
				min[i] = this->triangles.back().getAABBMin()[i];
			if (max[i] < this->triangles.back().getAABBMax()[i])
				max[i] = this->triangles.back().getAABBMax()[i];
		}
	}

	std::vector<Triangle> left;
	std::vector<Triangle> right;

	Vec3f middle = max;
	int axis = aabb.getLongestAxis();
	middle[axis] = (min[axis] + max[axis]) / 2;

	AABB half = AABB(min, middle);

	while (this->triangles.size() > 0)
	{
		if (half.inside(this->triangles.back().getCentroid()))
			left.push_back(this->triangles.back());
		else
			right.push_back(this->triangles.back());

		this->triangles.pop_back();
	}

    this->aabb = AABB(min, max);

	if (left.size() > MAX_LEAF_TRIANGLES)
	{
		this->left = new BVHNode();
		this->left->insert(&left);
	}

	if (right.size() > MAX_LEAF_TRIANGLES)
	{
		this->right = new BVHNode();
		this->right->insert(&right);
	}
}

void BVHNode::insert(std::vector<Triangle>* triangles)
{
	this->triangles.push_back(triangles->back());
	Vec3f min = this->triangles.back().getAABBMin();
	Vec3f max = this->triangles.back().getAABBMax();

	triangles->pop_back();

	while(triangles->size() >0)
	{
		this->triangles.push_back(triangles->back());
		triangles->pop_back();
		for (int i = 0; i < 3; i++)
		{
			if (min[i] > this->triangles.back().getAABBMin()[i])
				min[i] = this->triangles.back().getAABBMin()[i];
			if (max[i] < this->triangles.back().getAABBMax()[i])
				max[i] = this->triangles.back().getAABBMax()[i];
		}
	}

	this->aabb = AABB(min, max);

	if (this->triangles.size() <= MAX_LEAF_TRIANGLES)
		return;

	std::vector<Triangle> left;
	std::vector<Triangle> right;

	Vec3f middle = max;
	int axis = aabb.getLongestAxis();
	middle[axis] = (min[axis] + max[axis]) / 2;

	AABB half = AABB(min, middle);

	while (this->triangles.size() > 0)
	{
		if (half.inside(this->triangles.back().getCentroid()))
			left.push_back(this->triangles.back());
		else
			right.push_back(this->triangles.back());

		this->triangles.pop_back();
	}

	this->left = new BVHNode();
	this->left->insert(&left);

	this->right = new BVHNode();
	this->right->insert(&right);
}

bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const
{
	if (this->aabb.intersect(ray))
	{
		if (left == NULL && right == NULL)
			for (unsigned int var = 1; var < triangles.size(); ++var)
				if (triangles.at(var).intersect(ray, intersection))
					return true;
		else
			return left->intersect(ray, intersection) || right->intersect(ray, intersection);
	}
    return false;
<|endoftext|>


<commit_before>/*
 * Copyright 2014-present Facebook, Inc.
 *
 * 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.
 */

#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <folly/init/Init.h>
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>
#include <thrift/test/gen-cpp2/DeserializationBench_types.h>

folly::Random::DefaultGenerator rng_(12345);
const int32_t kNumOfInserts = 250;

std::vector<int32_t> getRandomVector() {
  std::vector<int32_t> v;
  for (int i = 0; i < kNumOfInserts; ++i) {
    v.push_back(i);
  }
  return v;
}

std::set<int32_t> getRandomSet() {
  std::set<int32_t> s;
  for (int i = 0; i < kNumOfInserts; ++i) {
    s.insert(i);
  }
  return s;
}

std::map<int32_t, std::string> getRandomMap() {
  std::map<int32_t, std::string> m;
  for (int i = 0; i < kNumOfInserts; ++i) {
    m.emplace(i, std::to_string(i));
  }
  return m;
}

void buildRandomStructA(cpp2::StructA& obj) {
  obj.fieldA = folly::Random::rand32(rng_) % 2;
  obj.fieldB = folly::Random::rand32(rng_);
  obj.fieldC = std::to_string(folly::Random::rand32(rng_));
  obj.fieldD = getRandomVector();
  obj.fieldE = getRandomSet();
  obj.fieldF = getRandomMap();

  for (int32_t i = 0; i < kNumOfInserts; ++i) {
    std::vector<std::vector<int32_t>> g1;
    std::set<std::set<int32_t>> h1;
    std::vector<std::set<int32_t>> j1;
    std::set<std::vector<int32_t>> j2;
    for (int32_t j = 0; j < kNumOfInserts; ++j) {
      g1.push_back(getRandomVector());
      h1.insert(getRandomSet());
      j1.push_back(getRandomSet());
      j2.insert(getRandomVector());
    }
    obj.fieldG.push_back(g1);
    obj.fieldH.insert(h1);
    obj.fieldI.emplace(getRandomMap(), getRandomMap());
    obj.fieldJ.emplace(j1, j2);
  }
}

BENCHMARK(Deserialization, iters) {
  for (size_t i = 0; i < iters; ++i) {
    // Stop time during object construction
    folly::BenchmarkSuspender braces;
      cpp2::StructA obj;
      cpp2::StructA obj2;
      apache::thrift::CompactProtocolWriter writer;
      apache::thrift::CompactProtocolReader reader;

      buildRandomStructA(obj);

      // Prepare Serialization
      size_t bufSize = obj.serializedSize(&writer);
      folly::IOBufQueue queue(folly::IOBufQueue::cacheChainLength());
      writer.setOutput(&queue, bufSize);

      // Serialize
      obj.write(&writer);

      // Prepare Deserialization
      bufSize = queue.chainLength();
      auto buf = queue.move();
      reader.setInput(buf.get());
    braces.dismiss();

    // Deserialize
    obj2.read(&reader);
  }
}

int main(int argc, char** argv) {
  folly::init(&argc, &argv);
  folly::runBenchmarks();
  return 0;
}

/*
============================================================================
thrift/test/DeserializationBench.cpp            relative  time/iter  iters/s
============================================================================
Deserialization                                               1.36s  734.51m
============================================================================
*/
<commit_msg>Better control of timing in the deserialization bench<commit_after>/*
 * Copyright 2014-present Facebook, Inc.
 *
 * 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.
 */

#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <folly/init/Init.h>
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>
#include <thrift/test/gen-cpp2/DeserializationBench_types.h>

folly::Random::DefaultGenerator rng_(12345);
const int32_t kNumOfInserts = 250;

std::vector<int32_t> getRandomVector() {
  std::vector<int32_t> v;
  for (int i = 0; i < kNumOfInserts; ++i) {
    v.push_back(i);
  }
  return v;
}

std::set<int32_t> getRandomSet() {
  std::set<int32_t> s;
  for (int i = 0; i < kNumOfInserts; ++i) {
    s.insert(i);
  }
  return s;
}

std::map<int32_t, std::string> getRandomMap() {
  std::map<int32_t, std::string> m;
  for (int i = 0; i < kNumOfInserts; ++i) {
    m.emplace(i, std::to_string(i));
  }
  return m;
}

void buildRandomStructA(cpp2::StructA& obj) {
  obj.fieldA = folly::Random::rand32(rng_) % 2;
  obj.fieldB = folly::Random::rand32(rng_);
  obj.fieldC = std::to_string(folly::Random::rand32(rng_));
  obj.fieldD = getRandomVector();
  obj.fieldE = getRandomSet();
  obj.fieldF = getRandomMap();

  for (int32_t i = 0; i < kNumOfInserts; ++i) {
    std::vector<std::vector<int32_t>> g1;
    std::set<std::set<int32_t>> h1;
    std::vector<std::set<int32_t>> j1;
    std::set<std::vector<int32_t>> j2;
    for (int32_t j = 0; j < kNumOfInserts; ++j) {
      g1.push_back(getRandomVector());
      h1.insert(getRandomSet());
      j1.push_back(getRandomSet());
      j2.insert(getRandomVector());
    }
    obj.fieldG.push_back(g1);
    obj.fieldH.insert(h1);
    obj.fieldI.emplace(getRandomMap(), getRandomMap());
    obj.fieldJ.emplace(j1, j2);
  }
}

BENCHMARK(Deserialization, iters) {
  folly::BenchmarkSuspender braces; // stop the clock by default

  for (size_t i = 0; i < iters; ++i) {
    // Prep, untimed:
    cpp2::StructA obj;
    cpp2::StructA obj2;
    apache::thrift::CompactProtocolWriter writer;
    apache::thrift::CompactProtocolReader reader;

    buildRandomStructA(obj);

    // Serialize, untimed:
    size_t bufSize = obj.serializedSize(&writer);
    folly::IOBufQueue queue(folly::IOBufQueue::cacheChainLength());
    writer.setOutput(&queue, bufSize);
    obj.write(&writer);

    // Deserialize, timed:
    bufSize = queue.chainLength();
    auto buf = queue.move();
    reader.setInput(buf.get());
    braces.dismissing([&] {
      obj2.read(&reader);
    });
  }
}

int main(int argc, char** argv) {
  folly::init(&argc, &argv);
  folly::runBenchmarks();
  return 0;
}

/*
============================================================================
thrift/test/DeserializationBench.cpp            relative  time/iter  iters/s
============================================================================
Deserialization                                               1.36s  734.51m
============================================================================
*/
<|endoftext|>


<commit_before>//The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence S= {a1 , a2 , a3, a4, ............., an-1, an } we have to find a longest subset such that for all j and i,  j<i in the subset aj<ai.
<commit_msg>Update LongestIncreasingSubsequence.cpp<commit_after>//The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence S= {a1 , a2 , a3, a4, ............., an-1, an } we have to find a longest subset such that for all j and i,  j<i in the subset aj<ai.

A[0] = 0. Case 1. There are no active lists, create one.
0.
-----------------------------------------------------------------------------
A[1] = 8. Case 2. Clone and extend.
0.
0, 8.
-----------------------------------------------------------------------------
A[2] = 4. Case 3. Clone, extend and discard.
0.
0, 4.
0, 8. Discarded
-----------------------------------------------------------------------------
A[3] = 12. Case 2. Clone and extend.
0.
0, 4.
0, 4, 12.
-----------------------------------------------------------------------------
A[4] = 2. Case 3. Clone, extend and discard.
0.
0, 2.
0, 4. Discarded.
0, 4, 12.
-----------------------------------------------------------------------------
A[5] = 10. Case 3. Clone, extend and discard.
0.
0, 2.
0, 2, 10.
0, 4, 12. Discarded.
-----------------------------------------------------------------------------
A[6] = 6. Case 3. Clone, extend and discard.
0.
0, 2.
0, 2, 6.
0, 2, 10. Discarded.
-----------------------------------------------------------------------------
A[7] = 14. Case 2. Clone and extend.
0.
0, 2.
0, 2, 6.
0, 2, 6, 14.
-----------------------------------------------------------------------------
A[8] = 1. Case 3. Clone, extend and discard.
0.
0, 1.
0, 2. Discarded.
0, 2, 6.
0, 2, 6, 14.
-----------------------------------------------------------------------------
A[9] = 9. Case 3. Clone, extend and discard.
0.
0, 1.
0, 2, 6.
0, 2, 6, 9.
0, 2, 6, 14. Discarded.
-----------------------------------------------------------------------------
A[10] = 5. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 5.
0, 2, 6. Discarded.
0, 2, 6, 9.
-----------------------------------------------------------------------------
A[11] = 13. Case 2. Clone and extend.
0.
0, 1.
0, 1, 5.
0, 2, 6, 9.
0, 2, 6, 9, 13.
-----------------------------------------------------------------------------
A[12] = 3. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 3.
0, 1, 5. Discarded.
0, 2, 6, 9.
0, 2, 6, 9, 13.
-----------------------------------------------------------------------------
A[13] = 11. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 3.
0, 2, 6, 9.
0, 2, 6, 9, 11.
0, 2, 6, 9, 13. Discarded.
-----------------------------------------------------------------------------
A[14] = 7. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 3.
0, 1, 3, 7.
0, 2, 6, 9. Discarded.
0, 2, 6, 9, 11.
----------------------------------------------------------------------------
A[15] = 15. Case 2. Clone and extend.
0.
0, 1.
0, 1, 3.
0, 1, 3, 7.
0, 2, 6, 9, 11.
0, 2, 6, 9, 11, 15. <-- LIS List
----------------------------------------------------------------------------

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2015 Colin Hill
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////
#include "Logging.h"

#include "Hect/Timing/Timer.h"

#ifdef HECT_WINDOWS_BUILD
#include <Windows.h>

static HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif

#include <iomanip>
#include <iostream>
#include <mutex>
#include <sstream>

namespace hect
{

static std::mutex _logMutex;

void log(LogLevel level, const std::string& message)
{
    static Timer timer;
    std::lock_guard<std::mutex> lock(_logMutex);

    // Calculate timestamp parts
    int64_t total = timer.elapsed().milliseconds();
    int64_t milliseconds = total % 1000;
    int64_t seconds = total / 1000 % 60;
    int64_t minutes = total / 1000 / 60 % 60;
    int64_t hours = total / 1000 / 60 / 60;

    // Format message with timestamp prepended
    std::stringstream ss;
    ss << std::setfill('0') << "[" << hours << ":"
       << std::setw(2) << minutes << ":"
       << std::setw(2) << seconds << ":"
       << std::setw(3) << milliseconds << "] "
       << message << std::endl;
    std::string formattedMessage = ss.str();

#ifdef HECT_WINDOWS_BUILD

#ifdef HECT_DEBUG_BUILD
    OutputDebugString(formattedMessage.c_str());
#endif

    // Set the color text color
    switch (level)
    {
    case LogLevel_Info:
        SetConsoleTextAttribute(stdOutHandle, 15);
        break;
    case LogLevel_Debug:
        SetConsoleTextAttribute(stdOutHandle, 7);
        break;
    case LogLevel_Warning:
        SetConsoleTextAttribute(stdOutHandle, 14);
        break;
    case LogLevel_Error:
        SetConsoleTextAttribute(stdOutHandle, 12);
        break;
    case LogLevel_Trace:
        SetConsoleTextAttribute(stdOutHandle, 8);
        break;
    }

    std::cout << formattedMessage;
    std::cout.flush();

    // Reset the console text color
    SetConsoleTextAttribute(stdOutHandle, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    // Show a message box when logging an error
    if (level == LogLevel_Error)
    {
        MessageBoxA(NULL, message.c_str(), "Error", MB_ICONHAND | MB_OK);
    }
#else
    std::cout << formattedMessage;
    std::cout.flush();
#endif
}

}
<commit_msg>Fixed Clang warning in recent changes<commit_after>///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2015 Colin Hill
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////
#include "Logging.h"

#include "Hect/Timing/Timer.h"

#ifdef HECT_WINDOWS_BUILD
#include <Windows.h>

static HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif

#include <iomanip>
#include <iostream>
#include <mutex>
#include <sstream>

namespace hect
{

static std::mutex _logMutex;

void log(LogLevel level, const std::string& message)
{
    static Timer timer;
    std::lock_guard<std::mutex> lock(_logMutex);

    // Calculate timestamp parts
    int64_t total = timer.elapsed().milliseconds();
    int64_t milliseconds = total % 1000;
    int64_t seconds = total / 1000 % 60;
    int64_t minutes = total / 1000 / 60 % 60;
    int64_t hours = total / 1000 / 60 / 60;

    // Format message with timestamp prepended
    std::stringstream ss;
    ss << std::setfill('0') << "[" << hours << ":"
       << std::setw(2) << minutes << ":"
       << std::setw(2) << seconds << ":"
       << std::setw(3) << milliseconds << "] "
       << message << std::endl;
    std::string formattedMessage = ss.str();

#ifdef HECT_WINDOWS_BUILD

#ifdef HECT_DEBUG_BUILD
    OutputDebugString(formattedMessage.c_str());
#endif

    // Set the color text color
    switch (level)
    {
    case LogLevel_Info:
        SetConsoleTextAttribute(stdOutHandle, 15);
        break;
    case LogLevel_Debug:
        SetConsoleTextAttribute(stdOutHandle, 7);
        break;
    case LogLevel_Warning:
        SetConsoleTextAttribute(stdOutHandle, 14);
        break;
    case LogLevel_Error:
        SetConsoleTextAttribute(stdOutHandle, 12);
        break;
    case LogLevel_Trace:
        SetConsoleTextAttribute(stdOutHandle, 8);
        break;
    }

    std::cout << formattedMessage;
    std::cout.flush();

    // Reset the console text color
    SetConsoleTextAttribute(stdOutHandle, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    // Show a message box when logging an error
    if (level == LogLevel_Error)
    {
        MessageBoxA(NULL, message.c_str(), "Error", MB_ICONHAND | MB_OK);
    }
#else
    (void)level;
    std::cout << formattedMessage;
    std::cout.flush();
#endif
}

}
<|endoftext|>


<commit_before>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2014 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)

#include <iostream>  // NO LINT
#include "ceres/callbacks.h"
#include "ceres/program.h"
#include "ceres/stringprintf.h"
#include "glog/logging.h"

namespace ceres {
namespace internal {

StateUpdatingCallback::StateUpdatingCallback(Program* program,
                                             double* parameters)
    : program_(program), parameters_(parameters) {}

StateUpdatingCallback::~StateUpdatingCallback() {}

CallbackReturnType StateUpdatingCallback::operator()(
    const IterationSummary& summary) {
  if (summary.step_is_successful) {
    program_->StateVectorToParameterBlocks(parameters_);
    program_->CopyParameterBlockStateToUserState();
  }
  return SOLVER_CONTINUE;
}

LoggingCallback::LoggingCallback(const MinimizerType minimizer_type,
                                 const bool log_to_stdout)
    : minimizer_type(minimizer_type),
      log_to_stdout_(log_to_stdout) {}

LoggingCallback::~LoggingCallback() {}

CallbackReturnType LoggingCallback::operator()(
    const IterationSummary& summary) {
  string output;
  if (minimizer_type == LINE_SEARCH) {
    const char* kReportRowFormat =
        "% 4d: f:% 8e d:% 3.2e g:% 3.2e h:% 3.2e "
        "s:% 3.2e e:% 3d it:% 3.2e tt:% 3.2e";
    output = StringPrintf(kReportRowFormat,
                          summary.iteration,
                          summary.cost,
                          summary.cost_change,
                          summary.gradient_max_norm,
                          summary.step_norm,
                          summary.step_size,
                          summary.line_search_function_evaluations,
                          summary.iteration_time_in_seconds,
                          summary.cumulative_time_in_seconds);
  } else if (minimizer_type == TRUST_REGION) {
    const char* kReportRowFormat =
        "% 4d: f:% 8e d:% 3.2e g:% 3.2e h:% 3.2e "
        "rho:% 3.2e mu:% 3.2e li:% 3d it:% 3.2e tt:% 3.2e";
    output = StringPrintf(kReportRowFormat,
                          summary.iteration,
                          summary.cost,
                          summary.cost_change,
                          summary.gradient_max_norm,
                          summary.step_norm,
                          summary.relative_decrease,
                          summary.trust_region_radius,
                          summary.linear_solver_iterations,
                          summary.iteration_time_in_seconds,
                          summary.cumulative_time_in_seconds);
  } else {
    LOG(FATAL) << "Unknown minimizer type.";
  }

  if (log_to_stdout_) {
    cout << output << endl;
  } else {
    VLOG(1) << output;
  }
  return SOLVER_CONTINUE;
}

}  // namespace internal
}  // namespace ceres
<commit_msg>Change logging for TRUST_REGION.<commit_after>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2014 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)

#include <iostream>  // NO LINT
#include "ceres/callbacks.h"
#include "ceres/program.h"
#include "ceres/stringprintf.h"
#include "glog/logging.h"

namespace ceres {
namespace internal {

StateUpdatingCallback::StateUpdatingCallback(Program* program,
                                             double* parameters)
    : program_(program), parameters_(parameters) {}

StateUpdatingCallback::~StateUpdatingCallback() {}

CallbackReturnType StateUpdatingCallback::operator()(
    const IterationSummary& summary) {
  if (summary.step_is_successful) {
    program_->StateVectorToParameterBlocks(parameters_);
    program_->CopyParameterBlockStateToUserState();
  }
  return SOLVER_CONTINUE;
}

LoggingCallback::LoggingCallback(const MinimizerType minimizer_type,
                                 const bool log_to_stdout)
    : minimizer_type(minimizer_type),
      log_to_stdout_(log_to_stdout) {}

LoggingCallback::~LoggingCallback() {}

CallbackReturnType LoggingCallback::operator()(
    const IterationSummary& summary) {
  string output;
  if (minimizer_type == LINE_SEARCH) {
    const char* kReportRowFormat =
        "% 4d: f:% 8e d:% 3.2e g:% 3.2e h:% 3.2e "
        "s:% 3.2e e:% 3d it:% 3.2e tt:% 3.2e";
    output = StringPrintf(kReportRowFormat,
                          summary.iteration,
                          summary.cost,
                          summary.cost_change,
                          summary.gradient_max_norm,
                          summary.step_norm,
                          summary.step_size,
                          summary.line_search_function_evaluations,
                          summary.iteration_time_in_seconds,
                          summary.cumulative_time_in_seconds);
  } else if (minimizer_type == TRUST_REGION) {
    if (summary.iteration == 0) {
      output = "iter      cost      cost_change  |gradient|   |step|    tr_ratio  tr_radius  ls_iter  iter_time  total_time\n";
    }
    const char* kReportRowFormat =
        "% 4d % 8e   % 3.2e   % 3.2e  % 3.2e  % 3.2e % 3.2e     % 3d   % 3.2e   % 3.2e";
    output += StringPrintf(kReportRowFormat,
                          summary.iteration,
                          summary.cost,
                          summary.cost_change,
                          summary.gradient_max_norm,
                          summary.step_norm,
                          summary.relative_decrease,
                          summary.trust_region_radius,
                          summary.linear_solver_iterations,
                          summary.iteration_time_in_seconds,
                          summary.cumulative_time_in_seconds);
  } else {
    LOG(FATAL) << "Unknown minimizer type.";
  }

  if (log_to_stdout_) {
    cout << output << endl;
  } else {
    VLOG(1) << output;
  }
  return SOLVER_CONTINUE;
}

}  // namespace internal
}  // namespace ceres
<|endoftext|>


<commit_before>#include "platform/i_platform.h"
#include "kill_score_on_death_system.h"
#include "core/i_kill_score_on_death_component.h"
#include "core/i_health_component.h"
#include "kill_score_event.h"
#include "kill_score_event.h"

namespace engine {

KillScoreOnDeathSystem::KillScoreOnDeathSystem()
    : mScene( Scene::Get() )
{
}

void KillScoreOnDeathSystem::Init()
{
}

void KillScoreOnDeathSystem::Update( double DeltaTime )
{
    for( ActorList_t::iterator it = mScene.GetActors().begin(), e = mScene.GetActors().end(); it != e; ++it )
    {
        Actor& actor = **it;
        Opt<IKillScoreOnDeathComponent> killScoreOnDeathC = actor.Get<IKillScoreOnDeathComponent>();
        if ( !killScoreOnDeathC.IsValid() )
        {
            continue;
        }
        Opt<IHealthComponent> healthC = actor.Get<IHealthComponent>();
        if ( !killScoreOnDeathC->IsScored() && healthC.IsValid() && !healthC->IsAlive() )
        {
            L1( "KillScoreOnDeath sent" );
            EventServer<KillScoreEvent>::Get().SendEvent( KillScoreEvent( healthC->GetLastDamageOwnerGUID(), actor.GetGUID() ) );
            killScoreOnDeathC->SetScored( true );
        }
    }
}

} // namespace engine

<commit_msg>remove duplicate include<commit_after>#include "platform/i_platform.h"
#include "kill_score_on_death_system.h"
#include "core/i_kill_score_on_death_component.h"
#include "core/i_health_component.h"
#include "kill_score_event.h"

namespace engine {

KillScoreOnDeathSystem::KillScoreOnDeathSystem()
    : mScene( Scene::Get() )
{
}

void KillScoreOnDeathSystem::Init()
{
}

void KillScoreOnDeathSystem::Update( double DeltaTime )
{
    for( ActorList_t::iterator it = mScene.GetActors().begin(), e = mScene.GetActors().end(); it != e; ++it )
    {
        Actor& actor = **it;
        Opt<IKillScoreOnDeathComponent> killScoreOnDeathC = actor.Get<IKillScoreOnDeathComponent>();
        if ( !killScoreOnDeathC.IsValid() )
        {
            continue;
        }
        Opt<IHealthComponent> healthC = actor.Get<IHealthComponent>();
        if ( !killScoreOnDeathC->IsScored() && healthC.IsValid() && !healthC->IsAlive() )
        {
            L1( "KillScoreOnDeath sent" );
            EventServer<KillScoreEvent>::Get().SendEvent( KillScoreEvent( healthC->GetLastDamageOwnerGUID(), actor.GetGUID() ) );
            killScoreOnDeathC->SetScored( true );
        }
    }
}

} // namespace engine

<|endoftext|>


<commit_before>#include <chrono>
#include <vector>
#include <initializer_list>

#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cassert>

class bitvector {

    const size_t n;
    uint64_t* array;

public:
    bitvector(size_t n_) : n(n_) {
        assert(n > 0);
        array = new uint64_t[n];
    }

    ~bitvector() {
        delete[] array;
    }

    void fill(uint64_t word) {
        for (size_t i=0; i < n; i++)
            array[i] = word;
    }

    void fill_random(int threshold) {
        assert(threshold >= 0);
        assert(threshold <= 100);

        srand(0);
        for (size_t i=0; i < n; i++) {
            if ((rand() % 100) > threshold) {
                array[i] = -1;
            } else {
                array[i] = 0;
            }
        }
    }

    size_t size() const {
        return n * 64;
    }

    size_t cardinality() const {
        size_t k = 0;
        for (size_t i=0; i < n; i++) {
            k += __builtin_popcountll(array[i]);
        }

        return k;
    }

public:
    template <typename CALLBACK>
    void iterate_naive(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                if (tmp & 0x1) {
                    callback(k);
                }

                tmp >>= 1;
                k += 1;
            }
        }
    }

    template <typename CALLBACK>
    void iterate_better(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                const uint64_t t = tmp & (~tmp + 1);
                const uint64_t r = __builtin_ctzll(t);
                callback(k + r);
                tmp ^= t;
            }
        }
    }

    template <typename CALLBACK>
    void iterate_block3(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                switch (tmp & 0x7) {
                    case 0:
                        break;

                    case 1:
                        callback(k);
                        break;

                    case 2:
                        callback(k + 1);
                        break;

                    case 3:
                        callback(k);
                        callback(k + 1);
                        break;

                    case 4:
                        callback(k + 2);
                        break;

                    case 5:
                        callback(k);
                        callback(k + 2);
                        break;

                    case 6:
                        callback(k + 1);
                        callback(k + 2);
                        break;

                    case 7:
                        callback(k);
                        callback(k + 1);
                        callback(k + 2);
                        break;
                }

                tmp >>= 3;
                k += 3;
            }
        }
    }

    template <typename CALLBACK>
    void iterate_block4(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                switch (tmp & 0xf) {
                    case 0:
                        break;

                    case 1:
                        callback(k);
                        break;

                    case 2:
                        callback(k + 1);
                        break;

                    case 3:
                        callback(k);
                        callback(k + 1);
                        break;

                    case 4:
                        callback(k + 2);
                        break;

                    case 5:
                        callback(k);
                        callback(k + 2);
                        break;

                    case 6:
                        callback(k + 1);
                        callback(k + 2);
                        break;

                    case 7:
                        callback(k);
                        callback(k + 1);
                        callback(k + 2);
                        break;

                    case 8:
                        callback(k + 3);
                        break;

                    case 9:
                        callback(k);
                        callback(k + 3);
                        break;

                    case 10:
                        callback(k + 1);
                        callback(k + 3);
                        break;

                    case 11:
                        callback(k);
                        callback(k + 1);
                        callback(k + 3);
                        break;

                    case 12:
                        callback(k + 2);
                        callback(k + 3);
                        break;

                    case 13:
                        callback(k);
                        callback(k + 2);
                        callback(k + 3);
                        break;

                    case 14:
                        callback(k + 1);
                        callback(k + 2);
                        callback(k + 3);
                        break;

                    case 15:
                        callback(k);
                        callback(k + 1);
                        callback(k + 2);
                        callback(k + 3);
                        break;
                }

                tmp >>= 4;
                k += 4;
            }
        }
    }
};

void testcase(const bitvector& bv, int iterations) {
    using clock = std::chrono::high_resolution_clock;
    using std::chrono::duration_cast;
    using std::chrono::microseconds;

    uint64_t ta;
    uint64_t tb;

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_naive(callback);
            k += n;
        }
        const auto t2 = clock::now();

        ta = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tnaive:  %10ldms [%ld]\n", ta, k);
    }

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_better(callback);
            k += n;
        }
        const auto t2 = clock::now();

        tb = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tbetter: %10ldms [%ld]", tb, k);
        printf(" (%0.2f)\n", ta/double(tb));
    }

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_block3(callback);
            k += n;
        }
        const auto t2 = clock::now();

        tb = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tblock3: %10ldms [%ld]", tb, k);
        printf(" (%0.2f)\n", ta/double(tb));
    }

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_block4(callback);
            k += n;
        }
        const auto t2 = clock::now();

        tb = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tblock4: %10ldms [%ld]", tb, k);
        printf(" (%0.2f)\n", ta/double(tb));
    }
}

template <typename INITIALIZER>
void test(const char* info, const std::vector<size_t>& sizes, int iterations, INITIALIZER initalizer) {

    bool print = true;
    for (size_t i: sizes) {
        bitvector bv(i);
        initalizer(bv);
        if (print) {
            printf("%s\n", info);
            print = false;
        }
        printf("\tsize=%lu, cardinality=%lu\n", bv.size(), bv.cardinality());

        testcase(bv, iterations);
    }
}

int main() {

    const std::vector<size_t> sizes = {64, 256, 1024, 4096, 8192};

    test("empty", sizes, 10000, [](bitvector& bv) {bv.fill(0);});
    test("1/4",   sizes,  1000, [](bitvector& bv) {bv.fill(0x000000000000ffff);});
    test("1/2",   sizes,  1000, [](bitvector& bv) {bv.fill(0x00000000ffffffff);});
    test("3/4",   sizes,  1000, [](bitvector& bv) {bv.fill(0x0000ffffffffffff);});
    test("full",  sizes,  1000, [](bitvector& bv) {bv.fill(0xffffffffffffffff);});
    test("rand",  sizes,  1000, [](bitvector& bv) {bv.fill_random(80);});
    test("rand2", sizes,  1000, [](bitvector& bv) {bv.fill_random(5);});
    return 0;
}

<commit_msg>Fix the displayed time unit<commit_after>#include <chrono>
#include <vector>
#include <initializer_list>

#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cassert>

class bitvector {

    const size_t n;
    uint64_t* array;

public:
    bitvector(size_t n_) : n(n_) {
        assert(n > 0);
        array = new uint64_t[n];
    }

    ~bitvector() {
        delete[] array;
    }

    void fill(uint64_t word) {
        for (size_t i=0; i < n; i++)
            array[i] = word;
    }

    void fill_random(int threshold) {
        assert(threshold >= 0);
        assert(threshold <= 100);

        srand(0);
        for (size_t i=0; i < n; i++) {
            if ((rand() % 100) > threshold) {
                array[i] = -1;
            } else {
                array[i] = 0;
            }
        }
    }

    size_t size() const {
        return n * 64;
    }

    size_t cardinality() const {
        size_t k = 0;
        for (size_t i=0; i < n; i++) {
            k += __builtin_popcountll(array[i]);
        }

        return k;
    }

public:
    template <typename CALLBACK>
    void iterate_naive(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                if (tmp & 0x1) {
                    callback(k);
                }

                tmp >>= 1;
                k += 1;
            }
        }
    }

    template <typename CALLBACK>
    void iterate_better(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                const uint64_t t = tmp & (~tmp + 1);
                const uint64_t r = __builtin_ctzll(t);
                callback(k + r);
                tmp ^= t;
            }
        }
    }

    template <typename CALLBACK>
    void iterate_block3(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                switch (tmp & 0x7) {
                    case 0:
                        break;

                    case 1:
                        callback(k);
                        break;

                    case 2:
                        callback(k + 1);
                        break;

                    case 3:
                        callback(k);
                        callback(k + 1);
                        break;

                    case 4:
                        callback(k + 2);
                        break;

                    case 5:
                        callback(k);
                        callback(k + 2);
                        break;

                    case 6:
                        callback(k + 1);
                        callback(k + 2);
                        break;

                    case 7:
                        callback(k);
                        callback(k + 1);
                        callback(k + 2);
                        break;
                }

                tmp >>= 3;
                k += 3;
            }
        }
    }

    template <typename CALLBACK>
    void iterate_block4(CALLBACK callback) const {
        for (size_t i=0; i < n; i++) {
            uint64_t tmp = array[i];

            size_t k = i * 64;
            while (tmp) {
                switch (tmp & 0xf) {
                    case 0:
                        break;

                    case 1:
                        callback(k);
                        break;

                    case 2:
                        callback(k + 1);
                        break;

                    case 3:
                        callback(k);
                        callback(k + 1);
                        break;

                    case 4:
                        callback(k + 2);
                        break;

                    case 5:
                        callback(k);
                        callback(k + 2);
                        break;

                    case 6:
                        callback(k + 1);
                        callback(k + 2);
                        break;

                    case 7:
                        callback(k);
                        callback(k + 1);
                        callback(k + 2);
                        break;

                    case 8:
                        callback(k + 3);
                        break;

                    case 9:
                        callback(k);
                        callback(k + 3);
                        break;

                    case 10:
                        callback(k + 1);
                        callback(k + 3);
                        break;

                    case 11:
                        callback(k);
                        callback(k + 1);
                        callback(k + 3);
                        break;

                    case 12:
                        callback(k + 2);
                        callback(k + 3);
                        break;

                    case 13:
                        callback(k);
                        callback(k + 2);
                        callback(k + 3);
                        break;

                    case 14:
                        callback(k + 1);
                        callback(k + 2);
                        callback(k + 3);
                        break;

                    case 15:
                        callback(k);
                        callback(k + 1);
                        callback(k + 2);
                        callback(k + 3);
                        break;
                }

                tmp >>= 4;
                k += 4;
            }
        }
    }
};

void testcase(const bitvector& bv, int iterations) {
    using clock = std::chrono::high_resolution_clock;
    using std::chrono::duration_cast;
    using std::chrono::microseconds;

    uint64_t ta;
    uint64_t tb;

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_naive(callback);
            k += n;
        }
        const auto t2 = clock::now();

        ta = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tnaive:  %10ld us [%ld]\n", ta, k);
    }

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_better(callback);
            k += n;
        }
        const auto t2 = clock::now();

        tb = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tbetter: %10ld us [%ld]", tb, k);
        printf(" (%0.2f)\n", ta/double(tb));
    }

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_block3(callback);
            k += n;
        }
        const auto t2 = clock::now();

        tb = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tblock3: %10ld us [%ld]", tb, k);
        printf(" (%0.2f)\n", ta/double(tb));
    }

    {
        int tmp = iterations;
        volatile uint64_t k = 0;

        const auto t1 = clock::now();
        while (tmp--) {
            uint64_t n = 0;
            auto callback = [&n](size_t i) {
                n += i;
            };

            bv.iterate_block4(callback);
            k += n;
        }
        const auto t2 = clock::now();

        tb = duration_cast<microseconds>(t2 - t1).count();
        printf("\t\tblock4: %10ld us [%ld]", tb, k);
        printf(" (%0.2f)\n", ta/double(tb));
    }
}

template <typename INITIALIZER>
void test(const char* info, const std::vector<size_t>& sizes, int iterations, INITIALIZER initalizer) {

    bool print = true;
    for (size_t i: sizes) {
        bitvector bv(i);
        initalizer(bv);
        if (print) {
            printf("%s\n", info);
            print = false;
        }
        printf("\tsize=%lu, cardinality=%lu\n", bv.size(), bv.cardinality());

        testcase(bv, iterations);
    }
}

int main() {

    const std::vector<size_t> sizes = {64, 256, 1024, 4096, 8192};

    test("empty", sizes, 10000, [](bitvector& bv) {bv.fill(0);});
    test("1/4",   sizes,  1000, [](bitvector& bv) {bv.fill(0x000000000000ffff);});
    test("1/2",   sizes,  1000, [](bitvector& bv) {bv.fill(0x00000000ffffffff);});
    test("3/4",   sizes,  1000, [](bitvector& bv) {bv.fill(0x0000ffffffffffff);});
    test("full",  sizes,  1000, [](bitvector& bv) {bv.fill(0xffffffffffffffff);});
    test("rand",  sizes,  1000, [](bitvector& bv) {bv.fill_random(80);});
    test("rand2", sizes,  1000, [](bitvector& bv) {bv.fill_random(5);});
    return 0;
}

<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "ros_pi/Rpi_car.h"
#include <wiringPi.h>
#include <softPwm.h>

/*
	define the io pins
	M1: fwd/backwd
	M2: steering
*/
//use BCM numbers for code, and wiringPi for export in the setup  sh
//wiringPi pin 7 == BCM_GPIO 4
#define	M1_A 7
//wiringPi pin 1 == BCM_GPIO 18
#define M1_B 1

//wiringPi pin 3 == BCM_GPIO 22
#define M2_A 3
//wiringPi pin 4 == BCM_GPIO 23
#define M2_B  4

//enable pin of the engine
//wiringPi pin 0 == BCM_GPIO 17
#define M1_E 0
//wiringPi pin 6 == BCM_GPIO 25
#define M2_E 6

//amount of gears/pwm levels
#define TOP_SPEED 100
//full stop at gear
#define FULLSTOP 25

int direction, speed;
bool accelerate, brake, lights;

/// ===============================
void honk() {
    //honk
}

/// ===============================
bool plan(ros_pi::Rpi_car::Request  &req,
         ros_pi::Rpi_car::Response &res)
{
    switch(req.mode) {
    case -4: ///un-brake
    {
        brake = false;
        break;}
    case -3: ///un-accelerate
    {
        accelerate = false;
        break;}
    case -2: ///un-right
    {
        direction = 0;
        break;}
    case -1: ///un-left
    {
        direction = 0;
        break;}
    case 1: ///left
    {
        direction = 1;
        break;}
    case 2: ///right
    {
        direction = -1;
        break;}
    case 3: ///accelerate
    {
        accelerate = true;
        break;}
    case 4: ///brake
    {
        brake = true;
        break;}
    /// ############ ///
    default:
    {
        return false;
        break;}
    }
    return true;
}

/// ===============================
int main(int argc, char **argv)
{
    direction = 0;
    speed = FULLSTOP;
    accelerate = false;

    wiringPiSetup();
    pinMode (M1_A, OUTPUT);
    pinMode (M1_B, OUTPUT);
    pinMode (M2_A, OUTPUT);
    pinMode (M2_B, OUTPUT);
    //pin,initVal,pwmRange
    softPwmCreate (M1_E, 0, TOP_SPEED);
    softPwmCreate (M2_E, 0, 100) ;

    //init pins
    digitalWrite(M1_A, LOW);
    digitalWrite(M1_B, LOW);
    digitalWrite(M2_A, LOW);
    digitalWrite(M2_B, LOW);
    softPwmWrite (M1_E, 0);
    softPwmWrite (M2_E, 0);

    ros::init(argc, argv, "car_service");
    ros::NodeHandle n;

    ros::ServiceServer service = n.advertiseService("/car_service", plan);

    while(ros::ok()) {
        if(speed < TOP_SPEED && accelerate == true) {
            speed++;
        }
        if (speed > 0 && brake) {
            //braking added to rollout and backwards
            speed--;
        }
        if (speed > FULLSTOP && !accelerate) {
            //rollout till fullstop
            speed--;
        }
	if (speed < FULLSTOP && !brake) {
	    //rollout braking
	    speed++;
	}
	//write pwm speed
	softPwmWrite(M1_E, abs(speed-FULLSTOP));

	if(speed >= FULLSTOP) {
	    //forward
	    digitalWrite(M1_A, LOW);
	    digitalWrite(M1_B, HIGH);
	} else {
	    //backward
	    digitalWrite(M1_B, LOW);
	    digitalWrite(M1_A, HIGH);
	}

        if(direction != 0) {
            if(direction == 1) {
                //ROS_INFO("go left");
            } else {
                //ROS_INFO("go right");
            }
        } else {

	}

        ros::Duration(0.25).sleep();
        ros::spinOnce();
    }

    service.shutdown();

    return 0;
}
<commit_msg>Added code to skip low pwm levels which don't move the motor.<commit_after>#include "ros/ros.h"
#include "ros_pi/Rpi_car.h"
#include <wiringPi.h>
#include <softPwm.h>

/*
	define the io pins
	M1: fwd/backwd
	M2: steering
*/
//use BCM numbers for code, and wiringPi for export in the setup  sh
//wiringPi pin 7 == BCM_GPIO 4
#define	M1_A 7
//wiringPi pin 1 == BCM_GPIO 18
#define M1_B 1

//wiringPi pin 3 == BCM_GPIO 22
#define M2_A 3
//wiringPi pin 4 == BCM_GPIO 23
#define M2_B  4

//enable pin of the engine
//wiringPi pin 0 == BCM_GPIO 17
#define M1_E 0
//wiringPi pin 6 == BCM_GPIO 25
#define M2_E 6

//amount of gears/pwm levels
#define TOP_SPEED 30
//full stop at gear
#define FULLSTOP 10

int direction, speed;
bool accelerate, brake, lights;

/// ===============================
void honk() {
    //honk
}

/// ===============================
bool plan(ros_pi::Rpi_car::Request  &req,
         ros_pi::Rpi_car::Response &res)
{
    switch(req.mode) {
    case -4: ///un-brake
    {
        brake = false;
        break;}
    case -3: ///un-accelerate
    {
        accelerate = false;
        break;}
    case -2: ///un-right
    {
        direction = 0;
        break;}
    case -1: ///un-left
    {
        direction = 0;
        break;}
    case 1: ///left
    {
        direction = 1;
        break;}
    case 2: ///right
    {
        direction = -1;
        break;}
    case 3: ///accelerate
    {
	speed += 10;
        accelerate = true;
        break;}
    case 4: ///brake
    {
	speed -= 5;
        brake = true;
        break;}
    /// ############ ///
    default:
    {
        return false;
        break;}
    }
    return true;
}

/// ===============================
int main(int argc, char **argv)
{
    direction = 0;
    speed = FULLSTOP;
    accelerate = false;

    wiringPiSetup();
    pinMode (M1_A, OUTPUT);
    pinMode (M1_B, OUTPUT);
    pinMode (M2_A, OUTPUT);
    pinMode (M2_B, OUTPUT);
    //pin,initVal,pwmRange
    softPwmCreate (M1_E, 0, TOP_SPEED);
    softPwmCreate (M2_E, 0, 100) ;

    //init pins
    digitalWrite(M1_A, LOW);
    digitalWrite(M1_B, LOW);
    digitalWrite(M2_A, LOW);
    digitalWrite(M2_B, LOW);
    softPwmWrite (M1_E, 0);
    softPwmWrite (M2_E, 0);

    ros::init(argc, argv, "car_service");
    ros::NodeHandle n;

    ros::ServiceServer service = n.advertiseService("/car_service", plan);

    while(ros::ok()) {
        if(speed < TOP_SPEED && accelerate == true) {
/*		if(speed = FULLSTOP) {
			//skip low pwm levels
			speed =speed+7;
		} else {
            		speed++;
		}*/
	    speed++;

        }
        if (speed > 0 && brake) {
            //braking added to rollout and backwards
             /* if(speed = FULLSTOP) {
                        //skip low pwm levels
                        speed -=(int)0.1*TOP_SPEED;
                } else {
                        speed--;
                }*/
	    speed--;
        }
        if (speed > FULLSTOP && !accelerate) {
            //rollout till fullstop
            speed--;
        }
	if (speed < FULLSTOP && !brake) {
	    //rollout braking
	    speed++;
	}

	if(speed >= FULLSTOP) {
	    //forward
	    digitalWrite(M1_A, LOW);
	    digitalWrite(M1_B, HIGH);
	} else {
	    //backward
	    digitalWrite(M1_B, LOW);
	    digitalWrite(M1_A, HIGH);
	}
	//write pwm speed
	softPwmWrite(M1_E, abs(speed-FULLSTOP));

        if(direction != 0) {
            if(direction == 1) {
                //ROS_INFO("go left");
            } else {
                //ROS_INFO("go right");
            }
        } else {

	}

        ros::Duration(0.25).sleep();
        ros::spinOnce();
    }

    service.shutdown();

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sstream>
#include <string>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_failed_dns_job.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class ResourceDispatcherTest : public UITest {
 public:
  void CheckTitleTest(const std::wstring& file,
                      const std::wstring& expected_title) {
    NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
    const int kCheckDelayMs = 100;
    int max_wait_time = 5000;
    while (max_wait_time > 0) {
      max_wait_time -= kCheckDelayMs;
      PlatformThread::Sleep(kCheckDelayMs);
      if (expected_title == GetActiveTabTitle())
        break;
    }

    EXPECT_EQ(expected_title, GetActiveTabTitle());
  }

 protected:
  ResourceDispatcherTest() : UITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}

TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
  CheckTitleTest(L"nosniff-test.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
  CheckTitleTest(L"content-sniffer-test1.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
  CheckTitleTest(L"content-sniffer-test2.html", L"");
}

TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
  CheckTitleTest(L"content-sniffer-test3.html",
                 L"Content Sniffer Test 3");
  PlatformThread::Sleep(sleep_timeout_ms() * 2);
  EXPECT_EQ(1, GetTabCount());

  // Make sure the download shelf is not showing.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  bool visible = false;
  ASSERT_TRUE(browser->IsShelfVisible(&visible));
  EXPECT_FALSE(visible);
}

TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
  CheckTitleTest(L"content-disposition-empty.html", L"success");
}

TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
  CheckTitleTest(L"content-disposition-inline.html", L"success");
}

// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSyncRequestSucceed());",
      &success));
  EXPECT_TRUE(success);
}

TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest_disallowed.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSucceed());",
      &success));
  EXPECT_TRUE(success);
}

// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  tab->NavigateToURL(
      server->TestServerPageW(L"files/sync_xmlhttprequest_during_unload.html"));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"sync xhr on unload", tab_title);

  // Navigate to a new page, to dispatch unload event and trigger xhr.
  // (the bug would make this step hang the renderer).
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(server->TestServerPageW(L"files/title2.html"),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);

  // Check that the new page got loaded, and that no download was triggered.
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);

  bool shelf_is_visible = false;
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
  EXPECT_FALSE(shelf_is_visible);
}

// Tests that onunload is run for cross-site requests.  (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site page, to dispatch unload event and set the
  // cookie.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Check that the cookie was set.
  std::string value_result;
  ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  ASSERT_FALSE(value_result.empty());
  ASSERT_STREQ("foo", value_result.c_str());
}

#if !defined(OS_MAC)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone.  In that case, we don't want to wait for the old renderer
// to run the handlers.
// TODO(pinkerton): We need to disable this because the crash causes
// the OS CrashReporter process to kick in to analyze the poor dead renderer.
// Unfortunately, if the app isn't stripped of debug symbols, this takes about
// five minutes to complete and isn't conducive to quick turnarounds. As we
// don't currently strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Cause the renderer to crash.
  // TODO(albertb): We need to disable this on Linux since
  // crash_service.exe hasn't been ported yet.
#if defined(OS_WIN)
  expected_crashes_ = 1;
#endif
  tab->NavigateToURLAsync(GURL("about:crash"));
  // Wait for browser to notice the renderer crash.
  PlatformThread::Sleep(sleep_timeout_ms());

  // Navigate to a new cross-site page.  The browser should not wait around for
  // the old renderer's on{before}unload handlers to run.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}
#endif

// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs).  (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Start with an HTTP page.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Now load a file:// page, which does not use the BufferedEventHandler.
  // Make sure that the page loads and displays a title, and doesn't get stuck.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("title2.html");
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);
  EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}

// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page.  (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site URL that results in an error page.  We must
  // wait for the error page to update the title.
  // TODO(creis): If this causes crashes or hangs, it might be for the same
  // reason as ErrorPageTest::DNSError.  See bug 1199491.
  tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));
  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    if (GetActiveTabTitle() != L"set cookie on unload") {
      // Success, bail out.
      break;
    }
  }
  EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());

  // Check that the cookie was set, meaning that the onunload handler ran.
  std::string value_result;
  EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  EXPECT_FALSE(value_result.empty());
  EXPECT_STREQ("foo", value_result.c_str());

  // Check that renderer-initiated navigations still work.  In a previous bug,
  // the ResourceDispatcherHost would think that such navigations were
  // cross-site, because we didn't clean up from the previous request.  Since
  // TabContents was in the NORMAL state, it would ignore the attempt to run
  // the onunload handler, and the navigation would fail.
  // (Test by redirecting to javascript:window.location='someURL'.)
  GURL test_url(server->TestServerPageW(L"files/title2.html"));
  std::string redirect_url = "javascript:window.location='" +
      test_url.possibly_invalid_spec() + "'";
  tab->NavigateToURLAsync(GURL(redirect_url));
  // Wait for JavaScript redirect to happen.
  PlatformThread::Sleep(sleep_timeout_ms() * 3);
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}

}  // namespace
<commit_msg>s/OS_MAC/OS_MACOSX/<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sstream>
#include <string>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_failed_dns_job.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class ResourceDispatcherTest : public UITest {
 public:
  void CheckTitleTest(const std::wstring& file,
                      const std::wstring& expected_title) {
    NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
    const int kCheckDelayMs = 100;
    int max_wait_time = 5000;
    while (max_wait_time > 0) {
      max_wait_time -= kCheckDelayMs;
      PlatformThread::Sleep(kCheckDelayMs);
      if (expected_title == GetActiveTabTitle())
        break;
    }

    EXPECT_EQ(expected_title, GetActiveTabTitle());
  }

 protected:
  ResourceDispatcherTest() : UITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}

TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
  CheckTitleTest(L"nosniff-test.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
  CheckTitleTest(L"content-sniffer-test1.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
  CheckTitleTest(L"content-sniffer-test2.html", L"");
}

TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
  CheckTitleTest(L"content-sniffer-test3.html",
                 L"Content Sniffer Test 3");
  PlatformThread::Sleep(sleep_timeout_ms() * 2);
  EXPECT_EQ(1, GetTabCount());

  // Make sure the download shelf is not showing.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  bool visible = false;
  ASSERT_TRUE(browser->IsShelfVisible(&visible));
  EXPECT_FALSE(visible);
}

TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
  CheckTitleTest(L"content-disposition-empty.html", L"success");
}

TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
  CheckTitleTest(L"content-disposition-inline.html", L"success");
}

// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSyncRequestSucceed());",
      &success));
  EXPECT_TRUE(success);
}

TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest_disallowed.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSucceed());",
      &success));
  EXPECT_TRUE(success);
}

// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  tab->NavigateToURL(
      server->TestServerPageW(L"files/sync_xmlhttprequest_during_unload.html"));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"sync xhr on unload", tab_title);

  // Navigate to a new page, to dispatch unload event and trigger xhr.
  // (the bug would make this step hang the renderer).
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(server->TestServerPageW(L"files/title2.html"),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);

  // Check that the new page got loaded, and that no download was triggered.
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);

  bool shelf_is_visible = false;
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
  EXPECT_FALSE(shelf_is_visible);
}

// Tests that onunload is run for cross-site requests.  (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site page, to dispatch unload event and set the
  // cookie.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Check that the cookie was set.
  std::string value_result;
  ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  ASSERT_FALSE(value_result.empty());
  ASSERT_STREQ("foo", value_result.c_str());
}

#if !defined(OS_MACOSX)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone.  In that case, we don't want to wait for the old renderer
// to run the handlers.
// TODO(pinkerton): We need to disable this because the crash causes
// the OS CrashReporter process to kick in to analyze the poor dead renderer.
// Unfortunately, if the app isn't stripped of debug symbols, this takes about
// five minutes to complete and isn't conducive to quick turnarounds. As we
// don't currently strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Cause the renderer to crash.
  // TODO(albertb): We need to disable this on Linux since
  // crash_service.exe hasn't been ported yet.
#if defined(OS_WIN)
  expected_crashes_ = 1;
#endif
  tab->NavigateToURLAsync(GURL("about:crash"));
  // Wait for browser to notice the renderer crash.
  PlatformThread::Sleep(sleep_timeout_ms());

  // Navigate to a new cross-site page.  The browser should not wait around for
  // the old renderer's on{before}unload handlers to run.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}
#endif  // !defined(OS_MACOSX)

// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs).  (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Start with an HTTP page.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Now load a file:// page, which does not use the BufferedEventHandler.
  // Make sure that the page loads and displays a title, and doesn't get stuck.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("title2.html");
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);
  EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}

// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page.  (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site URL that results in an error page.  We must
  // wait for the error page to update the title.
  // TODO(creis): If this causes crashes or hangs, it might be for the same
  // reason as ErrorPageTest::DNSError.  See bug 1199491.
  tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));
  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    if (GetActiveTabTitle() != L"set cookie on unload") {
      // Success, bail out.
      break;
    }
  }
  EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());

  // Check that the cookie was set, meaning that the onunload handler ran.
  std::string value_result;
  EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  EXPECT_FALSE(value_result.empty());
  EXPECT_STREQ("foo", value_result.c_str());

  // Check that renderer-initiated navigations still work.  In a previous bug,
  // the ResourceDispatcherHost would think that such navigations were
  // cross-site, because we didn't clean up from the previous request.  Since
  // TabContents was in the NORMAL state, it would ignore the attempt to run
  // the onunload handler, and the navigation would fail.
  // (Test by redirecting to javascript:window.location='someURL'.)
  GURL test_url(server->TestServerPageW(L"files/title2.html"));
  std::string redirect_url = "javascript:window.location='" +
      test_url.possibly_invalid_spec() + "'";
  tab->NavigateToURLAsync(GURL(redirect_url));
  // Wait for JavaScript redirect to happen.
  PlatformThread::Sleep(sleep_timeout_ms() * 3);
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}

}  // namespace
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrTextureDomainEffect.h"
#include "gl/GrGLProgramStage.h"
#include "GrProgramStageFactory.h"

class GrGLTextureDomainEffect : public GrGLProgramStage {
public:
    GrGLTextureDomainEffect(const GrProgramStageFactory& factory,
                            const GrCustomStage& stage);

    virtual void setupVariables(GrGLShaderBuilder* state,
                                int stage) SK_OVERRIDE;
    virtual void emitVS(GrGLShaderBuilder* state,
                        const char* vertexCoords) SK_OVERRIDE { }
    virtual void emitFS(GrGLShaderBuilder* state,
                        const char* outputColor,
                        const char* inputColor,
                        const char* samplerName) SK_OVERRIDE;

    virtual void initUniforms(const GrGLInterface*, int programID) SK_OVERRIDE;

    virtual void setData(const GrGLInterface*,
                         const GrCustomStage&,
                         const GrRenderTarget*,
                         int stageNum) SK_OVERRIDE;

    static inline StageKey GenKey(const GrCustomStage&) { return 0; }

private:
    const GrGLShaderVar* fNameVar;
    int                  fNameLocation;

    typedef GrGLProgramStage INHERITED;
};

GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrProgramStageFactory& factory,
                                                 const GrCustomStage& stage)
    : GrGLProgramStage(factory)
    , fNameVar(NULL)
    , fNameLocation(0) {
}

void GrGLTextureDomainEffect::setupVariables(GrGLShaderBuilder* state,
                                             int stage) {
    fNameVar = &state->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
                                  kVec4f_GrSLType, "uTexDom", stage);
    fNameLocation = kUseUniform;
};

void GrGLTextureDomainEffect::emitFS(GrGLShaderBuilder* state,
                                     const char* outputColor,
                                     const char* inputColor,
                                     const char* samplerName) {
    SkString coordVar("clampCoord");
    state->fFSCode.appendf("\t%s %s = clamp(%s, %s.xy, %s.zw);\n",
                           GrGLShaderVar::TypeString(GrSLFloatVectorType(state->fCoordDims)),
                           coordVar.c_str(),
                           state->fSampleCoords.c_str(),
                           fNameVar->getName().c_str(),
                           fNameVar->getName().c_str());
    state->fSampleCoords = coordVar;

    state->emitDefaultFetch(outputColor, samplerName);
}

void GrGLTextureDomainEffect::initUniforms(const GrGLInterface* gl, int programID) {
    GR_GL_CALL_RET(gl, fNameLocation,
                   GetUniformLocation(programID, fNameVar->getName().c_str()));
    GrAssert(kUnusedUniform != fNameLocation);
}

void GrGLTextureDomainEffect::setData(const GrGLInterface* gl,
                         const GrCustomStage& data,
                         const GrRenderTarget*,
                         int stageNum) {
    const GrTextureDomainEffect& effect = static_cast<const GrTextureDomainEffect&>(data);
    const GrRect& domain = effect.domain();

    float values[4] = {
        GrScalarToFloat(domain.left()),
        GrScalarToFloat(domain.top()),
        GrScalarToFloat(domain.right()),
        GrScalarToFloat(domain.bottom())
    };
    // vertical flip if necessary
    const GrGLTexture* texture = static_cast<const GrGLTexture*>(effect.texture(0));
    if (GrGLTexture::kBottomUp_Orientation == texture->orientation()) {
        values[1] = 1.0f - values[1];
        values[3] = 1.0f - values[3];
        // The top and bottom were just flipped, so correct the ordering
        // of elements so that values = (l, t, r, b).
        SkTSwap(values[1], values[3]);
    }

    GR_GL_CALL(gl, Uniform4fv(fNameLocation, 1, values));
}

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

GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture, GrRect domain)
    : GrSingleTextureEffect(texture)
    , fTextureDomain(domain) {

}

GrTextureDomainEffect::~GrTextureDomainEffect() {

}

const GrProgramStageFactory& GrTextureDomainEffect::getFactory() const {
    return GrTProgramStageFactory<GrTextureDomainEffect>::getInstance();
}

bool GrTextureDomainEffect::isEqual(const GrCustomStage& sBase) const {
    const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);
    return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);
}

<commit_msg>Fix build breakage in r4641. Unreviewed.<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrTextureDomainEffect.h"
#include "gl/GrGLProgramStage.h"
#include "GrProgramStageFactory.h"

// For brevity, and these definitions are likely to move to a different class soon.
typedef GrGLShaderBuilder::UniformHandle UniformHandle;
static const UniformHandle kInvalidUniformHandle = GrGLShaderBuilder::kInvalidUniformHandle;

class GrGLTextureDomainEffect : public GrGLProgramStage {
public:
    GrGLTextureDomainEffect(const GrProgramStageFactory& factory,
                            const GrCustomStage& stage);

    virtual void setupVariables(GrGLShaderBuilder* builder,
                                int stage) SK_OVERRIDE;
    virtual void emitVS(GrGLShaderBuilder* builder,
                        const char* vertexCoords) SK_OVERRIDE { }
    virtual void emitFS(GrGLShaderBuilder* builder,
                        const char* outputColor,
                        const char* inputColor,
                        const char* samplerName) SK_OVERRIDE;

    virtual void initUniforms(const GrGLShaderBuilder* builder,
                              const GrGLInterface*,
                              int programID) SK_OVERRIDE;

    virtual void setData(const GrGLInterface*,
                         const GrCustomStage&,
                         const GrRenderTarget*,
                         int stageNum) SK_OVERRIDE;

    static inline StageKey GenKey(const GrCustomStage&) { return 0; }

private:
    UniformHandle fNameUni;
    int           fNameLocation;

    typedef GrGLProgramStage INHERITED;
};

GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrProgramStageFactory& factory,
                                                 const GrCustomStage& stage)
    : GrGLProgramStage(factory)
    , fNameUni(kInvalidUniformHandle)
    , fNameLocation(0) {
}

void GrGLTextureDomainEffect::setupVariables(GrGLShaderBuilder* builder,
                                             int stage) {
    fNameUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
                                   kVec4f_GrSLType, "uTexDom", stage);
    fNameLocation = kUseUniform;
};

void GrGLTextureDomainEffect::emitFS(GrGLShaderBuilder* builder,
                                     const char* outputColor,
                                     const char* inputColor,
                                     const char* samplerName) {
    SkString coordVar("clampCoord");
    builder->fFSCode.appendf("\t%s %s = clamp(%s, %s.xy, %s.zw);\n",
                           GrGLShaderVar::TypeString(GrSLFloatVectorType(builder->fCoordDims)),
                           coordVar.c_str(),
                           builder->fSampleCoords.c_str(),
                           builder->getUniformCStr(fNameUni),
                           builder->getUniformCStr(fNameUni));
    builder->fSampleCoords = coordVar;

    builder->emitDefaultFetch(outputColor, samplerName);
}

void GrGLTextureDomainEffect::initUniforms(const GrGLShaderBuilder* builder,
                                           const GrGLInterface* gl, int programID) {
    GR_GL_CALL_RET(gl, fNameLocation,
                   GetUniformLocation(programID, builder->getUniformCStr(fNameUni)));
    GrAssert(kUnusedUniform != fNameLocation);
}

void GrGLTextureDomainEffect::setData(const GrGLInterface* gl,
                         const GrCustomStage& data,
                         const GrRenderTarget*,
                         int stageNum) {
    const GrTextureDomainEffect& effect = static_cast<const GrTextureDomainEffect&>(data);
    const GrRect& domain = effect.domain();

    float values[4] = {
        GrScalarToFloat(domain.left()),
        GrScalarToFloat(domain.top()),
        GrScalarToFloat(domain.right()),
        GrScalarToFloat(domain.bottom())
    };
    // vertical flip if necessary
    const GrGLTexture* texture = static_cast<const GrGLTexture*>(effect.texture(0));
    if (GrGLTexture::kBottomUp_Orientation == texture->orientation()) {
        values[1] = 1.0f - values[1];
        values[3] = 1.0f - values[3];
        // The top and bottom were just flipped, so correct the ordering
        // of elements so that values = (l, t, r, b).
        SkTSwap(values[1], values[3]);
    }

    GR_GL_CALL(gl, Uniform4fv(fNameLocation, 1, values));
}

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

GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture, GrRect domain)
    : GrSingleTextureEffect(texture)
    , fTextureDomain(domain) {

}

GrTextureDomainEffect::~GrTextureDomainEffect() {

}

const GrProgramStageFactory& GrTextureDomainEffect::getFactory() const {
    return GrTProgramStageFactory<GrTextureDomainEffect>::getInstance();
}

bool GrTextureDomainEffect::isEqual(const GrCustomStage& sBase) const {
    const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);
    return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);
}

<|endoftext|>