<commit_before>#pragma once

#include "base/not_null.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/oblate_body.hpp"
#include "quantities/named_quantities.hpp"

namespace principia {
namespace physics {
namespace internal_geopotential {

using base::not_null;
using geometry::Displacement;
using geometry::Instant;
using geometry::Vector;
using quantities::Acceleration;
using quantities::Exponentiation;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::Quotient;
using quantities::Square;

// Representation of the geopotential model of an oblate body.
template<typename Frame>
class Geopotential {
 public:
  explicit Geopotential(not_null<OblateBody<Frame> const*> body);

  Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
  SphericalHarmonicsAcceleration(
      Instant const& t,
      Displacement<Frame> const& r,
      Square<Length> const& r²,
      Exponentiation<Length, -3> const& one_over_r³) const;

 private:
  using UnitVector = Vector<double, Frame>;

  // If j is a unit vector along the axis of rotation, and r a vector from the
  // center of |body_| to some point in space, the acceleration computed here
  // is:
  //
  //   -(J₂ / (μ ‖r‖⁵)) (3 j (r.j) + r (3 - 15 (r.j)² / ‖r‖²) / 2)
  //
  // Where ‖r‖ is the norm of r and r.j is the inner product.  It is the
  // additional acceleration exerted by the oblateness of |body| on a point at
  // position r.  J₂, J̃₂ and J̄₂ are normally positive and C̃₂₀ and C̄₂₀ negative
  // because the planets are oblate, not prolate.  Note that this follows IERS
  // Technical Note 36 and it differs from
  // https://en.wikipedia.org/wiki/Geopotential_model which seems to want J̃₂ to
  // be negative.
  Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
  Order2ZonalAcceleration(UnitVector const& axis,
                          Displacement<Frame> const& r,
                          Exponentiation<Length, -2> const& one_over_r²,
                          Exponentiation<Length, -3> const& one_over_r³) const;

  //TODO(phl):comment
  Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
  Order3ZonalAcceleration(UnitVector const& axis,
                          Displacement<Frame> const& r,
                          Square<Length> const& r²,
                          Exponentiation<Length, -2> const& one_over_r²,
                          Exponentiation<Length, -3> const& one_over_r³) const;

  not_null<OblateBody<Frame> const*> const body_;
};

}  // namespace internal_geopotential

using internal_geopotential::Geopotential;

}  // namespace physics
}  // namespace principia

#include "physics/geopotential_body.hpp"
<commit_msg>Comment.<commit_after>#pragma once

#include "base/not_null.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/oblate_body.hpp"
#include "quantities/named_quantities.hpp"

namespace principia {
namespace physics {
namespace internal_geopotential {

using base::not_null;
using geometry::Displacement;
using geometry::Instant;
using geometry::Vector;
using quantities::Acceleration;
using quantities::Exponentiation;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::Quotient;
using quantities::Square;

// Representation of the geopotential model of an oblate body.
template<typename Frame>
class Geopotential {
 public:
  explicit Geopotential(not_null<OblateBody<Frame> const*> body);

  Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
  SphericalHarmonicsAcceleration(
      Instant const& t,
      Displacement<Frame> const& r,
      Square<Length> const& r²,
      Exponentiation<Length, -3> const& one_over_r³) const;

 private:
  using UnitVector = Vector<double, Frame>;

  // If j is a unit vector along the axis of rotation, and r a vector from the
  // center of |body_| to some point in space, the acceleration computed here
  // is:
  //
  //   -(J₂ / (μ ‖r‖⁵)) (3 j (r.j) + r (3 - 15 (r.j)² / ‖r‖²) / 2)
  //
  // Where ‖r‖ is the norm of r and r.j is the inner product.  It is the
  // additional acceleration exerted by the oblateness of |body| on a point at
  // position r.  J₂, J̃₂ and J̄₂ are normally positive and C̃₂₀ and C̄₂₀ negative
  // because the planets are oblate, not prolate.  Note that this follows IERS
  // Technical Note 36 and it differs from
  // https://en.wikipedia.org/wiki/Geopotential_model which seems to want J̃₂ to
  // be negative.
  Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
  Order2ZonalAcceleration(UnitVector const& axis,
                          Displacement<Frame> const& r,
                          Exponentiation<Length, -2> const& one_over_r²,
                          Exponentiation<Length, -3> const& one_over_r³) const;

  Vector<Quotient<Acceleration, GravitationalParameter>, Frame>
  Order3ZonalAcceleration(UnitVector const& axis,
                          Displacement<Frame> const& r,
                          Square<Length> const& r²,
                          Exponentiation<Length, -2> const& one_over_r²,
                          Exponentiation<Length, -3> const& one_over_r³) const;

  not_null<OblateBody<Frame> const*> const body_;
};

}  // namespace internal_geopotential

using internal_geopotential::Geopotential;

}  // namespace physics
}  // namespace principia

#include "physics/geopotential_body.hpp"
<|endoftext|>


<commit_before>
#pragma once

#include <functional>
#include <type_traits>

#include "base/not_null.hpp"
#include "geometry/affine_map.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/orthogonal_map.hpp"
#include "geometry/rotation.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/quantities.hpp"
#include "serialization/physics.pb.h"

namespace principia {
namespace physics {
namespace internal_rigid_motion {

using base::not_null;
using geometry::AffineMap;
using geometry::AngularVelocity;
using geometry::Bivector;
using geometry::Instant;
using geometry::OrthogonalMap;
using geometry::Position;
using geometry::RigidTransformation;
using geometry::Vector;
using geometry::Velocity;
using quantities::Acceleration;
using quantities::Length;
using quantities::Variation;
using quantities::si::Radian;

// The instantaneous motion of |ToFrame| with respect to |FromFrame|.
// This is the derivative of a |RigidTransformation<FromFrame, ToFrame>|.
// In order to invert, the |RigidTransformation| is needed, and we need its
// linear part anyway, so we store it (and we forward its action on positions).
template<typename FromFrame, typename ToFrame>
class RigidMotion final {
 public:
  RigidMotion(
      RigidTransformation<FromFrame, ToFrame> rigid_transformation,
      AngularVelocity<FromFrame> const& angular_velocity_of_to_frame,
      Velocity<FromFrame> const& velocity_of_to_frame_origin);

  template<typename F = FromFrame,
           typename T = ToFrame,
           typename = std::enable_if_t<!std::is_same_v<F, T>>>
  RigidMotion(
      RigidTransformation<FromFrame, ToFrame> const& rigid_transformation,
      AngularVelocity<ToFrame> const& angular_velocity_of_from_frame,
      Velocity<ToFrame> const& velocity_of_from_frame_origin);

  RigidTransformation<FromFrame, ToFrame> const& rigid_transformation() const;
  // Returns |rigid_transformation().linear_map()|.
  OrthogonalMap<FromFrame, ToFrame> const& orthogonal_map() const;
  AngularVelocity<FromFrame> const& angular_velocity_of_to_frame() const;
  Velocity<FromFrame> const& velocity_of_to_frame_origin() const;

  DegreesOfFreedom<ToFrame> operator()(
      DegreesOfFreedom<FromFrame> const& degrees_of_freedom) const;

  RigidMotion<ToFrame, FromFrame> Inverse() const;

  // A rigid motion expressing that |FromFrame| and |ToFrame| have the same
  // axes, origin, and instantaneous motion.
  // This function is enabled only if both frames have the same handedness (this
  // is a requirement of OrthogonalMap::Identity) and if the |motion| of FromFrame
  // is a special case of that of |ToFrame| (see the comments on |FrameMotion|).
  template<typename F = FromFrame,
           typename T = ToFrame,
           typename = std::enable_if_t<F::handedness == T::handedness &&
                                       F::motion <= T::motion>>
  static RigidMotion Identity();

  // A factory that construct a non-rotating motion using the given degrees of
  // freedom.  Useful e.g. for save compatibility.
  static RigidMotion MakeNonRotatingMotion(
      DegreesOfFreedom<ToFrame> const& degrees_of_freedom_of_from_frame_origin);

  void WriteToMessage(not_null<serialization::RigidMotion*> message) const;
  static RigidMotion ReadFromMessage(serialization::RigidMotion const& message);

 private:
  RigidTransformation<FromFrame, ToFrame> rigid_transformation_;
  // d/dt rigid_transformation⁻¹(basis of ToFrame). The positively oriented
  // orthogonal bases of |FromFrame| are acted upon faithfully and transitively
  // by SO(FromFrame), so this lies in the tangent space, i.e., the Lie algebra
  // 𝖘𝔬(FromFrame) ≅ FromFrame ∧ FromFrame.
  AngularVelocity<FromFrame> angular_velocity_of_to_frame_;
  // d/dt rigid_transformation⁻¹(ToFrame::origin).
  Velocity<FromFrame> velocity_of_to_frame_origin_;

  template<typename From, typename Through, typename To>
  friend RigidMotion<From, To> operator*(
      RigidMotion<Through, To> const& left,
      RigidMotion<From, Through> const& right);
};

template<typename FromFrame, typename ThroughFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame> operator*(
    RigidMotion<ThroughFrame, ToFrame> const& left,
    RigidMotion<FromFrame, ThroughFrame> const& right);

// A |RigidTransformation|, its first derivative (a |RigidMotion|), and its
// second derivative (angular and linear accelerations).
template<typename FromFrame, typename ToFrame>
class AcceleratedRigidMotion final {
 public:
  AcceleratedRigidMotion(
      RigidMotion<FromFrame, ToFrame> rigid_motion,
      Variation<AngularVelocity<FromFrame>> const&
          angular_acceleration_of_to_frame,
      Vector<Acceleration, FromFrame> const& acceleration_of_to_frame_origin);

  RigidMotion<FromFrame, ToFrame> const& rigid_motion() const;
  Variation<AngularVelocity<FromFrame>> const&
  angular_acceleration_of_to_frame() const;
  Vector<Acceleration, FromFrame> const& acceleration_of_to_frame_origin()
      const;

 private:
  RigidMotion<FromFrame, ToFrame> const rigid_motion_;
  // d/dt rigid_motion_.angular_velocity_of_to_frame().
  Variation<AngularVelocity<FromFrame>> const angular_acceleration_of_to_frame_;
  // d/dt rigid_motion_.velocity_of_to_frame_origin().
  Vector<Acceleration, FromFrame> const acceleration_of_to_frame_origin_;
};

template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(std::ostream& out,
                         RigidMotion<FromFrame, ToFrame> const& rigid_motion);

template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(
    std::ostream& out,
    AcceleratedRigidMotion<FromFrame, ToFrame> const& accelerated_rigid_motion);

}  // namespace internal_rigid_motion

using internal_rigid_motion::AcceleratedRigidMotion;
using internal_rigid_motion::RigidMotion;
using internal_rigid_motion::RigidTransformation;

}  // namespace physics
}  // namespace principia

#include "physics/rigid_motion_body.hpp"
<commit_msg>long line<commit_after>
#pragma once

#include <functional>
#include <type_traits>

#include "base/not_null.hpp"
#include "geometry/affine_map.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/orthogonal_map.hpp"
#include "geometry/rotation.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/quantities.hpp"
#include "serialization/physics.pb.h"

namespace principia {
namespace physics {
namespace internal_rigid_motion {

using base::not_null;
using geometry::AffineMap;
using geometry::AngularVelocity;
using geometry::Bivector;
using geometry::Instant;
using geometry::OrthogonalMap;
using geometry::Position;
using geometry::RigidTransformation;
using geometry::Vector;
using geometry::Velocity;
using quantities::Acceleration;
using quantities::Length;
using quantities::Variation;
using quantities::si::Radian;

// The instantaneous motion of |ToFrame| with respect to |FromFrame|.
// This is the derivative of a |RigidTransformation<FromFrame, ToFrame>|.
// In order to invert, the |RigidTransformation| is needed, and we need its
// linear part anyway, so we store it (and we forward its action on positions).
template<typename FromFrame, typename ToFrame>
class RigidMotion final {
 public:
  RigidMotion(
      RigidTransformation<FromFrame, ToFrame> rigid_transformation,
      AngularVelocity<FromFrame> const& angular_velocity_of_to_frame,
      Velocity<FromFrame> const& velocity_of_to_frame_origin);

  template<typename F = FromFrame,
           typename T = ToFrame,
           typename = std::enable_if_t<!std::is_same_v<F, T>>>
  RigidMotion(
      RigidTransformation<FromFrame, ToFrame> const& rigid_transformation,
      AngularVelocity<ToFrame> const& angular_velocity_of_from_frame,
      Velocity<ToFrame> const& velocity_of_from_frame_origin);

  RigidTransformation<FromFrame, ToFrame> const& rigid_transformation() const;
  // Returns |rigid_transformation().linear_map()|.
  OrthogonalMap<FromFrame, ToFrame> const& orthogonal_map() const;
  AngularVelocity<FromFrame> const& angular_velocity_of_to_frame() const;
  Velocity<FromFrame> const& velocity_of_to_frame_origin() const;

  DegreesOfFreedom<ToFrame> operator()(
      DegreesOfFreedom<FromFrame> const& degrees_of_freedom) const;

  RigidMotion<ToFrame, FromFrame> Inverse() const;

  // A rigid motion expressing that |FromFrame| and |ToFrame| have the same
  // axes, origin, and instantaneous motion.
  // This function is enabled only if both frames have the same handedness (this
  // is a requirement of OrthogonalMap::Identity) and if the |motion| of
  // FromFrame is a special case of that of |ToFrame| (see the comments on
  // |FrameMotion|).
  template<typename F = FromFrame,
           typename T = ToFrame,
           typename = std::enable_if_t<F::handedness == T::handedness &&
                                       F::motion <= T::motion>>
  static RigidMotion Identity();

  // A factory that construct a non-rotating motion using the given degrees of
  // freedom.  Useful e.g. for save compatibility.
  static RigidMotion MakeNonRotatingMotion(
      DegreesOfFreedom<ToFrame> const& degrees_of_freedom_of_from_frame_origin);

  void WriteToMessage(not_null<serialization::RigidMotion*> message) const;
  static RigidMotion ReadFromMessage(serialization::RigidMotion const& message);

 private:
  RigidTransformation<FromFrame, ToFrame> rigid_transformation_;
  // d/dt rigid_transformation⁻¹(basis of ToFrame). The positively oriented
  // orthogonal bases of |FromFrame| are acted upon faithfully and transitively
  // by SO(FromFrame), so this lies in the tangent space, i.e., the Lie algebra
  // 𝖘𝔬(FromFrame) ≅ FromFrame ∧ FromFrame.
  AngularVelocity<FromFrame> angular_velocity_of_to_frame_;
  // d/dt rigid_transformation⁻¹(ToFrame::origin).
  Velocity<FromFrame> velocity_of_to_frame_origin_;

  template<typename From, typename Through, typename To>
  friend RigidMotion<From, To> operator*(
      RigidMotion<Through, To> const& left,
      RigidMotion<From, Through> const& right);
};

template<typename FromFrame, typename ThroughFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame> operator*(
    RigidMotion<ThroughFrame, ToFrame> const& left,
    RigidMotion<FromFrame, ThroughFrame> const& right);

// A |RigidTransformation|, its first derivative (a |RigidMotion|), and its
// second derivative (angular and linear accelerations).
template<typename FromFrame, typename ToFrame>
class AcceleratedRigidMotion final {
 public:
  AcceleratedRigidMotion(
      RigidMotion<FromFrame, ToFrame> rigid_motion,
      Variation<AngularVelocity<FromFrame>> const&
          angular_acceleration_of_to_frame,
      Vector<Acceleration, FromFrame> const& acceleration_of_to_frame_origin);

  RigidMotion<FromFrame, ToFrame> const& rigid_motion() const;
  Variation<AngularVelocity<FromFrame>> const&
  angular_acceleration_of_to_frame() const;
  Vector<Acceleration, FromFrame> const& acceleration_of_to_frame_origin()
      const;

 private:
  RigidMotion<FromFrame, ToFrame> const rigid_motion_;
  // d/dt rigid_motion_.angular_velocity_of_to_frame().
  Variation<AngularVelocity<FromFrame>> const angular_acceleration_of_to_frame_;
  // d/dt rigid_motion_.velocity_of_to_frame_origin().
  Vector<Acceleration, FromFrame> const acceleration_of_to_frame_origin_;
};

template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(std::ostream& out,
                         RigidMotion<FromFrame, ToFrame> const& rigid_motion);

template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(
    std::ostream& out,
    AcceleratedRigidMotion<FromFrame, ToFrame> const& accelerated_rigid_motion);

}  // namespace internal_rigid_motion

using internal_rigid_motion::AcceleratedRigidMotion;
using internal_rigid_motion::RigidMotion;
using internal_rigid_motion::RigidTransformation;

}  // namespace physics
}  // namespace principia

#include "physics/rigid_motion_body.hpp"
<|endoftext|>


<commit_before>/*
 * file OculusVR.cpp
 *
 * author luoxw
 * date 2016/11/10
 *
 *
 */
#include "HookCorePCH.h"
#include "OculusVR.h"

using namespace lostvr;

OculusVR::OculusVR(const std::string& key) :
	IVRDevice(key),
	Session(nullptr),
	HmdDesc(),
	TrackerDescArray(),
	presentResult(ovrSuccess),
	bInitialized(false),
	Renderer(nullptr),
	RTV(nullptr)
{
	// Set all layers to zero
	for (int i = 0; i < ovrMaxLayerCount; ++i)
		Layer[i] = nullptr;
}

OculusVR::~OculusVR()
{
	Shutdown();
}

bool OculusVR::Startup()
{
	const CHAR* head = "OculusVR::Startup";

	// Initializes LibOVR, and the Rift
	ovrResult result;
	ovrDetectResult detectResult = ovr_Detect(0);
	LVMSG("Oculus startup", "detect result: IsOculusServiceRunning(%d), IsOculusHMDConnected(%d)", detectResult.IsOculusServiceRunning, detectResult.IsOculusHMDConnected);

	if (detectResult.IsOculusServiceRunning && detectResult.IsOculusHMDConnected)
	{
		static bool s_first = true;
		WCHAR curr[MAX_PATH];
		if (!s_first)
		{
			LVMSG(head, "we've failed once, about to use our runtime");
			GetCurrentDirectoryW(MAX_PATH, curr);
			SetCurrentDirectory(SGlobalSharedDataInst.GetDependencyDirectory());
		}

		ovrInitParams initParams;
		memset(&initParams, 0, sizeof(initParams));
		initParams.Flags = ovrInit_RequestVersion;
		initParams.RequestedMinorVersion = OVR_MINOR_VERSION;
		initParams.LogCallback = OvrLogCallback;
		result = ovr_Initialize(&initParams);
		s_first = false;
		SetCurrentDirectoryW(curr);
	}
	else
	{
		return false;
	}

	if (!OVR_SUCCESS(result))
	{
		ovrErrorInfo errorInfo;
		ovr_GetLastErrorInfo(&errorInfo);
		LVMSG("Oculus startup", "ovr_Initialize failed(%d), error message: %d, %s", result, errorInfo.Result, errorInfo.ErrorString);
		return false;
	}
	else
	{
		LVMSG("Oculus startup", "ovr_Initialize succeeded");
		const CHAR* clientid = "vronline";
		ovr_IdentifyClient(clientid);
	}

	ovrGraphicsLuid luid;
	result = ovr_Create(&Session, &luid);
	if (!OVR_SUCCESS(result))
	{
		if (result == ovrError_ServiceConnection || result == ovrError_ServiceError || result == ovrError_NotInitialized)
		{
			Shutdown();

			ovrInitParams initParams;
			memset(&initParams, 0, sizeof(initParams));
			initParams.Flags = ovrInit_RequestVersion;
			initParams.RequestedMinorVersion = OVR_MINOR_VERSION;
			initParams.LogCallback = OvrLogCallback;
			result = ovr_Initialize(&initParams);
			if (OVR_SUCCESS(result))
			{
				const CHAR* clientid = "vronline";
				ovr_IdentifyClient(clientid);
				result = ovr_Create(&Session, &luid);
				if (OVR_SUCCESS(result))
				{
					LVMSG("Oculus startup", "create after reinitialize success");
				}
				else
				{
					LVMSG("Oculus startup", "create after reinitialize failed: %d", result);
					return false;
				}
			}
			else
			{
				LVMSG("Oculus startup", "reinitialize failed: %d", result);
				return false;
			}
		}
		else
		{
			ovrErrorInfo errorInfo;
			ovr_GetLastErrorInfo(&errorInfo);
			LVMSG("Oculus startup", "ovr_Create failed(%d), error message: %d, %s", result, errorInfo.Result, errorInfo.ErrorString);
			return false;
		}
	}
	else
	{
		LVMSG("Oculus startup", "ovr_Create succeeded");
	}

	HmdDesc = ovr_GetHmdDesc(Session);
	return true;
}

void OculusVR::Shutdown()
{
	for (int i = 0; i < ovrMaxLayerCount; ++i)
	{
		delete Layer[i];
		Layer[i] = nullptr;
	}

	if (Session)
	{
		ovr_Destroy(Session);
		Session = nullptr;
	}

	if (bInitialized)
	{
		ovr_Shutdown();
		bInitialized = false;
	}

	memset(&HmdDesc, 0, sizeof(HmdDesc));

	SAFE_RELEASE(RTV);
	SAFE_DELETE(Renderer);
}

bool OculusVR::IsConnected()
{
	return (Session != nullptr);
}

bool OculusVR::OnPresent_Direct3D11(IDXGISwapChain* swapChain)
{
	const CHAR* head = "OculusVR::OnPresent_Direct3D11";
	if (Renderer == nullptr)
	{
		Renderer = new Direct3D11Helper(EDirect3D::DeviceRef);
		if (Renderer == nullptr)
		{
			LVMSG(head, "alloc renderer object failed");
			return false;
		}
	}

	// If swap chain changed, dirt initial state
	if (swapChain != Renderer->GetSwapChain())
	{
		bInitialized = false;
	}

	if (!Renderer->UpdateRHIWithSwapChain(swapChain) || !EnsureInitialized(swapChain, true))
	{
		return false;
	}
	else
	{
		DXGI_SWAP_CHAIN_DESC scd;
		swapChain->GetDesc(&scd);
		SGlobalSharedDataInst.SetTargetWindow(scd.OutputWindow);
	}

	{
		RenderStateCache cache(Renderer->GetContext());
		cache.Capture();

		D3D11_VIEWPORT vp;
		vp.TopLeftX = Layer[0]->EyeRenderViewport[0].Pos.x;
		vp.TopLeftY = Layer[0]->EyeRenderViewport[0].Pos.y;
		vp.Width = Layer[0]->EyeRenderViewport[0].Size.w;
		vp.Height = Layer[0]->EyeRenderViewport[0].Size.h;
		vp.MinDepth = 0.01f;
		vp.MaxDepth = 10000.f;

		Renderer->GetContext()->RSSetViewports(1, &vp);
		Renderer->GetContext()->OMSetRenderTargets(1, &RTV, nullptr);
		Renderer->UpdateCursor(LVVec3(2.f, 2.f, -1.f), 0.1f, DirectX::XMMatrixIdentity(), DirectX::XMMatrixIdentity(),
			SGlobalSharedDataInst.GetBDrawCursor());

		cache.Restore();
	}

	Layer[0]->GetEyePoses();
	ID3D11Texture2D* dst = Layer[0]->pEyeRenderTexture[0]->GetBuffer();
	ID3D11Texture2D* buf = Renderer->GetSwapChainBuffer();
	if (buf == nullptr)
	{
		return false;
	}

	ContextCopyResource(dst, buf, "OculusVR::OnPresent_Direct3D11", false);
	Layer[0]->Commit(0);
	ovrResult ret = DistortAndPresent(1);
	if (!OVR_SUCCESS(ret))
	{
		LVMSG(head, "submit failed(%d), ...", ret);
		return false;
	}

	return true;
}

bool OculusVR::OnPresent_Direct3D9(IDirect3DDevice9* device)
{
	const CHAR* head = "OculusVR::OnPresent_Direct3D9";

	if (Renderer == nullptr)
	{
		Renderer = new Direct3D11Helper(EDirect3D::DXGI0, device);
		if (Renderer == nullptr)
		{
			LVMSG(head, "alloc renderer object failed");
			return false;
		}
	}

	if (device != nullptr)
	{
		IDirect3DSwapChain9* swapChain = nullptr;
		D3DPRESENT_PARAMETERS params;
		if (FAILED(device->GetSwapChain(0, &swapChain)) ||
			FAILED(swapChain->GetPresentParameters(&params)))
		{
			LVERROR(head, "get target window from direct9 device failed");
			return false;
		}

		SGlobalSharedDataInst.SetTargetWindow(params.hDeviceWindow);
		SAFE_RELEASE(swapChain);
	}

	if (!EnsureInitialized(Renderer->GetSwapChain(), false))
	{
		return false;
	}

	if (!Renderer->UpdateBuffer_Direct3D9(device))
	{
		LVMSG(head, "update buffer with direct9 device failed");
		return false;
	}

	//{
	//	if (RTV == nullptr)
	//	{
	//		if (Renderer->CreateRenderTargetView(Renderer->GetBufferDirect3D9Copy(), &RTV))
	//		{
	//			return false;
	//		}
	//	}

	//	RenderStateCache cache(Renderer->GetContext());
	//	cache.Capture();

	//	D3D11_VIEWPORT vp;
	//	vp.TopLeftX = Layer[0]->EyeRenderViewport[0].Pos.x;
	//	vp.TopLeftY = Layer[0]->EyeRenderViewport[0].Pos.y;
	//	vp.Width = Layer[0]->EyeRenderViewport[0].Size.w;
	//	vp.Height = Layer[0]->EyeRenderViewport[0].Size.h;
	//	vp.MinDepth = 0.01f;
	//	vp.MaxDepth = 10000.f;

	//	Renderer->GetContext()->RSSetViewports(1, &vp);
	//	Renderer->GetContext()->OMSetRenderTargets(1, &RTV, nullptr);
	//	Renderer->UpdateCursor(LVVec3(2.f, 2.f, -1.f), 0.1f, DirectX::XMMatrixIdentity(), DirectX::XMMatrixIdentity(),
	//		SGlobalSharedDataInst.GetBDrawCursor());

	//	cache.Restore();
	//}

	Layer[0]->GetEyePoses();
	ID3D11Texture2D* dst = Layer[0]->pEyeRenderTexture[0]->GetBuffer();
	if (!Renderer->OutputBuffer_Texture2D_Direct3D9(dst))
	{
		return false;
	}

	Layer[0]->Commit(0);
	ovrResult ret = DistortAndPresent(1);
	if (!OVR_SUCCESS(ret))
	{
		LVMSG(head, "submit failed(%d), ...", ret);
		return false;
	}

	return true;
}

const std::string OculusVR::GetDeviceString() const
{
	char strDesc[1024];
	snprintf(strDesc, 1023, "[ProductName: %s, Manufacturer: %s, SerialNumber: %s]",
		HmdDesc.ProductName, HmdDesc.Manufacturer, HmdDesc.SerialNumber);
	return std::string(strDesc);
}

//std::string OculusVR::GetKeyString() const
//{
//	return std::string("[OculusVR]");
//}

bool OculusVR::Init(ID3D11Device* Dev, DXGI_SWAP_CHAIN_DESC Desc)
{
	unsigned int trackerCount = ovr_GetTrackerCount(Session) < 1 ? 1 : ovr_GetTrackerCount(Session); // Make sure there's always at least one.
	for (unsigned int i = 0; i < trackerCount; ++i)
		TrackerDescArray.push_back(ovr_GetTrackerDesc(Session, i));

	{
		Layer[0] = new VRLayer(Dev, Desc, Session);
	}

	LVMSG("OculusVR Init", "sucess");
	bInitialized = true;
	return true;
}

bool OculusVR::EnsureInitialized(IDXGISwapChain * swapChain, bool bCreateRTV)
{
	const CHAR* head = "OculusVR::EnsureInitialized";

	if (!bInitialized)
	{
		if (swapChain == nullptr)
		{
			LVMSG(head, "null swap chain");
			return false;
		}

		DXGI_SWAP_CHAIN_DESC Desc;
		if (FAILED(swapChain->GetDesc(&Desc)))
		{
			LVMSG(head, "failed to get SwapChain's desc, SwapChain(%x).", swapChain);
			return false;
		}

		if (!(bInitialized = Init(Renderer->GetDevice(), Desc)))
		{
			LVMSG(head, "failed to initialize, SwapChain(%x).", swapChain);
			return false;
		}

		if (bCreateRTV)
		{
			SAFE_RELEASE(RTV);
			if (!Renderer->CreateRenderTargetView(nullptr, &RTV))
			{
				return false;
			}
		}
	}

	return true;
}

ovrResult OculusVR::DistortAndPresent(int numLayersToRender, D3D11_BOX * optionalBoxForMirrorWindow/* = 0*/, bool mirror/* = true*/)
{
	ovrLayerHeader* layerHeaders[ovrMaxLayerCount];
	for (int i = 0; i < ovrMaxLayerCount; i++)
	{
		if (Layer[i])
		{
			layerHeaders[i] = &(Layer[i]->ovrLayer.Header);
		}
	}

	presentResult = ovr_SubmitFrame(Session, 0, nullptr, layerHeaders, numLayersToRender);
	if (!OVR_SUCCESS(presentResult))
	{
		LVMSG("ovr_SubmitFrame", "layers(%d), result(%d)", (int)ovrMaxLayerCount, presentResult);
		return(presentResult);
	}

	return(presentResult);
}

void OculusVR::AddMovement(EMovement movement)
{
	switch (movement)
	{
	case lostvr::EMovement::UnDefined:
		break;
	case lostvr::EMovement::CameraFront:
		Layer[0]->AdjustViewport(1.25f, 1.25f);
		break;
	case lostvr::EMovement::CameraBack:
		Layer[0]->AdjustViewport(0.8f, 0.8f);
		break;
	default:
		break;
	}
}

static OculusVR* SInst = new OculusVR("libovr");<commit_msg>fix not found runtimes<commit_after>/*
 * file OculusVR.cpp
 *
 * author luoxw
 * date 2016/11/10
 *
 *
 */
#include "HookCorePCH.h"
#include "OculusVR.h"

using namespace lostvr;

OculusVR::OculusVR(const std::string& key) :
	IVRDevice(key),
	Session(nullptr),
	HmdDesc(),
	TrackerDescArray(),
	presentResult(ovrSuccess),
	bInitialized(false),
	Renderer(nullptr),
	RTV(nullptr)
{
	// Set all layers to zero
	for (int i = 0; i < ovrMaxLayerCount; ++i)
		Layer[i] = nullptr;
}

OculusVR::~OculusVR()
{
	Shutdown();
}

bool OculusVR::Startup()
{
	const CHAR* head = "OculusVR::Startup";

	// Initializes LibOVR, and the Rift
	ovrResult result;
	ovrDetectResult detectResult = ovr_Detect(0);
	LVMSG("Oculus startup", "detect result: IsOculusServiceRunning(%d), IsOculusHMDConnected(%d)", detectResult.IsOculusServiceRunning, detectResult.IsOculusHMDConnected);

	if (detectResult.IsOculusServiceRunning && detectResult.IsOculusHMDConnected)
	{
		ovrInitParams initParams;
		memset(&initParams, 0, sizeof(initParams));
		initParams.Flags = ovrInit_RequestVersion;
		initParams.RequestedMinorVersion = OVR_MINOR_VERSION;
		initParams.LogCallback = OvrLogCallback;
		result = ovr_Initialize(&initParams);

		if (result == ovrError_LibLoad)
		{
			SetCurrentDirectory(SGlobalSharedDataInst.GetDependencyDirectory());
			result = ovr_Initialize(&initParams);
		}
	}
	else
	{
		return false;
	}

	if (!OVR_SUCCESS(result))
	{
		ovrErrorInfo errorInfo;
		ovr_GetLastErrorInfo(&errorInfo);
		LVMSG("Oculus startup", "ovr_Initialize failed(%d), error message: %d, %s", result, errorInfo.Result, errorInfo.ErrorString);
		return false;
	}
	else
	{
		LVMSG("Oculus startup", "ovr_Initialize succeeded");
		const CHAR* clientid = "vronline";
		ovr_IdentifyClient(clientid);
	}

	ovrGraphicsLuid luid;
	result = ovr_Create(&Session, &luid);
	if (!OVR_SUCCESS(result))
	{
		if (result == ovrError_ServiceConnection || result == ovrError_ServiceError || result == ovrError_NotInitialized)
		{
			Shutdown();

			ovrInitParams initParams;
			memset(&initParams, 0, sizeof(initParams));
			initParams.Flags = ovrInit_RequestVersion;
			initParams.RequestedMinorVersion = OVR_MINOR_VERSION;
			initParams.LogCallback = OvrLogCallback;
			result = ovr_Initialize(&initParams);
			if (OVR_SUCCESS(result))
			{
				const CHAR* clientid = "vronline";
				ovr_IdentifyClient(clientid);
				result = ovr_Create(&Session, &luid);
				if (OVR_SUCCESS(result))
				{
					LVMSG("Oculus startup", "create after reinitialize success");
				}
				else
				{
					LVMSG("Oculus startup", "create after reinitialize failed: %d", result);
					return false;
				}
			}
			else
			{
				LVMSG("Oculus startup", "reinitialize failed: %d", result);
				return false;
			}
		}
		else
		{
			ovrErrorInfo errorInfo;
			ovr_GetLastErrorInfo(&errorInfo);
			LVMSG("Oculus startup", "ovr_Create failed(%d), error message: %d, %s", result, errorInfo.Result, errorInfo.ErrorString);
			return false;
		}
	}
	else
	{
		LVMSG("Oculus startup", "ovr_Create succeeded");
	}

	HmdDesc = ovr_GetHmdDesc(Session);
	return true;
}

void OculusVR::Shutdown()
{
	for (int i = 0; i < ovrMaxLayerCount; ++i)
	{
		delete Layer[i];
		Layer[i] = nullptr;
	}

	if (Session)
	{
		ovr_Destroy(Session);
		Session = nullptr;
	}

	if (bInitialized)
	{
		ovr_Shutdown();
		bInitialized = false;
	}

	memset(&HmdDesc, 0, sizeof(HmdDesc));

	SAFE_RELEASE(RTV);
	SAFE_DELETE(Renderer);
}

bool OculusVR::IsConnected()
{
	return (Session != nullptr);
}

bool OculusVR::OnPresent_Direct3D11(IDXGISwapChain* swapChain)
{
	const CHAR* head = "OculusVR::OnPresent_Direct3D11";
	if (Renderer == nullptr)
	{
		Renderer = new Direct3D11Helper(EDirect3D::DeviceRef);
		if (Renderer == nullptr)
		{
			LVMSG(head, "alloc renderer object failed");
			return false;
		}
	}

	// If swap chain changed, dirt initial state
	if (swapChain != Renderer->GetSwapChain())
	{
		bInitialized = false;
	}

	if (!Renderer->UpdateRHIWithSwapChain(swapChain) || !EnsureInitialized(swapChain, true))
	{
		return false;
	}
	else
	{
		DXGI_SWAP_CHAIN_DESC scd;
		swapChain->GetDesc(&scd);
		SGlobalSharedDataInst.SetTargetWindow(scd.OutputWindow);
	}

	{
		RenderStateCache cache(Renderer->GetContext());
		cache.Capture();

		D3D11_VIEWPORT vp;
		vp.TopLeftX = Layer[0]->EyeRenderViewport[0].Pos.x;
		vp.TopLeftY = Layer[0]->EyeRenderViewport[0].Pos.y;
		vp.Width = Layer[0]->EyeRenderViewport[0].Size.w;
		vp.Height = Layer[0]->EyeRenderViewport[0].Size.h;
		vp.MinDepth = 0.01f;
		vp.MaxDepth = 10000.f;

		Renderer->GetContext()->RSSetViewports(1, &vp);
		Renderer->GetContext()->OMSetRenderTargets(1, &RTV, nullptr);
		Renderer->UpdateCursor(LVVec3(2.f, 2.f, -1.f), 0.1f, DirectX::XMMatrixIdentity(), DirectX::XMMatrixIdentity(),
			SGlobalSharedDataInst.GetBDrawCursor());

		cache.Restore();
	}

	Layer[0]->GetEyePoses();
	ID3D11Texture2D* dst = Layer[0]->pEyeRenderTexture[0]->GetBuffer();
	ID3D11Texture2D* buf = Renderer->GetSwapChainBuffer();
	if (buf == nullptr)
	{
		return false;
	}

	ContextCopyResource(dst, buf, "OculusVR::OnPresent_Direct3D11", false);
	Layer[0]->Commit(0);
	ovrResult ret = DistortAndPresent(1);
	if (!OVR_SUCCESS(ret))
	{
		LVMSG(head, "submit failed(%d), ...", ret);
		return false;
	}

	return true;
}

bool OculusVR::OnPresent_Direct3D9(IDirect3DDevice9* device)
{
	const CHAR* head = "OculusVR::OnPresent_Direct3D9";

	if (Renderer == nullptr)
	{
		Renderer = new Direct3D11Helper(EDirect3D::DXGI0, device);
		if (Renderer == nullptr)
		{
			LVMSG(head, "alloc renderer object failed");
			return false;
		}
	}

	if (device != nullptr)
	{
		IDirect3DSwapChain9* swapChain = nullptr;
		D3DPRESENT_PARAMETERS params;
		if (FAILED(device->GetSwapChain(0, &swapChain)) ||
			FAILED(swapChain->GetPresentParameters(&params)))
		{
			LVERROR(head, "get target window from direct9 device failed");
			return false;
		}

		SGlobalSharedDataInst.SetTargetWindow(params.hDeviceWindow);
		SAFE_RELEASE(swapChain);
	}

	if (!EnsureInitialized(Renderer->GetSwapChain(), false))
	{
		return false;
	}

	if (!Renderer->UpdateBuffer_Direct3D9(device))
	{
		LVMSG(head, "update buffer with direct9 device failed");
		return false;
	}

	//{
	//	if (RTV == nullptr)
	//	{
	//		if (Renderer->CreateRenderTargetView(Renderer->GetBufferDirect3D9Copy(), &RTV))
	//		{
	//			return false;
	//		}
	//	}

	//	RenderStateCache cache(Renderer->GetContext());
	//	cache.Capture();

	//	D3D11_VIEWPORT vp;
	//	vp.TopLeftX = Layer[0]->EyeRenderViewport[0].Pos.x;
	//	vp.TopLeftY = Layer[0]->EyeRenderViewport[0].Pos.y;
	//	vp.Width = Layer[0]->EyeRenderViewport[0].Size.w;
	//	vp.Height = Layer[0]->EyeRenderViewport[0].Size.h;
	//	vp.MinDepth = 0.01f;
	//	vp.MaxDepth = 10000.f;

	//	Renderer->GetContext()->RSSetViewports(1, &vp);
	//	Renderer->GetContext()->OMSetRenderTargets(1, &RTV, nullptr);
	//	Renderer->UpdateCursor(LVVec3(2.f, 2.f, -1.f), 0.1f, DirectX::XMMatrixIdentity(), DirectX::XMMatrixIdentity(),
	//		SGlobalSharedDataInst.GetBDrawCursor());

	//	cache.Restore();
	//}

	Layer[0]->GetEyePoses();
	ID3D11Texture2D* dst = Layer[0]->pEyeRenderTexture[0]->GetBuffer();
	if (!Renderer->OutputBuffer_Texture2D_Direct3D9(dst))
	{
		return false;
	}

	Layer[0]->Commit(0);
	ovrResult ret = DistortAndPresent(1);
	if (!OVR_SUCCESS(ret))
	{
		LVMSG(head, "submit failed(%d), ...", ret);
		return false;
	}

	return true;
}

const std::string OculusVR::GetDeviceString() const
{
	char strDesc[1024];
	snprintf(strDesc, 1023, "[ProductName: %s, Manufacturer: %s, SerialNumber: %s]",
		HmdDesc.ProductName, HmdDesc.Manufacturer, HmdDesc.SerialNumber);
	return std::string(strDesc);
}

//std::string OculusVR::GetKeyString() const
//{
//	return std::string("[OculusVR]");
//}

bool OculusVR::Init(ID3D11Device* Dev, DXGI_SWAP_CHAIN_DESC Desc)
{
	unsigned int trackerCount = ovr_GetTrackerCount(Session) < 1 ? 1 : ovr_GetTrackerCount(Session); // Make sure there's always at least one.
	for (unsigned int i = 0; i < trackerCount; ++i)
		TrackerDescArray.push_back(ovr_GetTrackerDesc(Session, i));

	{
		Layer[0] = new VRLayer(Dev, Desc, Session);
	}

	LVMSG("OculusVR Init", "sucess");
	bInitialized = true;
	return true;
}

bool OculusVR::EnsureInitialized(IDXGISwapChain * swapChain, bool bCreateRTV)
{
	const CHAR* head = "OculusVR::EnsureInitialized";

	if (!bInitialized)
	{
		if (swapChain == nullptr)
		{
			LVMSG(head, "null swap chain");
			return false;
		}

		DXGI_SWAP_CHAIN_DESC Desc;
		if (FAILED(swapChain->GetDesc(&Desc)))
		{
			LVMSG(head, "failed to get SwapChain's desc, SwapChain(%x).", swapChain);
			return false;
		}

		if (!(bInitialized = Init(Renderer->GetDevice(), Desc)))
		{
			LVMSG(head, "failed to initialize, SwapChain(%x).", swapChain);
			return false;
		}

		if (bCreateRTV)
		{
			SAFE_RELEASE(RTV);
			if (!Renderer->CreateRenderTargetView(nullptr, &RTV))
			{
				return false;
			}
		}
	}

	return true;
}

ovrResult OculusVR::DistortAndPresent(int numLayersToRender, D3D11_BOX * optionalBoxForMirrorWindow/* = 0*/, bool mirror/* = true*/)
{
	ovrLayerHeader* layerHeaders[ovrMaxLayerCount];
	for (int i = 0; i < ovrMaxLayerCount; i++)
	{
		if (Layer[i])
		{
			layerHeaders[i] = &(Layer[i]->ovrLayer.Header);
		}
	}

	presentResult = ovr_SubmitFrame(Session, 0, nullptr, layerHeaders, numLayersToRender);
	if (!OVR_SUCCESS(presentResult))
	{
		LVMSG("ovr_SubmitFrame", "layers(%d), result(%d)", (int)ovrMaxLayerCount, presentResult);
		return(presentResult);
	}

	return(presentResult);
}

void OculusVR::AddMovement(EMovement movement)
{
	switch (movement)
	{
	case lostvr::EMovement::UnDefined:
		break;
	case lostvr::EMovement::CameraFront:
		Layer[0]->AdjustViewport(1.25f, 1.25f);
		break;
	case lostvr::EMovement::CameraBack:
		Layer[0]->AdjustViewport(0.8f, 0.8f);
		break;
	default:
		break;
	}
}

static OculusVR* SInst = new OculusVR("libovr");<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * 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 "perfetto/base/logging.h"
#include "perfetto/trace_processor/trace_processor.h"

#include "perfetto/trace_processor/raw_query.pb.h"

namespace perfetto {
namespace trace_processor {

void FuzzTraceProcessor(const uint8_t* data, size_t size);

void FuzzTraceProcessor(const uint8_t* data, size_t size) {
  std::unique_ptr<TraceProcessor> processor =
      TraceProcessor::CreateInstance(Config());
  std::unique_ptr<uint8_t[]> buf(new uint8_t[size]);
  memcpy(buf.get(), data, size);
  if (!processor->Parse(std::move(buf), size))
    return;
  processor->NotifyEndOfFile();
}

}  // namespace trace_processor
}  // namespace perfetto

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  perfetto::trace_processor::FuzzTraceProcessor(data, size);
  return 0;
}
<commit_msg>trace_processor: fix fuzzing target am: 3f4671995b am: 4b3591be1b am: a78d52fc1b<commit_after>/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * 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 "perfetto/base/logging.h"
#include "perfetto/trace_processor/trace_processor.h"

#include "perfetto/trace_processor/raw_query.pb.h"

namespace perfetto {
namespace trace_processor {

void FuzzTraceProcessor(const uint8_t* data, size_t size);

void FuzzTraceProcessor(const uint8_t* data, size_t size) {
  std::unique_ptr<TraceProcessor> processor =
      TraceProcessor::CreateInstance(Config());
  std::unique_ptr<uint8_t[]> buf(new uint8_t[size]);
  memcpy(buf.get(), data, size);
  util::Status status = processor->Parse(std::move(buf), size);
  if (!status.ok())
    return;
  processor->NotifyEndOfFile();
}

}  // namespace trace_processor
}  // namespace perfetto

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  perfetto::trace_processor::FuzzTraceProcessor(data, size);
  return 0;
}
<|endoftext|>


<commit_before>#include "UrdfModelReader.h"

#include <tinyxml2/tinyxml2.h>
#include <fstream>

#include <core/StringTools.h>

#include <simulation.model/builder/ModelBuilderHolder.h>

#include <utility.reader.urdf/UrdfModelReader.h>
#include <utility.reader.urdf/parsers/RobotElementParser.h>

using namespace std;
using namespace nspace;

UrdfModelReader * UrdfModelReader::_instance =0;
UrdfModelReader::UrdfModelReader(){}

bool UrdfModelReader::parse(IModelBuilder & builder, std::istream & data){
  // read all data of inputstream
  string s = readToEnd(data);
  const char * text = s.c_str();

  // parse tinyxml2 document
  tinyxml2::XMLDocument document;
  int errorCode = document.Parse(text);

  //return false if document could not be parsed (this indicates that xml was not valid
  if(errorCode){
    ERROR("tinyxml2 Parse error number " <<errorCode);
    return false;
  }

  // create a robot parser and parse all nodes of document
  RobotElementParser robotParser(builder);
  robotParser.parseSiblingsOf(document.FirstChildElement());

}<commit_msg>fixed a unix issue<commit_after>#include "UrdfModelReader.h"

#include <tinyxml2/tinyxml2.h>
#include <fstream>

#include <core/StringTools.h>

#include <simulation.model/builder/ModelBuilderHolder.h>

#include <utility.reader.urdf/UrdfModelReader.h>
#include <utility.reader.urdf/parsers/RobotElementParser.h>

using namespace std;
using namespace nspace;

UrdfModelReader * UrdfModelReader::_instance =0;
UrdfModelReader::UrdfModelReader(){}

bool UrdfModelReader::parse(IModelBuilder & builder, std::istream & data){
  // read all data of inputstream
  string s = readToEnd(data);
  const char * text = s.c_str();

  // parse tinyxml2 document
  tinyxml2::XMLDocument document;
  int errorCode = document.Parse(text);

  //return false if document could not be parsed (this indicates that xml was not valid
  if(errorCode){
    ERROR("tinyxml2 Parse error number " <<errorCode);
    return false;
  }

  // create a robot parser and parse all nodes of document
  RobotElementParser robotParser(builder);
  robotParser.parseSiblingsOf(document.FirstChildElement());

  return true;
}
<|endoftext|>


<commit_before>
#include "FileRecordMgr.h"
#include "FreeList.h"
#include "Record.h"
#include "NewGenomeFile.h"

FileRecordMgr::FileRecordMgr(const string &filename)
: _fileIdx(-1),
  _filename(filename),
  _bufStreamMgr(NULL),
  _fileReader(NULL),
  _fileType(FileRecordTypeChecker::UNKNOWN_FILE_TYPE),
  _recordType(FileRecordTypeChecker::UNKNOWN_RECORD_TYPE),
  _recordMgr(NULL),
  _isSortedInput(false),
  _freeListBlockSize(512),
  _useFullBamTags(false),
  _prevStart(INT_MAX),
  _prevChromId(-1),
  _mustBeForward(false),
  _mustBeReverse(false),
  _totalRecordLength(0),
  _totalMergedRecordLength(0),
  _blockMgr(NULL),
  _bamReader(NULL),
  _hasGenomeFile(false),
  _genomeFile(NULL),
  _ioBufSize(0),
  _noEnforceCoordSort(false),
  _isGroupBy(false),
  _isCram(false)
 {
}

FileRecordMgr::~FileRecordMgr()
{
	close();
	//delete _recordMgr;
	_recordMgr = NULL;
}

bool FileRecordMgr::open(bool inheader){
	_bufStreamMgr = new BufferedStreamMgr(_filename);
	_bufStreamMgr->getTypeChecker().setInHeader(inheader);

	if (_ioBufSize > 0) _bufStreamMgr->setIoBufSize(_ioBufSize);

	if (_isGroupBy) {
		_bufStreamMgr->getTypeChecker().setIsGroupBy(true);
	}

	if (!_bufStreamMgr->init()) {
		cerr << "Error: unable to open file or unable to determine types for file " << _filename << endl;
		cerr << endl;
		cerr << "- Please ensure that your file is TAB delimited (e.g., cat -t FILE)." << endl;
		cerr << "- Also ensure that your file has integer chromosome coordinates in the " << endl
		     << "  expected columns (e.g., cols 2 and 3 for BED)." << endl;
		delete _bufStreamMgr;
		_bufStreamMgr = NULL;
		exit(1);
	}
	_fileType = _bufStreamMgr->getTypeChecker().getFileType();
	_recordType = _bufStreamMgr->getTypeChecker().getRecordType();

	//HACK: If groupBy and not Bam, over-ride file type.
	if (_isGroupBy && _fileType != FileRecordTypeChecker::BAM_FILE_TYPE)
	{
		_bufStreamMgr->getTypeChecker().setFileType(FileRecordTypeChecker::SINGLE_LINE_DELIM_TEXT_FILE_TYPE);
		_bufStreamMgr->getTypeChecker().setRecordType(FileRecordTypeChecker::NO_POS_PLUS_RECORD_TYPE);
		_fileType = FileRecordTypeChecker::SINGLE_LINE_DELIM_TEXT_FILE_TYPE;
		_recordType = FileRecordTypeChecker::NO_POS_PLUS_RECORD_TYPE;
		_isCram = _bufStreamMgr->getTypeChecker().isCram();
	}
	if (_fileType == FileRecordTypeChecker::UNKNOWN_FILE_TYPE || _recordType == FileRecordTypeChecker::UNKNOWN_RECORD_TYPE) {
		cerr << "Error: Unable to determine type for file " << _filename << endl;
		delete _bufStreamMgr;
		_bufStreamMgr = NULL;
		exit(1);
	}
	allocateFileReader(inheader);
	_recordMgr = new RecordMgr(_recordType, _freeListBlockSize);

	_fileReader->setFileName(_filename.c_str());
	_fileReader->setInputStream(_bufStreamMgr);
	if (!_fileReader->open()) {
		cerr << "Error: Types determined but can't open file " << _filename << endl;
		delete _bufStreamMgr;
		_bufStreamMgr = NULL;
		exit(1);
	}

	return true;
}

void FileRecordMgr::close(){
	delete _bufStreamMgr;
	_bufStreamMgr = NULL;

	if (_fileReader != NULL) {
		_fileReader->close();
		delete _fileReader;
		_fileReader = NULL;
	}
}

bool FileRecordMgr::eof(){
	return _fileReader->eof();
}

Record *FileRecordMgr::getNextRecord(RecordKeyVector *keyList)
{
	if (!_fileReader->isOpen()) {
		return NULL;
	}
	if (!_fileReader->readEntry()) {
		return NULL;
	}
	Record *record = NULL;
	record = _recordMgr->allocateRecord();
	if (!record->initFromFile(_fileReader)) {
		_recordMgr->deleteRecord(record);
		return NULL;
	}

	// If the record is unmapped, don't test for valid coords or sort order,
	// but still return it so the -v (noHit) option and the like will still
	// see it.

	if (!record->isUnmapped() ) {
		if (!record->coordsValid() && (record->getType() != FileRecordTypeChecker::NO_POS_PLUS_RECORD_TYPE)) {
			cerr << "Error: Invalid record in file " << _filename << ". Record is " << endl << *record << endl;
			exit(1);
		}

		//test for sorted order, if necessary.
		if (_isSortedInput && !_noEnforceCoordSort) {
			testInputSortOrder(record);
		}
	}
	assignChromId(record);
	_totalRecordLength += (unsigned long)(record->getEndPos() - record->getStartPos());
	if (keyList != NULL) {
		keyList->setKey(record);
	}
	record->setFileRecordManager(this);
	return record;
}

void FileRecordMgr::assignChromId(Record *record) {
	const string &currChrom = record->getChrName();
	if (currChrom != _prevChrom  && _hasGenomeFile) {
		_prevChromId = _genomeFile->getChromId(currChrom);
		record->setChromId(_prevChromId);
	} else {
		record->setChromId(_prevChromId);
	}
}

void FileRecordMgr::testInputSortOrder(Record *record)
{

	// Special: For BAM records that aren't mapped, we actually don't want
	// to test the sort order. Another ugly hack sponsored by the letters B, A, and M.
	if (record->isUnmapped()) {
		return;
	}

	const string &currChrom = record->getChrName();
	int currStart = record->getStartPos();
	if (record->isZeroLength()) {
		currStart++;
	}
	if (currChrom != _prevChrom) {
		if ( _foundChroms.find(currChrom) != _foundChroms.end()) {
			//this is a different chrom than the last record had, but we've already seen this chrom.
			sortError(record, false);
		} else {
			//new chrom has not been seen before.
			//TBD: test genome file for ChromId.
			if (_hasGenomeFile) {
				int currChromId = _genomeFile->getChromId(currChrom);
				if (currChromId < _prevChromId) {
					sortError(record, true);
				} else {
					_prevChromId = currChromId;
				}
			}
			_foundChroms.insert(currChrom);
			_prevChrom = currChrom;
			_prevStart = INT_MAX;
			record->setChromId(_prevChromId);
		}
	} else if (currStart < _prevStart) { //same chrom as last record, but with lower startPos, so still out of order.
		sortError(record, false);
	}
	_prevStart = currStart;

}

void FileRecordMgr::sortError(const Record *record, bool genomeFileError)
{
	if (genomeFileError) {
		cerr << "Error: Sorted input specified, but the file " << _filename << " has the following record with a different sort order than the genomeFile " <<
				_genomeFile->getGenomeFileName() << endl;
	} else {
		cerr << "Error: Sorted input specified, but the file " << _filename << " has the following out of order record" << endl;
	}
	cerr << *record << endl;
	exit(1);
}

void FileRecordMgr::deleteRecord(const Record *record) {
	_recordMgr->deleteRecord(record);
}

void FileRecordMgr::deleteRecord(RecordKeyVector *keyList) {
	_recordMgr->deleteRecord(keyList->getKey());
}

void FileRecordMgr::allocateFileReader(bool inheader)
{
	switch (_fileType) {
	case FileRecordTypeChecker::EMPTY_FILE_TYPE:
	case FileRecordTypeChecker::SINGLE_LINE_DELIM_TEXT_FILE_TYPE:
	case FileRecordTypeChecker::VCF_FILE_TYPE:
		_fileReader = new SingleLineDelimTextFileReader(_bufStreamMgr->getTypeChecker().getNumFields(), _bufStreamMgr->getTypeChecker().getDelimChar());
		static_cast<SingleLineDelimTextFileReader *>(_fileReader)->setInHeader(inheader);
		break;

	case FileRecordTypeChecker::BAM_FILE_TYPE:
		_fileReader = new BamFileReader();
		(static_cast<BamFileReader *>(_fileReader))->setUseTags(_useFullBamTags);
		(static_cast<BamFileReader *>(_fileReader))->setBamReader(_bufStreamMgr->getBamReader());
		break;
	default:
		break;
	}
	_fileReader->setFileIdx(_fileIdx);
}

const BamTools::RefVector & FileRecordMgr::getBamReferences() {
	// exta safety check to insure user checked the file type first.
	if (_fileType != FileRecordTypeChecker::BAM_FILE_TYPE) {
		cerr << "Error: Attempted to get BAM references from file " << _filename << ", which is NOT a BAM file." << endl;
		exit(1);
	}
	return static_cast<BamFileReader *>(_fileReader)->getReferences();
}
refs_t* FileRecordMgr::getCramRefs() {
	if (_fileType != FileRecordTypeChecker::BAM_FILE_TYPE) {
		cerr << "Error: Attempted to get BAM references from file " << _filename << ", which is NOT a BAM file." << endl;
		exit(1);
	}
	return static_cast<BamFileReader *>(_fileReader)->getCramRefs();
}
<commit_msg>Fix the CRAM detection<commit_after>
#include "FileRecordMgr.h"
#include "FreeList.h"
#include "Record.h"
#include "NewGenomeFile.h"

FileRecordMgr::FileRecordMgr(const string &filename)
: _fileIdx(-1),
  _filename(filename),
  _bufStreamMgr(NULL),
  _fileReader(NULL),
  _fileType(FileRecordTypeChecker::UNKNOWN_FILE_TYPE),
  _recordType(FileRecordTypeChecker::UNKNOWN_RECORD_TYPE),
  _recordMgr(NULL),
  _isSortedInput(false),
  _freeListBlockSize(512),
  _useFullBamTags(false),
  _prevStart(INT_MAX),
  _prevChromId(-1),
  _mustBeForward(false),
  _mustBeReverse(false),
  _totalRecordLength(0),
  _totalMergedRecordLength(0),
  _blockMgr(NULL),
  _bamReader(NULL),
  _hasGenomeFile(false),
  _genomeFile(NULL),
  _ioBufSize(0),
  _noEnforceCoordSort(false),
  _isGroupBy(false),
  _isCram(false)
 {
}

FileRecordMgr::~FileRecordMgr()
{
	close();
	//delete _recordMgr;
	_recordMgr = NULL;
}

bool FileRecordMgr::open(bool inheader){
	_bufStreamMgr = new BufferedStreamMgr(_filename);
	_bufStreamMgr->getTypeChecker().setInHeader(inheader);

	if (_ioBufSize > 0) _bufStreamMgr->setIoBufSize(_ioBufSize);

	if (_isGroupBy) {
		_bufStreamMgr->getTypeChecker().setIsGroupBy(true);
	}

	if (!_bufStreamMgr->init()) {
		cerr << "Error: unable to open file or unable to determine types for file " << _filename << endl;
		cerr << endl;
		cerr << "- Please ensure that your file is TAB delimited (e.g., cat -t FILE)." << endl;
		cerr << "- Also ensure that your file has integer chromosome coordinates in the " << endl
		     << "  expected columns (e.g., cols 2 and 3 for BED)." << endl;
		delete _bufStreamMgr;
		_bufStreamMgr = NULL;
		exit(1);
	}
	_fileType = _bufStreamMgr->getTypeChecker().getFileType();
	_recordType = _bufStreamMgr->getTypeChecker().getRecordType();

	//HACK: If groupBy and not Bam, over-ride file type.
	if (_isGroupBy && _fileType != FileRecordTypeChecker::BAM_FILE_TYPE)
	{
		_bufStreamMgr->getTypeChecker().setFileType(FileRecordTypeChecker::SINGLE_LINE_DELIM_TEXT_FILE_TYPE);
		_bufStreamMgr->getTypeChecker().setRecordType(FileRecordTypeChecker::NO_POS_PLUS_RECORD_TYPE);
		_fileType = FileRecordTypeChecker::SINGLE_LINE_DELIM_TEXT_FILE_TYPE;
		_recordType = FileRecordTypeChecker::NO_POS_PLUS_RECORD_TYPE;
	}

	if(_fileType == FileRecordTypeChecker::BAM_FILE_TYPE)
		_isCram = _bufStreamMgr->getTypeChecker().isCram();

	if (_fileType == FileRecordTypeChecker::UNKNOWN_FILE_TYPE || _recordType == FileRecordTypeChecker::UNKNOWN_RECORD_TYPE) {
		cerr << "Error: Unable to determine type for file " << _filename << endl;
		delete _bufStreamMgr;
		_bufStreamMgr = NULL;
		exit(1);
	}
	allocateFileReader(inheader);
	_recordMgr = new RecordMgr(_recordType, _freeListBlockSize);

	_fileReader->setFileName(_filename.c_str());
	_fileReader->setInputStream(_bufStreamMgr);
	if (!_fileReader->open()) {
		cerr << "Error: Types determined but can't open file " << _filename << endl;
		delete _bufStreamMgr;
		_bufStreamMgr = NULL;
		exit(1);
	}

	return true;
}

void FileRecordMgr::close(){
	delete _bufStreamMgr;
	_bufStreamMgr = NULL;

	if (_fileReader != NULL) {
		_fileReader->close();
		delete _fileReader;
		_fileReader = NULL;
	}
}

bool FileRecordMgr::eof(){
	return _fileReader->eof();
}

Record *FileRecordMgr::getNextRecord(RecordKeyVector *keyList)
{
	if (!_fileReader->isOpen()) {
		return NULL;
	}
	if (!_fileReader->readEntry()) {
		return NULL;
	}
	Record *record = NULL;
	record = _recordMgr->allocateRecord();
	if (!record->initFromFile(_fileReader)) {
		_recordMgr->deleteRecord(record);
		return NULL;
	}

	// If the record is unmapped, don't test for valid coords or sort order,
	// but still return it so the -v (noHit) option and the like will still
	// see it.

	if (!record->isUnmapped() ) {
		if (!record->coordsValid() && (record->getType() != FileRecordTypeChecker::NO_POS_PLUS_RECORD_TYPE)) {
			cerr << "Error: Invalid record in file " << _filename << ". Record is " << endl << *record << endl;
			exit(1);
		}

		//test for sorted order, if necessary.
		if (_isSortedInput && !_noEnforceCoordSort) {
			testInputSortOrder(record);
		}
	}
	assignChromId(record);
	_totalRecordLength += (unsigned long)(record->getEndPos() - record->getStartPos());
	if (keyList != NULL) {
		keyList->setKey(record);
	}
	record->setFileRecordManager(this);
	return record;
}

void FileRecordMgr::assignChromId(Record *record) {
	const string &currChrom = record->getChrName();
	if (currChrom != _prevChrom  && _hasGenomeFile) {
		_prevChromId = _genomeFile->getChromId(currChrom);
		record->setChromId(_prevChromId);
	} else {
		record->setChromId(_prevChromId);
	}
}

void FileRecordMgr::testInputSortOrder(Record *record)
{

	// Special: For BAM records that aren't mapped, we actually don't want
	// to test the sort order. Another ugly hack sponsored by the letters B, A, and M.
	if (record->isUnmapped()) {
		return;
	}

	const string &currChrom = record->getChrName();
	int currStart = record->getStartPos();
	if (record->isZeroLength()) {
		currStart++;
	}
	if (currChrom != _prevChrom) {
		if ( _foundChroms.find(currChrom) != _foundChroms.end()) {
			//this is a different chrom than the last record had, but we've already seen this chrom.
			sortError(record, false);
		} else {
			//new chrom has not been seen before.
			//TBD: test genome file for ChromId.
			if (_hasGenomeFile) {
				int currChromId = _genomeFile->getChromId(currChrom);
				if (currChromId < _prevChromId) {
					sortError(record, true);
				} else {
					_prevChromId = currChromId;
				}
			}
			_foundChroms.insert(currChrom);
			_prevChrom = currChrom;
			_prevStart = INT_MAX;
			record->setChromId(_prevChromId);
		}
	} else if (currStart < _prevStart) { //same chrom as last record, but with lower startPos, so still out of order.
		sortError(record, false);
	}
	_prevStart = currStart;

}

void FileRecordMgr::sortError(const Record *record, bool genomeFileError)
{
	if (genomeFileError) {
		cerr << "Error: Sorted input specified, but the file " << _filename << " has the following record with a different sort order than the genomeFile " <<
				_genomeFile->getGenomeFileName() << endl;
	} else {
		cerr << "Error: Sorted input specified, but the file " << _filename << " has the following out of order record" << endl;
	}
	cerr << *record << endl;
	exit(1);
}

void FileRecordMgr::deleteRecord(const Record *record) {
	_recordMgr->deleteRecord(record);
}

void FileRecordMgr::deleteRecord(RecordKeyVector *keyList) {
	_recordMgr->deleteRecord(keyList->getKey());
}

void FileRecordMgr::allocateFileReader(bool inheader)
{
	switch (_fileType) {
	case FileRecordTypeChecker::EMPTY_FILE_TYPE:
	case FileRecordTypeChecker::SINGLE_LINE_DELIM_TEXT_FILE_TYPE:
	case FileRecordTypeChecker::VCF_FILE_TYPE:
		_fileReader = new SingleLineDelimTextFileReader(_bufStreamMgr->getTypeChecker().getNumFields(), _bufStreamMgr->getTypeChecker().getDelimChar());
		static_cast<SingleLineDelimTextFileReader *>(_fileReader)->setInHeader(inheader);
		break;

	case FileRecordTypeChecker::BAM_FILE_TYPE:
		_fileReader = new BamFileReader();
		(static_cast<BamFileReader *>(_fileReader))->setUseTags(_useFullBamTags);
		(static_cast<BamFileReader *>(_fileReader))->setBamReader(_bufStreamMgr->getBamReader());
		break;
	default:
		break;
	}
	_fileReader->setFileIdx(_fileIdx);
}

const BamTools::RefVector & FileRecordMgr::getBamReferences() {
	// exta safety check to insure user checked the file type first.
	if (_fileType != FileRecordTypeChecker::BAM_FILE_TYPE) {
		cerr << "Error: Attempted to get BAM references from file " << _filename << ", which is NOT a BAM file." << endl;
		exit(1);
	}
	return static_cast<BamFileReader *>(_fileReader)->getReferences();
}
refs_t* FileRecordMgr::getCramRefs() {
	if (_fileType != FileRecordTypeChecker::BAM_FILE_TYPE) {
		cerr << "Error: Attempted to get BAM references from file " << _filename << ", which is NOT a BAM file." << endl;
		exit(1);
	}
	return static_cast<BamFileReader *>(_fileReader)->getCramRefs();
}
<|endoftext|>


<commit_before>/*	Eddie Rangel					*/
/*	COMS B35 OOP C++				*/
/*	CH4-B.CPP						*/
/*	2-13-03							*/
/*	Asks user for a double			*/
/*	HEX value in each byte			*/

#include<iostream.h>
#include<conio.h>
#include<ctype.h>

const int max_len = 5;
enum {EMPTY = -1, FULL = max_len - 1};
enum boolean{false,true}; 			/* This is for B.C. commons only */

class stack
{
	public:
		void reset(stack &stk);
		void push(double, stack &stk);
		double pop(stack &stk);
		double peek(const stack &stk);
		boolean full(const stack &stk);
		boolean empty(const stack &stk);
	private:
		double d[max_len];
		int top;
};

main()
{
	double nmbr;
	char c;
	stack mystack;
	clrscr();
	mystack.reset(mystack);
	cout << "Please enter +, -, P, C, or Q: ";
	cin >> c;
	c = toupper(c);
	while(c != 'Q')
	{
		switch(c)
		{
			case '+':
				if(mystack.full(mystack))
					cout << "Your stack is full\n";
				else
				{
					cout << "Please enter a number: ";
					cin >> nmbr;
					mystack.push(nmbr, mystack);
				}
				break;
			case '-':
				if(mystack.empty(mystack))
					cout << "Your stack is empty\n";
				else
				{
					cout << "This is your number: ";
					cout << mystack.pop(mystack) << '\n';
				}
				break;
			case 'P':
				if(mystack.empty(mystack))
					cout << "Your stack is empty\n";
				else
				{
					cout << "This is your number: ";
					cout << mystack.peek(mystack) << '\n';
				}
				break;
			case 'C':
				mystack.reset(mystack);
				break;
			default:
				cout << "You have entered invalid data!";
		}
		cout << "Please enter +, -, P, C, or Q: ";
		cin >> c;
		c = toupper(c);
	}
	return 0;
}
void stack::reset(stack &stk)
{
	stk.top = EMPTY;
	return;
}
void stack::push(double nmbr, stack &stk)
{
	stk.d[++stk.top] = nmbr;
	return;
}
double stack::pop(stack &stk)
{
	return stk.d[stk.top--];
}
double stack::peek(const stack &stk)
{
	return stk.d[stk.top];
}
boolean stack::full(const stack &stk)
{
	return (boolean)(stk.top == FULL);
}
boolean stack::empty(const stack &stk)
{
	return (boolean)(stk.top == EMPTY);
}

<commit_msg>Stack Implementation<commit_after>/*	Eddie Rangel					*/

#include <cstdlib>
#include <iostream>
using namespace std;

const int max_len = 5;
enum {EMPTY = -1, FULL = max_len - 1};

class stack
{
	public:
		void reset(stack &stk);
		void push(double, stack &stk);
		double pop(stack &stk);
		double peek(const stack &stk);
		bool full(const stack &stk);
		bool empty(const stack &stk);
	private:
		double d[max_len];
		int top;
};

main()
{
	double nmbr;
	char c;
	stack mystack;
	mystack.reset(mystack);
	cout << "Please enter +, -, P, C, or Q: ";
	cin >> c;
	c = toupper(c);
	while(c != 'Q')
	{
		switch(c)
		{
			case '+':
				if(mystack.full(mystack))
					cout << "Your stack is full\n";
				else
				{
					cout << "Please enter a number: ";
					cin >> nmbr;
					mystack.push(nmbr, mystack);
				}
				break;
			case '-':
				if(mystack.empty(mystack))
					cout << "Your stack is empty\n";
				else
				{
					cout << "This is your number: ";
					cout << mystack.pop(mystack) << '\n';
				}
				break;
			case 'P':
				if(mystack.empty(mystack))
					cout << "Your stack is empty\n";
				else
				{
					cout << "This is your number: ";
					cout << mystack.peek(mystack) << '\n';
				}
				break;
			case 'C':
				mystack.reset(mystack);
				break;
			default:
				cout << "You have entered invalid data!";
		}
		cout << "Please enter +, -, P, C, or Q: ";
		cin >> c;
		c = toupper(c);
	}
	return 0;
}
void stack::reset(stack &stk)
{
	stk.top = EMPTY;
	return;
}
void stack::push(double nmbr, stack &stk)
{
	stk.d[++stk.top] = nmbr;
	return;
}
double stack::pop(stack &stk)
{
	return stk.d[stk.top--];
}
double stack::peek(const stack &stk)
{
	return stk.d[stk.top];
}
bool stack::full(const stack &stk)
{
	return (bool)(stk.top == FULL);
}
bool stack::empty(const stack &stk)
{
	return (bool)(stk.top == EMPTY);
}

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *               2013 Oleksandr Novychenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/global.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/util/trim.hpp>
#include <mapnik/global.hpp> // for int2net

// boost
#include <boost/cstdint.hpp> // for boost::int16_t
#include <boost/scoped_array.hpp>

#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp> // needed for wrapping the transcoder

// stl
#include <sstream>
#include <string>

#include "mongodb_featureset.hpp"
#include "mongodb_converter.hpp"

using mapnik::geometry_type;
using mapnik::byte;
using mapnik::geometry_utils;
using mapnik::feature_factory;
using mapnik::context_ptr;

mongodb_featureset::mongodb_featureset(const boost::shared_ptr<mongo::DBClientCursor> &rs,
                                       const context_ptr &ctx,
                                       const std::string &encoding)
    : rs_(rs),
      ctx_(ctx),
      tr_(new transcoder(encoding)),
      feature_id_(0) {
}

mongodb_featureset::~mongodb_featureset() {
}

feature_ptr mongodb_featureset::next() {
    while (rs_->more()) {
        mapnik::feature_ptr feature(new mapnik::Feature(ctx_, feature_id_));

        try {
            mongo::BSONObj bson = rs_->nextSafe();
            mongo::BSONElement geom = bson["geometry"];
            mongo::BSONElement prop = bson["properties"];

            if (geom.type() != mongo::Object)
                continue;

            mongodb_converter::convert_geometry(bson["geometry"], feature);

            if (prop.type() == mongo::Object)
                for (mongo::BSONObjIterator i = prop.wrap().begin(); i.more(); ) {
                    mongo::BSONElement e = i.next();
                    std::string name(e.fieldName());

                    switch (e.type()) {
                    case mongo::String:
                        feature->put(name, tr_->transcode(e.String().c_str()));
                        break;

                    case mongo::NumberDouble:
                        feature->put(name, e.Double());
                        break;

                    case mongo::NumberLong:
                        feature->put<mapnik::value_integer>(name, e.Long());
                        break;

                    case mongo::NumberInt:
                        feature->put<mapnik::value_integer>(name, e.Int());
                        break;

                    default:
                        break;
                    }
                }
        } catch(mongo::DBException &de) {
            std::string err_msg = "Mongodb Plugin: ";
            err_msg += de.toString();
            err_msg += "\n";
            throw mapnik::datasource_exception(err_msg);
        }

        ++feature_id_;
        return feature;
    }

    return feature_ptr();
}
<commit_msg>fixed failure of load properties<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *               2013 Oleksandr Novychenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/global.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/util/trim.hpp>
#include <mapnik/global.hpp> // for int2net

// boost
#include <boost/cstdint.hpp> // for boost::int16_t
#include <boost/scoped_array.hpp>

#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp> // needed for wrapping the transcoder

// stl
#include <sstream>
#include <string>

#include "mongodb_featureset.hpp"
#include "mongodb_converter.hpp"

using mapnik::geometry_type;
using mapnik::byte;
using mapnik::geometry_utils;
using mapnik::feature_factory;
using mapnik::context_ptr;

mongodb_featureset::mongodb_featureset(const boost::shared_ptr<mongo::DBClientCursor> &rs,
                                       const context_ptr &ctx,
                                       const std::string &encoding)
    : rs_(rs),
      ctx_(ctx),
      tr_(new transcoder(encoding)),
      feature_id_(0) {
}

mongodb_featureset::~mongodb_featureset() {
}

feature_ptr mongodb_featureset::next() {
    while (rs_->more()) {
        mapnik::feature_ptr feature(new mapnik::Feature(ctx_, feature_id_));

        try {
            mongo::BSONObj bson = rs_->nextSafe();
            mongo::BSONElement geom = bson["geometry"];
            mongo::BSONElement prop = bson["properties"];

            if (geom.type() != mongo::Object)
                continue;

            mongodb_converter::convert_geometry(bson["geometry"], feature);

            if (prop.type() == mongo::Object)
                for (mongo::BSONObjIterator i = prop.Obj().begin(); i.more(); ) {
                    mongo::BSONElement e = i.next();
                    std::string name(e.fieldName());

                    switch (e.type()) {
                    case mongo::String:
                        feature->put_new(name, tr_->transcode(e.String().c_str()));
                        break;

                    case mongo::NumberDouble:
                        feature->put_new(name, e.Double());
                        break;

                    case mongo::NumberLong:
                        feature->put_new<mapnik::value_integer>(name, e.Long());
                        break;

                    case mongo::NumberInt:
                        feature->put_new<mapnik::value_integer>(name, e.Int());
                        break;

                    default:
                        std::cout << "ignored" << std::endl;
                        break;
                    }
                }
        } catch(mongo::DBException &de) {
            std::string err_msg = "Mongodb Plugin: ";
            err_msg += de.toString();
            err_msg += "\n";
            throw mapnik::datasource_exception(err_msg);
        }

        ++feature_id_;
        return feature;
    }

    return feature_ptr();
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  Euchre
//
//  Created by Dillon Hammond on 9/12/14.
//  Copyright (c) 2014 Learning. All rights reserved.
//

#define GLEW_STATIC
#include "GL/glew.h"
#include <SDL2/SDL.h>
#include "SOIL.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include <iostream>
#include <fstream>
#include <vector>

GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) {

	// Create the shaders
	GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
	GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

	// Read the Vertex Shader code from the file
	std::string VertexShaderCode;
	std::ifstream VertexShaderStream;
	VertexShaderStream.open(vertex_file_path);
	if(VertexShaderStream.is_open()) {
		std::string Line = "";
		while(getline(VertexShaderStream, Line)) {
			VertexShaderCode += "\n" + Line;
		}
		VertexShaderStream.close();
	}

	// Read the Fragment Shader code from the file
	std::string FragmentShaderCode;
	std::ifstream FragmentShaderStream;
	FragmentShaderStream.open(fragment_file_path);
	if(FragmentShaderStream.is_open()){
		std::string Line = "";
		while(getline(FragmentShaderStream, Line)) {
			FragmentShaderCode += "\n" + Line;
		}
		FragmentShaderStream.close();
	}
	GLint Result;
	// Compile Vertex Shader
	const char* VertexSourcePointer = VertexShaderCode.c_str();
	glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
	glCompileShader(VertexShaderID);
	glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
		if (Result == GL_FALSE) {
			std::cout << "NOOOV" << std::endl;
			std::cout << VertexSourcePointer << std::endl;
		}

	// Compile Fragment Shader
	const char* FragmentSourcePointer = FragmentShaderCode.c_str();
	glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
	glCompileShader(FragmentShaderID);
	glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
		if (Result == GL_FALSE) {
			std::cout << "NOOOF" << std::endl;
			std::cout << FragmentSourcePointer << std::endl;
		}

	// Link the program
	GLuint ProgramID = glCreateProgram();
	glAttachShader(ProgramID, VertexShaderID);
	glAttachShader(ProgramID, FragmentShaderID);
	glLinkProgram(ProgramID);

	glDeleteShader(VertexShaderID);
	glDeleteShader(FragmentShaderID);

	return ProgramID;
}

SDL_Window* createWindow(const char* title, int x, int y, int w, int h, Uint32 flags) {
	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_Window *window = SDL_CreateWindow(title, x, y, w, h, flags);
	return window;
}

void LoadTextures(std::vector<GLuint> textures, const char* filename, const char* texName, GLuint shaderProgram, int texNum) {
	int width, height;
	unsigned char* image;

	glActiveTexture(GL_TEXTURE0 + texNum);

	glBindTexture(GL_TEXTURE_2D, textures.at(texNum));
	image = SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGB);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
	SOIL_free_image_data(image);
	glUniform1i(glGetUniformLocation(shaderProgram, "backGround"), texNum);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}

template<class vecTYPE> // Allows for a vector of any type to be made and returned!
std::vector<vecTYPE> LoadData(const char* file_path) {
	// Read Vertices in from a file
	std::vector<vecTYPE> vertices;
	std::string fileCode;
	std::ifstream fileStream;
	fileStream.open(file_path);
	if(fileStream.is_open()) {
		std::string Line;
		while(getline(fileStream, Line, ',')) {
			fileCode = Line;
			float numRead = std::stof(fileCode); // std::stof converts a string to a float
			vertices.push_back(numRead); // When the value is pushed to the vertex, it is casted automatically
		}
		fileStream.close();
	}
	return vertices;
}

template<class vecTYPE> // Redefine new vecTYPE
GLuint makeBufferObject(GLsizei numBuffers, GLenum target, GLenum usage, std::vector<vecTYPE> data) {
	GLuint buffer;
	glGenBuffers(numBuffers, &buffer);
	glBindBuffer(target, buffer);
	glBufferData(target, data.size() * sizeof(vecTYPE), &data.at(0), usage);

	return buffer;
}

int main() {
	SDL_Window* window = createWindow("Euchre", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(window);

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	glewInit();

	// Create Vertex Array Object
	GLuint vao;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// Create a vector populated by text file data that describes the coordinates of the triangles to be drawn
	std::vector<float> bgPosition = LoadData<float>("./Resources/bgPosition.txt");

	// Create a Position Buffer Object and copy the vector data to it
	GLuint positionBuffer = makeBufferObject(1, GL_ARRAY_BUFFER, GL_STATIC_DRAW, bgPosition);

	// Create a vector populated by text file data that has the color of the triangles to be drawn
	std::vector<float> bgColor = LoadData<float>("./Resources/bgColor.txt");

	// Create a Color Buffer Object and copy the vector data to it
	GLuint colorBuffer = makeBufferObject(1, GL_ARRAY_BUFFER, GL_STATIC_DRAW, bgColor);

	// Create a vector populated by text file data that has the location of the texture image
	std::vector<float> bgTexture = LoadData<float>("./Resources/bgTexture.txt");

	// Create a Texture Buffer Object and copy the vector data to it
	GLuint textureBuffer = makeBufferObject(1, GL_ARRAY_BUFFER, GL_STATIC_DRAW, bgTexture);

	// Create a vector populated by text file data that describes the order that an object is drawn in
	std::vector<GLuint> drawOrder = LoadData<GLuint>("./Resources/drawOrder.txt");

	// Create an Element Buffer Object and copy the vector data to it
	GLuint elementBuffer = makeBufferObject(1, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW, drawOrder);

	GLuint shaderProgram = LoadShaders("./Resources/vertexShader.txt", "./Resources/fragmentShader.txt");
	glUseProgram(shaderProgram);

	// Specify the layout of the vertex data
	GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
	glEnableVertexAttribArray(posAttrib);
	glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
	glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);

	// Specify the color attributes
	GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
	glEnableVertexAttribArray(colAttrib);
	glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
	glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);

	// Specifiy the texture usage
	GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
	glEnableVertexAttribArray(texAttrib);
	glBindBuffer(GL_ARRAY_BUFFER, textureBuffer);
	glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);

	std::vector<GLuint> textures(1,0);
	LoadTextures(textures, "./Resources/Background.png", "backGround", shaderProgram, 0);

	SDL_Event windowEvent;
	while (true) {
		if (SDL_PollEvent(&windowEvent)) {
			if (windowEvent.type == SDL_QUIT) {
				break;
			}
		}

		// Clear the screen to black
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		// Draw a rectangle from the 2 triangles using 6 indices
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

		SDL_GL_SwapWindow(window);
	}
	glDeleteTextures(static_cast<GLsizei>(textures.size()), &textures.at(0)); // Casted to remove warning about precision loss (this doesn't matter)

	glDeleteProgram(shaderProgram);

	glDeleteBuffers(1, &elementBuffer);
	glDeleteBuffers(1, &positionBuffer);
	glDeleteBuffers(1, &colorBuffer);
	glDeleteBuffers(1, &textureBuffer);

	glDeleteVertexArrays(1, &vao);

	SDL_GL_DeleteContext(context);
	return 0;
}<commit_msg>Comment<commit_after>//
//  main.cpp
//  Euchre
//
//  Created by Dillon Hammond on 9/12/14.
//  Copyright (c) 2014 Learning. All rights reserved.
//

#define GLEW_STATIC
#include "GL/glew.h"
#include <SDL2/SDL.h>
#include "SOIL.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include <iostream>
#include <fstream>
#include <vector>

GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) {

	// Create the shaders
	GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
	GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

	// Read the Vertex Shader code from the file
	std::string VertexShaderCode;
	std::ifstream VertexShaderStream;
	VertexShaderStream.open(vertex_file_path);
	if(VertexShaderStream.is_open()) {
		std::string Line = "";
		while(getline(VertexShaderStream, Line)) {
			VertexShaderCode += "\n" + Line;
		}
		VertexShaderStream.close();
	}

	// Read the Fragment Shader code from the file
	std::string FragmentShaderCode;
	std::ifstream FragmentShaderStream;
	FragmentShaderStream.open(fragment_file_path);
	if(FragmentShaderStream.is_open()){
		std::string Line = "";
		while(getline(FragmentShaderStream, Line)) {
			FragmentShaderCode += "\n" + Line;
		}
		FragmentShaderStream.close();
	}
	GLint Result;
	// Compile Vertex Shader
	const char* VertexSourcePointer = VertexShaderCode.c_str();
	glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
	glCompileShader(VertexShaderID);
	glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
		if (Result == GL_FALSE) {
			std::cout << "NOOOV" << std::endl;
			std::cout << VertexSourcePointer << std::endl;
		}

	// Compile Fragment Shader
	const char* FragmentSourcePointer = FragmentShaderCode.c_str();
	glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
	glCompileShader(FragmentShaderID);
	glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
		if (Result == GL_FALSE) {
			std::cout << "NOOOF" << std::endl;
			std::cout << FragmentSourcePointer << std::endl;
		}

	// Link the program
	GLuint ProgramID = glCreateProgram();
	glAttachShader(ProgramID, VertexShaderID);
	glAttachShader(ProgramID, FragmentShaderID);
	glLinkProgram(ProgramID);

	glDeleteShader(VertexShaderID);
	glDeleteShader(FragmentShaderID);

	return ProgramID;
}

SDL_Window* createWindow(const char* title, int x, int y, int w, int h, Uint32 flags) {
	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_Window *window = SDL_CreateWindow(title, x, y, w, h, flags);
	return window;
}

void LoadTextures(std::vector<GLuint> textures, const char* filename, const char* texName, GLuint shaderProgram, int texNum) {
	int width, height;
	unsigned char* image;

	glActiveTexture(GL_TEXTURE0 + texNum);

	glBindTexture(GL_TEXTURE_2D, textures.at(texNum));
	image = SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGB);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
	SOIL_free_image_data(image);
	glUniform1i(glGetUniformLocation(shaderProgram, "backGround"), texNum);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}

template<class vecTYPE> // Allows for a vector of any type to be made and returned!
std::vector<vecTYPE> LoadData(const char* file_path) {
	// Read Vertices in from a file
	std::vector<vecTYPE> vertices;
	std::string fileCode;
	std::ifstream fileStream;
	fileStream.open(file_path);
	if(fileStream.is_open()) {
		std::string Line;
		while(getline(fileStream, Line, ',')) {
			fileCode = Line;
			float numRead = std::stof(fileCode); // std::stof converts a string to a float
			vertices.push_back(numRead); // When the value is pushed to the vertex, it is casted automatically
		}
		fileStream.close();
	}
	return vertices;
}

template<class vecTYPE> // Redefine new vecTYPE
GLuint makeBufferObject(GLsizei numBuffers, GLenum target, GLenum usage, std::vector<vecTYPE> data) {
	GLuint buffer;
	glGenBuffers(numBuffers, &buffer);
	glBindBuffer(target, buffer);
	glBufferData(target, data.size() * sizeof(vecTYPE), &data.at(0), usage);

	return buffer;
}

int main() {
	SDL_Window* window = createWindow("Euchre", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(window);

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	glewInit();

	// Create Vertex Array Object
	GLuint vao;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// Create a vector populated by text file data that describes the coordinates of the triangles to be drawn
	std::vector<float> bgPosition = LoadData<float>("./Resources/bgPosition.txt");

	// Create a Position Buffer Object and copy the vector data to it
	GLuint positionBuffer = makeBufferObject(1, GL_ARRAY_BUFFER, GL_STATIC_DRAW, bgPosition);

	// Create a vector populated by text file data that has the color of the triangles to be drawn
	std::vector<float> bgColor = LoadData<float>("./Resources/bgColor.txt");

	// Create a Color Buffer Object and copy the vector data to it
	GLuint colorBuffer = makeBufferObject(1, GL_ARRAY_BUFFER, GL_STATIC_DRAW, bgColor);

	// Create a vector populated by text file data that has the location of the texture image
	std::vector<float> bgTexture = LoadData<float>("./Resources/bgTexture.txt");

	// Create a Texture Buffer Object and copy the vector data to it
	GLuint textureBuffer = makeBufferObject(1, GL_ARRAY_BUFFER, GL_STATIC_DRAW, bgTexture);

	// Create a vector populated by text file data that describes the order that an object is drawn in
	std::vector<GLuint> drawOrder = LoadData<GLuint>("./Resources/drawOrder.txt");

	// Create an Element Buffer Object and copy the vector data to it
	GLuint elementBuffer = makeBufferObject(1, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW, drawOrder);

	GLuint shaderProgram = LoadShaders("./Resources/vertexShader.txt", "./Resources/fragmentShader.txt");
	glUseProgram(shaderProgram);

	// Specify the layout of the vertex data
	GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
	glEnableVertexAttribArray(posAttrib);
	glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
	glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);

	// Specify the color attributes
	GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
	glEnableVertexAttribArray(colAttrib);
	glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
	glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);

	// Specifiy the texture usage
	GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
	glEnableVertexAttribArray(texAttrib);
	glBindBuffer(GL_ARRAY_BUFFER, textureBuffer);
	glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);

	std::vector<GLuint> textures(1,0);
	LoadTextures(textures, "./Resources/Background.png", "backGround", shaderProgram, 0);

	SDL_Event windowEvent;
	while (true) {
		if (SDL_PollEvent(&windowEvent)) {
			if (windowEvent.type == SDL_QUIT) {
				break;
			}
		}

		// Clear the screen to black
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		// Draw a rectangle from the 2 triangles using 6 indices
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

		SDL_GL_SwapWindow(window);
	}
	glDeleteTextures(static_cast<GLsizei>(textures.size()), &textures.at(0)); // Casted to remove warning about precision loss (this doesn't matter)

	glDeleteProgram(shaderProgram);

	// Delete all the buffers!
	glDeleteBuffers(1, &elementBuffer);
	glDeleteBuffers(1, &positionBuffer);
	glDeleteBuffers(1, &colorBuffer);
	glDeleteBuffers(1, &textureBuffer);

	glDeleteVertexArrays(1, &vao);

	SDL_GL_DeleteContext(context);
	return 0;
}<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/kernel/xobject.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

SHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_state, KernelState* state) {
  // r3 = ptr to info?
  //   +0 = -4
  //   +4 = name ptr
  //   +8 = 0
  // r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType
  // r5 = 0
  // r6 = out_ptr (handle?)
  uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);
  uint32_t object_type_ptr = SHIM_GET_ARG_32(1);
  uint32_t unk = SHIM_GET_ARG_32(2);
  uint32_t handle_ptr = SHIM_GET_ARG_32(3);

  uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4);
  X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr);
  auto name = name_str.to_string();

  XELOGD("ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)",
         obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);

  X_HANDLE handle = X_INVALID_HANDLE_VALUE;
  X_STATUS result = state->object_table()->GetObjectByName(name, &handle);
  if (XSUCCEEDED(result)) {
    SHIM_SET_MEM_32(handle_ptr, handle);
  }

  SHIM_SET_RETURN_32(result);
}

SHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_state,
                                         KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);
  uint32_t object_type_ptr = SHIM_GET_ARG_32(1);
  uint32_t out_object_ptr = SHIM_GET_ARG_32(2);

  XELOGD("ObReferenceObjectByHandle(%.8X, %.8X, %.8X)", handle, object_type_ptr,
         out_object_ptr);

  X_STATUS result = X_STATUS_INVALID_HANDLE;

  XObject* object = NULL;
  result = state->object_table()->GetObject(handle, &object);
  if (XSUCCEEDED(result)) {
    // TODO(benvanik): verify type with object_type_ptr

    // TODO(benvanik): get native value, if supported.
    uint32_t native_ptr;
    switch (object_type_ptr) {
      case 0xD01BBEEF:  // ExThreadObjectType
      {
        XThread* thread = (XThread*)object;
        native_ptr = thread->thread_state_ptr();
      } break;
      default:
        assert_unhandled_case(object_type_ptr);
        native_ptr = 0xDEADF00D;
        break;
    }

    if (out_object_ptr) {
      SHIM_SET_MEM_32(out_object_ptr, native_ptr);
    }
  }

  SHIM_SET_RETURN_32(result);
}

SHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t native_ptr = SHIM_GET_ARG_32(0);

  XELOGD("ObDereferenceObject(%.8X)", native_ptr);

  // Check if a dummy value from ObReferenceObjectByHandle.
  if (native_ptr == 0xDEADF00D) {
    SHIM_SET_RETURN_32(0);
    return;
  }

  void* object_ptr = SHIM_MEM_ADDR(native_ptr);
  XObject* object = XObject::GetObject(state, object_ptr);
  if (object) {
    object->Release();
  }

  SHIM_SET_RETURN_32(0);
}

SHIM_CALL NtDuplicateObject_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);
  uint32_t new_handle_ptr = SHIM_GET_ARG_32(1);
  uint32_t options = SHIM_GET_ARG_32(2);

  XELOGD("NtDuplicateObject(%.8X, %.8X, %.8X)", handle, new_handle_ptr,
         options);

  // NOTE: new_handle_ptr can be zero to just close a handle.
  // NOTE: this function seems to be used to get the current thread handle
  //       (passed handle=-2).
  // Because this function is not like the NT version (with cross process
  // mumble), my guess is that it's just use for getting real handles.
  // So we just fake it and properly reference count but not actually make
  // different handles.

  X_STATUS result = X_STATUS_INVALID_HANDLE;

  XObject* obj = 0;
  result = state->object_table()->GetObject(handle, &obj);
  if (XSUCCEEDED(result)) {
    obj->RetainHandle();
    uint32_t new_handle = obj->handle();
    if (new_handle_ptr) {
      SHIM_SET_MEM_32(new_handle_ptr, new_handle);
    }

    if (options == 1 /* DUPLICATE_CLOSE_SOURCE */) {
      // Always close the source object.
      state->object_table()->RemoveHandle(handle);
    }
    obj->Release();
  }

  SHIM_SET_RETURN_32(result);
}

SHIM_CALL NtClose_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);

  XELOGD("NtClose(%.8X)", handle);

  X_STATUS result = X_STATUS_INVALID_HANDLE;

  result = state->object_table()->RemoveHandle(handle);

  SHIM_SET_RETURN_32(result);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xboxkrnl::RegisterObExports(
    xe::cpu::ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xboxkrnl.exe", ObOpenObjectByName, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", ObReferenceObjectByHandle, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", ObDereferenceObject, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", NtDuplicateObject, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", NtClose, state);
}
<commit_msg>Adding case for ObReferenceObjectByHandle, but impl still todo.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/kernel/xobject.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

SHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_state, KernelState* state) {
  // r3 = ptr to info?
  //   +0 = -4
  //   +4 = name ptr
  //   +8 = 0
  // r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType
  // r5 = 0
  // r6 = out_ptr (handle?)
  uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);
  uint32_t object_type_ptr = SHIM_GET_ARG_32(1);
  uint32_t unk = SHIM_GET_ARG_32(2);
  uint32_t handle_ptr = SHIM_GET_ARG_32(3);

  uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4);
  X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr);
  auto name = name_str.to_string();

  XELOGD("ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)",
         obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);

  X_HANDLE handle = X_INVALID_HANDLE_VALUE;
  X_STATUS result = state->object_table()->GetObjectByName(name, &handle);
  if (XSUCCEEDED(result)) {
    SHIM_SET_MEM_32(handle_ptr, handle);
  }

  SHIM_SET_RETURN_32(result);
}

SHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_state,
                                         KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);
  uint32_t object_type_ptr = SHIM_GET_ARG_32(1);
  uint32_t out_object_ptr = SHIM_GET_ARG_32(2);

  XELOGD("ObReferenceObjectByHandle(%.8X, %.8X, %.8X)", handle, object_type_ptr,
         out_object_ptr);

  X_STATUS result = X_STATUS_INVALID_HANDLE;

  XObject* object = NULL;
  result = state->object_table()->GetObject(handle, &object);
  if (XSUCCEEDED(result)) {
    // TODO(benvanik): verify type with object_type_ptr

    // TODO(benvanik): get native value, if supported.
    uint32_t native_ptr;
    switch (object_type_ptr) {
      case 0x00000000: {  // whatever?
        switch (object->type()) {
          // TODO(benvanik): need to track native_ptr in XObject, allocate as
          // needed?
          /*case XObject::kTypeEvent:
            XEvent* ev = (XEvent*)object;
            break;*/
          case XObject::kTypeThread:
            XThread* thread = (XThread*)object;
            native_ptr = thread->thread_state_ptr();
            break;
          default:
            assert_unhandled_case(object->type());
            native_ptr = 0xDEADF00D;
            break;
        }
      } break;
      case 0xD01BBEEF: {  // ExThreadObjectType
        XThread* thread = (XThread*)object;
        native_ptr = thread->thread_state_ptr();
      } break;
      default:
        assert_unhandled_case(object_type_ptr);
        native_ptr = 0xDEADF00D;
        break;
    }

    if (out_object_ptr) {
      SHIM_SET_MEM_32(out_object_ptr, native_ptr);
    }
  }

  SHIM_SET_RETURN_32(result);
}

SHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t native_ptr = SHIM_GET_ARG_32(0);

  XELOGD("ObDereferenceObject(%.8X)", native_ptr);

  // Check if a dummy value from ObReferenceObjectByHandle.
  if (native_ptr == 0xDEADF00D) {
    SHIM_SET_RETURN_32(0);
    return;
  }

  void* object_ptr = SHIM_MEM_ADDR(native_ptr);
  XObject* object = XObject::GetObject(state, object_ptr);
  if (object) {
    object->Release();
  }

  SHIM_SET_RETURN_32(0);
}

SHIM_CALL NtDuplicateObject_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);
  uint32_t new_handle_ptr = SHIM_GET_ARG_32(1);
  uint32_t options = SHIM_GET_ARG_32(2);

  XELOGD("NtDuplicateObject(%.8X, %.8X, %.8X)", handle, new_handle_ptr,
         options);

  // NOTE: new_handle_ptr can be zero to just close a handle.
  // NOTE: this function seems to be used to get the current thread handle
  //       (passed handle=-2).
  // Because this function is not like the NT version (with cross process
  // mumble), my guess is that it's just use for getting real handles.
  // So we just fake it and properly reference count but not actually make
  // different handles.

  X_STATUS result = X_STATUS_INVALID_HANDLE;

  XObject* obj = 0;
  result = state->object_table()->GetObject(handle, &obj);
  if (XSUCCEEDED(result)) {
    obj->RetainHandle();
    uint32_t new_handle = obj->handle();
    if (new_handle_ptr) {
      SHIM_SET_MEM_32(new_handle_ptr, new_handle);
    }

    if (options == 1 /* DUPLICATE_CLOSE_SOURCE */) {
      // Always close the source object.
      state->object_table()->RemoveHandle(handle);
    }
    obj->Release();
  }

  SHIM_SET_RETURN_32(result);
}

SHIM_CALL NtClose_shim(PPCContext* ppc_state, KernelState* state) {
  uint32_t handle = SHIM_GET_ARG_32(0);

  XELOGD("NtClose(%.8X)", handle);

  X_STATUS result = X_STATUS_INVALID_HANDLE;

  result = state->object_table()->RemoveHandle(handle);

  SHIM_SET_RETURN_32(result);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xboxkrnl::RegisterObExports(
    xe::cpu::ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xboxkrnl.exe", ObOpenObjectByName, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", ObReferenceObjectByHandle, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", ObDereferenceObject, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", NtDuplicateObject, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", NtClose, state);
}
<|endoftext|>