text
stringlengths
8
6.88M
#include <iostream> using namespace std; int main() { string var1 = "Esto es un ejemplo"; cout << var1[3] << endl; return 0; }
#ifndef SYSTEM_H #define SYSTEM_H class System { public: System(); int init(const char* title); private: }; #endif
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.System.Threading.0.h" #include "Windows.Foundation.0.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::System::Threading { struct __declspec(uuid("b6bf67dd-84bd-44f8-ac1c-93ebcb9dba91")) __declspec(novtable) IThreadPoolStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_RunAsync(Windows::System::Threading::WorkItemHandler * handler, Windows::Foundation::IAsyncAction ** operation) = 0; virtual HRESULT __stdcall abi_RunWithPriorityAsync(Windows::System::Threading::WorkItemHandler * handler, winrt::Windows::System::Threading::WorkItemPriority priority, Windows::Foundation::IAsyncAction ** operation) = 0; virtual HRESULT __stdcall abi_RunWithPriorityAndOptionsAsync(Windows::System::Threading::WorkItemHandler * handler, winrt::Windows::System::Threading::WorkItemPriority priority, winrt::Windows::System::Threading::WorkItemOptions options, Windows::Foundation::IAsyncAction ** operation) = 0; }; struct __declspec(uuid("594ebe78-55ea-4a88-a50d-3402ae1f9cf2")) __declspec(novtable) IThreadPoolTimer : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_Period(Windows::Foundation::TimeSpan * value) = 0; virtual HRESULT __stdcall get_Delay(Windows::Foundation::TimeSpan * value) = 0; virtual HRESULT __stdcall abi_Cancel() = 0; }; struct __declspec(uuid("1a8a9d02-e482-461b-b8c7-8efad1cce590")) __declspec(novtable) IThreadPoolTimerStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall abi_CreatePeriodicTimer(Windows::System::Threading::TimerElapsedHandler * handler, Windows::Foundation::TimeSpan period, Windows::System::Threading::IThreadPoolTimer ** timer) = 0; virtual HRESULT __stdcall abi_CreateTimer(Windows::System::Threading::TimerElapsedHandler * handler, Windows::Foundation::TimeSpan delay, Windows::System::Threading::IThreadPoolTimer ** timer) = 0; virtual HRESULT __stdcall abi_CreatePeriodicTimerWithCompletion(Windows::System::Threading::TimerElapsedHandler * handler, Windows::Foundation::TimeSpan period, Windows::System::Threading::TimerDestroyedHandler * destroyed, Windows::System::Threading::IThreadPoolTimer ** timer) = 0; virtual HRESULT __stdcall abi_CreateTimerWithCompletion(Windows::System::Threading::TimerElapsedHandler * handler, Windows::Foundation::TimeSpan delay, Windows::System::Threading::TimerDestroyedHandler * destroyed, Windows::System::Threading::IThreadPoolTimer ** timer) = 0; }; struct __declspec(uuid("34ed19fa-8384-4eb9-8209-fb5094eeec35")) __declspec(novtable) TimerDestroyedHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::System::Threading::IThreadPoolTimer * timer) = 0; }; struct __declspec(uuid("faaea667-fbeb-49cb-adb2-71184c556e43")) __declspec(novtable) TimerElapsedHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::System::Threading::IThreadPoolTimer * timer) = 0; }; struct __declspec(uuid("1d1a8b8b-fa66-414f-9cbd-b65fc99d17fa")) __declspec(novtable) WorkItemHandler : IUnknown { virtual HRESULT __stdcall abi_Invoke(Windows::Foundation::IAsyncAction * operation) = 0; }; } namespace ABI { template <> struct traits<Windows::System::Threading::ThreadPoolTimer> { using default_interface = Windows::System::Threading::IThreadPoolTimer; }; } namespace Windows::System::Threading { template <typename D> struct WINRT_EBO impl_IThreadPoolStatics { Windows::Foundation::IAsyncAction RunAsync(const Windows::System::Threading::WorkItemHandler & handler) const; Windows::Foundation::IAsyncAction RunAsync(const Windows::System::Threading::WorkItemHandler & handler, Windows::System::Threading::WorkItemPriority priority) const; Windows::Foundation::IAsyncAction RunAsync(const Windows::System::Threading::WorkItemHandler & handler, Windows::System::Threading::WorkItemPriority priority, Windows::System::Threading::WorkItemOptions options) const; }; template <typename D> struct WINRT_EBO impl_IThreadPoolTimer { Windows::Foundation::TimeSpan Period() const; Windows::Foundation::TimeSpan Delay() const; void Cancel() const; }; template <typename D> struct WINRT_EBO impl_IThreadPoolTimerStatics { Windows::System::Threading::ThreadPoolTimer CreatePeriodicTimer(const Windows::System::Threading::TimerElapsedHandler & handler, const Windows::Foundation::TimeSpan & period) const; Windows::System::Threading::ThreadPoolTimer CreateTimer(const Windows::System::Threading::TimerElapsedHandler & handler, const Windows::Foundation::TimeSpan & delay) const; Windows::System::Threading::ThreadPoolTimer CreatePeriodicTimer(const Windows::System::Threading::TimerElapsedHandler & handler, const Windows::Foundation::TimeSpan & period, const Windows::System::Threading::TimerDestroyedHandler & destroyed) const; Windows::System::Threading::ThreadPoolTimer CreateTimer(const Windows::System::Threading::TimerElapsedHandler & handler, const Windows::Foundation::TimeSpan & delay, const Windows::System::Threading::TimerDestroyedHandler & destroyed) const; }; } namespace impl { template <> struct traits<Windows::System::Threading::IThreadPoolStatics> { using abi = ABI::Windows::System::Threading::IThreadPoolStatics; template <typename D> using consume = Windows::System::Threading::impl_IThreadPoolStatics<D>; }; template <> struct traits<Windows::System::Threading::IThreadPoolTimer> { using abi = ABI::Windows::System::Threading::IThreadPoolTimer; template <typename D> using consume = Windows::System::Threading::impl_IThreadPoolTimer<D>; }; template <> struct traits<Windows::System::Threading::IThreadPoolTimerStatics> { using abi = ABI::Windows::System::Threading::IThreadPoolTimerStatics; template <typename D> using consume = Windows::System::Threading::impl_IThreadPoolTimerStatics<D>; }; template <> struct traits<Windows::System::Threading::TimerDestroyedHandler> { using abi = ABI::Windows::System::Threading::TimerDestroyedHandler; }; template <> struct traits<Windows::System::Threading::TimerElapsedHandler> { using abi = ABI::Windows::System::Threading::TimerElapsedHandler; }; template <> struct traits<Windows::System::Threading::WorkItemHandler> { using abi = ABI::Windows::System::Threading::WorkItemHandler; }; template <> struct traits<Windows::System::Threading::ThreadPool> { static constexpr const wchar_t * name() noexcept { return L"Windows.System.Threading.ThreadPool"; } }; template <> struct traits<Windows::System::Threading::ThreadPoolTimer> { using abi = ABI::Windows::System::Threading::ThreadPoolTimer; static constexpr const wchar_t * name() noexcept { return L"Windows.System.Threading.ThreadPoolTimer"; } }; } }
/*题目:小Q是一个非常聪明的孩子,除了国际象棋,他还很喜欢玩一个电脑益智游戏――矩阵游戏。 矩阵游戏在一个 [公式] 黑白方阵进行(如同国际象棋一般,只是颜色是随意的)。每次可以对该矩阵 进行两种操作:行交换操作:选择矩阵的任意两行,交换这两行(即交换对应格子的颜色)列交换操作: 选择矩阵的任意两列,交换这两列(即交换对应格子的颜色)游戏的目标,即通过若干次操作,使得方阵 的主对角线(左上角到右下角的连线)上的格子均为黑色。对于某些关卡,小Q百思不得其解,以致他开始怀 疑这些关卡是不是根本就是无解的!于是小Q决定写一个程序来判断这些关卡是否有解。*/ #include <cstdio> #include <cstring> int Map[205][205], p[205], vis[205], N, T; bool match(int i) { for (int j = 1; j <= N; ++j) { if (Map[i][j] && !vis[j]) { vis[j] = 1; if (p[j] == 0 || match(p[j])) { p[j] = i; return true; } } } return false; } int Hungarian() { int cnt = 0; for (int i = 1; i <= N; ++i) { memset(vis, 0, sizeof(vis)); if (match(i)) cnt++; } return cnt; } int main() { scanf("%d", &T); while (T--) { scanf("%d", &N); memset(p, 0, sizeof(p)); for (int i = 1; i <= N; ++i) for (int j = 1; j <= N; ++j) scanf("%d", &Map[i][j]); puts(Hungarian() == N ? "Yes" : "No"); } return 0; }
// // discount.cpp // polymorth // // Created by Damir Mustafin on 26/11/15. // Copyright (c) 2015 Damir Mustafin. All rights reserved. // #include "discount.h" DiscountSale :: DiscountSale() : Sale(), discount(0) { } // init section DiscountSale :: DiscountSale(double thePrice, double theDiscount) : Sale(thePrice), discount(theDiscount) { } double DiscountSale :: getDiscount() const { return discount; } void DiscountSale :: setDiscount(double newDiscount){ discount = newDiscount; } double DiscountSale :: bill() const { double fraction = discount/100; double tmp = (1-fraction) * getPrice(); return tmp; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Core.h" #include "Engine.h" #include "GameFramework/Actor.h" #include "XSpace.generated.h" UCLASS() class XPROJECT_API AXSpace : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AXSpace(); // Called every frame virtual void Tick(float DeltaTime) override; UFUNCTION(BlueprintCallable) float GetDamage(); UFUNCTION(BlueprintCallable) virtual void OnCollision(AActor * OtherActor, const FHitResult & SweepResult); UFUNCTION(BlueprintCallable) virtual UShapeComponent * GetCollisionComponent(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; UPROPERTY(EditAnywhere) float Damage; private: };
#ifndef RIGID2D_INCLUDE_GUARD_HPP #define RIGID2D_INCLUDE_GUARD_HPP /// \file /// \brief Library for two-dimensional rigid body transformations. #include<iosfwd> // contains forward definitions for iostream objects #include<cmath> namespace rigid2d { /// \brief PI. Not in C++ standard until C++20. constexpr double PI=3.14159265358979323846; /// \brief approximately compare two floating-point numbers using /// an absolute comparison /// \param d1 - a number to compare /// \param d2 - a second number to compare /// \param epsilon - absolute threshold required for equality /// \return true if abs(d1 - d2) < epsilon /// Note: the fabs function in <cmath> (c++ equivalent of math.h) will /// be useful here constexpr bool almost_equal(double d1, double d2, double epsilon=1.0e-12) { return std::fabs(d1-d2)<epsilon? true:false; } /// \brief convert degrees to radians /// \param deg - angle in degrees /// \returns radians /// NOTE: implement this in the header file /// constexpr means that the function can be computed at compile time /// if given a compile-time constant as input constexpr double deg2rad(double deg) { return deg*PI/180; } /// \brief convert radians to degrees /// \param rad - angle in radians /// \returns the angle in degrees constexpr double rad2deg(double rad) { return rad*180/PI; } /// \brief normalize angle and turn any angel into -pi ~ pi /// \param rad - radian to normalize /// \return normalized angle in radians constexpr double normalize_angle(double rad) { // floating point remainder essentially this is fmod const auto q = std::floor((rad + PI) / (2.0*PI)); rad = (rad + PI) - q * 2.0*PI; if (rad < 0) { rad += 2.0*PI; } return (rad - PI); } /// static_assertions test compile time assumptions. /// You should write at least one more test for each function /// You should also purposely (and temporarily) make one of these tests fail /// just to see what happens // static_assert(almost_equal(0, 0), "is_zero failed"); // static_assert(almost_equal(3.0, 3.0+1.0e-13),"is_zero failed"); // static_assert(almost_equal(0.001, 0.005, 1.0e-2), "is_zero failed"); // static_assert(almost_equal(0.003, 0.008, 1.0e-2), "is_zero failed"); // static_assert(almost_equal(deg2rad(0.0), 0.0), "deg2rad failed"); // static_assert(almost_equal(deg2rad(90.0), PI/2), "deg2rad failed"); // static_assert(almost_equal(rad2deg(0.0), 0.0), "rad2deg) failed"); // static_assert(almost_equal(rad2deg(PI/3),60.0), "rad2deg) failed"); // static_assert(almost_equal(deg2rad(rad2deg(2.1)), 2.1), "deg2rad failed"); // static_assert(almost_equal(deg2rad(rad2deg(PI/4)), PI/4), "deg2rad failed"); /// \brief A 2-Dimensional Vector struct Vector2D { double x; double y; /// \brief default constructor for 2D vector Vector2D(); /// \brief set elements of vector /// \param vec_x - x component /// \param vec_y - y component Vector2D(double vec_x, double vec_y); /// \brief add vector components /// \param v - components to add /// \return a reference to the newly constructed vector Vector2D & operator += (const Vector2D & v); /// \brief subtract vector components /// \param v - components to subtract /// \return a reference to the newly constructed vector Vector2D & operator -= (const Vector2D & v); /// \brief scalar multiplication of vector /// \param scalar - multiply vector by /// \return a reference to the newly constructed vector Vector2D & operator *= (const double & scalar); }; /// \brief A 2-Dimensional normal vector struct NormalVec2D { double nx = 0.0; double ny = 0.0; }; /// \brief A 2-Dimensional twist struct Twist2D { // rotation about z-axis double w = 0.0; // linear x velocity double vx = 0.0; // linear y velocity double vy = 0.0; }; /// \brief A 2-Dimensional transform struct TransformData2D { double theta = 0.0; double x = 0.0; double y =0.0; }; /// \brief A 2-Dimensional screw struct Screw2D { double w = 0.0; double vx = 0.0; double vy = 0.0; }; /// \brief add two vectors components /// \param v1 - vector to add components /// \param v2 - added components /// \return composition of two vectors Vector2D operator+(Vector2D v1, const Vector2D & v2); /// \brief subtract two vectors components /// \param v1 - vector to subtract components /// \param v2 - subtracted components /// \return composition of two vectors Vector2D operator-(Vector2D v1, const Vector2D & v2); /// \brief scalar multipliocation of vectors /// \param v - vector /// \param scalar - multiply vector by /// \return scaled vector Vector2D operator*(Vector2D v, const double & scalar); /// \brief scalar multipliocation of vector /// \param scalar - scalar /// \param v - multiply scalar by vector /// \return scaled vector Vector2D operator*(const double & scalar, Vector2D v); /// \brief magnitude of a vector /// \param v - vector /// \return magnitude double mag(const Vector2D & v); /// \brief angle between 2 vectors /// \param v1 - vector1 /// \param v2 - vector2 /// \return angle double angle(const Vector2D & v1, const Vector2D & v2); /// \brief output a 2 dimensional vector as [xcomponent ycomponent] /// os - stream to output to /// v - the vector to print std::ostream & operator<<(std::ostream & os, const Vector2D & v); /// \brief input a 2 dimensional vector /// You should be able to read vectors entered as two numbers /// separated by a newline or a space, or entered as [xcomponent, ycomponent] /// is - stream from which to read /// v [out] - output vector /// Hint: The following may be useful: /// https://en.cppreference.com/w/cpp/io/basic_istream/peek /// https://en.cppreference.com/w/cpp/io/basic_istream/get std::istream & operator>>(std::istream & is, Vector2D & v); /// \brief normalize a Vector2D /// \param v - the vector to normalize /// \return a normalized vector in the same coordinate system NormalVec2D norm(const Vector2D & v); /// \brief output a 2 dimensional vector as [angular_component vel_xcomponent vel_ycomponent] /// os - stream to output to /// twist - the twist to print std::ostream & operator<<(std::ostream & os, const Twist2D & twist); /// \brief input a 2 dimensional twist /// You should be able to read vectors entered as two numbers /// separated by a newline or a space, or entered as [xcomponent, ycomponent] /// is - stream from which to read /// twist [out] - output twist std::istream & operator>>(std::istream & is, Twist2D & twist); /// \brief a rigid body transformation in 2 dimensions class Transform2D { public: /// \brief Create an identity transformation Transform2D(); /// \brief create a transformation that is a pure translation /// \param trans - the vector by which to translate explicit Transform2D(const Vector2D & trans); /// \brief create a pure rotation /// \param radians - angle of the rotation, in radians explicit Transform2D(double radians); /// \brief Create a transformation with a translational and rotational /// component /// \param trans - the translation /// \param rot - the rotation, in radians Transform2D(const Vector2D & trans, double radians); /// \brief apply a transformation to a Vector2D /// \param v - the vector to transform /// \return a vector in the new coordinate system Vector2D operator()(Vector2D v) const; /// \brief apply a adjoint to a Twist2D /// \param twist - the twist to transform /// \return a twist in the new coordinate system Twist2D operator()(Twist2D twist) const; /// \brief invert the transformation /// \return the inverse transformation. Transform2D inv() const; /// \brief compose this transform with another and store the result /// in this object /// \param rhs - the first transform to apply /// \returns a reference to the newly transformed operator Transform2D & operator*=(const Transform2D & rhs); /// \brief integrate a Twist /// \param twist - the twist to integrate /// \return transformation correspond to a twist for one time step Transform2D integrateTwist(const Twist2D & twist) const; /// \brief displacement of transform /// \return displacement data of transform TransformData2D displacement() const; /// \brief \see operator<<(...) (declared outside this class) /// for a description friend std::ostream & operator<<(std::ostream & os, const Transform2D & tf); private: // Initialize trans Transform2D(double theta, double ctheta, double stheta, double x, double y); // angle, sin, cos, x and y double theta, ctheta, stheta, x, y; }; /// \brief should print a human readable version of the transform: /// An example output: /// dtheta (degrees): 90 dx: 3 dy: 5 /// \param os - an output stream /// \param tf - the transform to print std::ostream & operator<<(std::ostream & os, const Transform2D & tf); /// \brief Read a transformation from stdin /// Should be able to read input either as output by operator<< or /// as 3 numbers (degrees, dx, dy) separated by spaces or newlines std::istream & operator>>(std::istream & is, Transform2D & tf); /// \brief multiply two transforms together, returning their composition /// \param lhs - the left hand operand /// \param rhs - the right hand operand /// \return the composition of the two transforms /// HINT: This function should be implemented in terms of *= Transform2D operator*(Transform2D lhs, const Transform2D & rhs); } #endif
#include "ClockGame.h" ClockGame::ClockGame(sf::RenderWindow *window, sf::Clock *clock) { this->window = window; this->clock = clock; } ClockGame::~ClockGame() { } int ClockGame::getTime() { sf::Time elapsed = clock->getElapsedTime(); int a = elapsed.asSeconds(); return a; }
// // Created by 王润基 on 2017/4/8. // #include "ParallelLight.h" Light ParallelLight::illuminate(Vector3f const &point) const { float t = ray.calcProjectionT(point); float d = ray.calcDist(point); if(d > r || t < 0) return Light(point, point, Vector3f::zero); return Light(point - ray.getUnitDir() * t, point, color); } ParallelLight::ParallelLight(const Ray &ray, float r, const Color &color) : ray(ray), r(r) { this->color = color; } const Ray &ParallelLight::getRay() const { return ray; } void ParallelLight::setRay(const Ray &ray) { ParallelLight::ray = ray; } const Color &ParallelLight::getColor() const { return color; } void ParallelLight::setColor(const Color &color) { ParallelLight::color = color; } Ray ParallelLight::sample() const { // TODO throw std::exception(); }
#pragma once #include <vector> #include <algorithm> #include <iostream> #include <string> class BigInteger { public: BigInteger() = default; BigInteger(size_t num) { mData.reserve(30); while (num > 0) { mData.push_back(num % 10); num /= 10; } } BigInteger & operator += (BigInteger const& rhs) { uint8_t carry = 0; size_t i = 0; for (; i < rhs.mData.size(); ++i) { if (i == mData.size()) { mData.push_back(0); } carry += mData[i] + rhs.mData[i]; mData[i] = carry % 10; carry /= 10; } while (carry > 0) { if (i == mData.size()) { mData.push_back(0); } carry += mData[i]; mData[i] = carry % 10; carry /= 10; ++i; } return *this; } BigInteger & operator *= (BigInteger const& rhs) { BigInteger res; for (size_t i = 0; i < rhs.mData.size(); ++i) { BigInteger localRes; auto current = rhs.mData[i]; if (current == 0) { continue; } for (size_t j = 0; j < mData.size(); ++j) { localRes += BigInteger(current * mData[j]).shift(long(j)); } res += localRes.shift(long(i)); } swap(res); return *this; } BigInteger & operator -= (const BigInteger & rhs) { auto get = [&rhs](std::vector<uint8_t> & numbers, long i) { while (numbers[i + 1] == 0) { numbers[i + 1] = 9; i += 1; } --numbers[i + 1]; }; for (size_t j = 0, i = 0; i < rhs.mData.size(); ++i, ++j) { if (mData[j] < rhs.mData[i]) { get(mData, long(j)); mData[j] += (10 - rhs.mData[i]); } else { mData[j] -= rhs.mData[i]; } } removeZeroFront(); return *this; } void swap(BigInteger & rhs) { mData.swap(rhs.mData); } size_t digitsCount() const { return mData.size(); } private: size_t removeZeroFront() { auto rit = std::find_if(mData.rbegin(), mData.rend(), [](auto & item) { return (item != 0); }); auto it = rit.base(); size_t size = 0; if (it != mData.end()) { size = std::distance(it, mData.end()); mData.erase(it, mData.end()); } return size; } BigInteger & append(BigInteger const& rhs) { shift(long(rhs.mData.size())); return *this += rhs; } std::pair<BigInteger, BigInteger> splitFront(size_t size) const { if (mData.size() <= size) { return { *this, BigInteger() }; } auto offset = mData.size() - size; auto dataBeg = mData.begin(); std::pair<BigInteger, BigInteger> res; res.second.mData = std::vector<uint8_t>(dataBeg, dataBeg + offset); res.first.mData = std::vector<uint8_t>(dataBeg + offset, mData.end()); return res; } BigInteger & shift(long count) { if (mData.size() > 0 && count > 0) { mData.insert(mData.begin(), count, 0); } return *this; } friend bool operator == (BigInteger const& lhs, BigInteger const& rhs); friend std::ostream & operator << (std::ostream & out, BigInteger const& num); friend std::istream & operator >> (std::istream & in, BigInteger & obj); friend bool operator < (BigInteger const& lhs, BigInteger const& rhs); friend std::pair<BigInteger, BigInteger> divide(const BigInteger & lhs, const BigInteger & rhs); std::vector<uint8_t> mData; }; bool operator != (BigInteger const& lhs, BigInteger const& rhs) { return !(lhs == rhs); } bool operator == (BigInteger const& lhs, BigInteger const& rhs) { return lhs.mData == rhs.mData; } BigInteger operator * (BigInteger const& lhs, BigInteger const& rhs) { return (BigInteger(lhs) *= rhs); } BigInteger operator + (BigInteger const& lhs, BigInteger const& rhs) { return (BigInteger(lhs) += rhs); } BigInteger operator - (BigInteger const& lhs, BigInteger const& rhs) { return (BigInteger(lhs) -= rhs); } bool operator < (BigInteger const& lhs, BigInteger const& rhs) { auto less = [&]() { for (long i = long(lhs.mData.size() - 1); i >= 0; --i) { if (lhs.mData[i] == rhs.mData[i]) { continue; } return lhs.mData[i] < rhs.mData[i]; } return false; }; return (lhs.mData.size() == rhs.mData.size()) ? (lhs.mData.empty() ? true : less()) : lhs.mData.size() < rhs.mData.size(); } bool operator <= (BigInteger const& lhs, BigInteger const& rhs) { return lhs < rhs || lhs == rhs; } std::ostream & operator << (std::ostream & out, BigInteger const& num) { if (num.mData.empty()) { out << 0; } std::for_each(num.mData.rbegin(), num.mData.rend(), [&out](auto item) { out << std::to_string(item); }); return out; } std::istream & operator >> (std::istream & in, BigInteger & obj) { auto isWhiteSpace = [](int ch) { return ch == '\n' || ch == '\t' || ch == '\r' || ch == ' '; }; while (!in.eof()) { auto nextChar = in.peek(); if (isWhiteSpace(nextChar)) { in.get(); } else { break; } } BigInteger num; while (!in.eof()) { auto nextChar = in.peek(); if ('0' <= nextChar && nextChar <= '9') { num.mData.push_back(nextChar - '0'); in.get(); } else { break; } } if (num.mData.empty()) { in.setstate(std::ios::failbit); } else { std::reverse(num.mData.begin(), num.mData.end()); num.removeZeroFront(); obj.swap(num); } return in; } std::pair<BigInteger, BigInteger> divide(const BigInteger & lhs, const BigInteger & rhs) { if (rhs == 0) { throw std::logic_error("division on zero"); } if (lhs == rhs) { return { 1, 0 }; } if (lhs < rhs) { return { 0, lhs }; } auto div = [](BigInteger const & lhs, BigInteger const& rhs) { BigInteger tmp(lhs); BigInteger count = 0; while (rhs < tmp) { tmp -= rhs; count += 1; } if (rhs == tmp) { return std::pair<BigInteger, BigInteger>({ count + 1, 0 }); } return std::pair<BigInteger, BigInteger>({ count, tmp }); }; auto res = BigInteger(); auto prev = BigInteger(); auto amount = lhs; auto fullAmount = BigInteger(prev).append(amount); auto isFirst = true; while (rhs <= fullAmount) { auto curr = amount.splitFront(isFirst ? rhs.mData.size() : 1); isFirst = false; prev.append(curr.first); amount = curr.second; while (prev < rhs) { curr = amount.splitFront(1); prev.append(curr.first); amount = curr.second; res.shift(1); } auto localRes = div(prev, rhs); res.append(localRes.first); prev = localRes.second; size_t removedZerous = 0; if (prev == 0) { removedZerous = amount.removeZeroFront(); res.shift(long(removedZerous)); } fullAmount = BigInteger(prev).append(amount); if ((fullAmount < rhs) && (fullAmount.digitsCount() > 0)) { res.shift(long(curr.second.digitsCount() - removedZerous)); } } fullAmount.removeZeroFront(); return { res, fullAmount }; }
#ifndef __CSECTION_H_ #define __CSECTION_H_ class CSection { public: CSection(); ~CSection(); }; #endif
#define WINDOW_HEADER ("") #define SCREEN_WIDTH (1280.0f) #define SCREEN_HEIGHT (720.0f) #define MS_PER_S (1000.0) #define FRAMES_PER_SECOND (60.0) #define EDITOR //#define DEBUG_PRINT #define FPS_COUNT #define RELEASE_MODE (false) #if !(RELEASE_MODE) #define USE_ASSERTS #endif #define UNITY_BUILD (true) //#define METATESTING // audio #define AUDIO_SYS_IMPLEMENTATION #include "audio_sys.hpp" #define FILE_IO_IMPLEMENTATION #include "file_io.hpp" #define COMMON_UTILS_CPP_IMPLEMENTATION #include "common_utils_cpp.hpp" #include "types.h" #include "config/config_state.cpp" #define OPEN_GL_IMPLEMENTATION #include "opengl.hpp" #define CORE_UTILS_IMPLEMENTATION #include "core_utils.h" #define ENTITY_IMPLEMENTATION #include "entity.h" #define COLLISION_IMPLEMENTATION #include "collision.h" #include "sdl.hpp" #include <iostream> #include <string> #define SHADER_IMPLEMENTATION #include "shader.hpp" #define TEXTURE_IMPLEMENTATION #include "texture.hpp" #define CAMERA_IMPLEMENTATION #include "camera.hpp" int ignore_mouse_movement(void* unused, SDL_Event* event) { return (event->type == SDL_MOUSEMOTION) ? 0 : 1; } SDL_Window* window = NULL; void* GlobalArenaAlloc_vertex_attribute_data(size_t count) { return xmalloc(count * sizeof(GLfloat)); } void* GlobalArenaAlloc_index_data(size_t count) { return xmalloc(count * sizeof(GLuint)); } // WORLD STATE struct Room { VertexBufferData geometry; Collider* collision_data; Mat4 matrix; }; struct World { Room* rooms; Mat4 m_view; Mat4 m_projection; }; struct GlobalData { SDL_GLContext context; TextureData textures; }; GlobalData program_data; #define SD #define SD_DEBUG_LOG_ON #ifdef VULKAN_HPP #define SD_RENDERER_VULKAN #elif defined(OPEN_GL_HPP) #define SD_RENDERER_OPENGL #endif #if !(RELEASE_MODE) #define SD_BOUNDS_CHECK #endif #define SD_IMPLEMENTATION #include "sd.hpp" #include "rotologic_renderer.hpp" #define LOGIC_NODE_TYPE_LIST \ LOGIC_NODE_ENTRY(VALUE, STRING(VALUE)) \ LOGIC_NODE_ENTRY(NONE, STRING(NONE)) \ LOGIC_NODE_ENTRY(AND, STRING(AND)) \ LOGIC_NODE_ENTRY(OR, STRING(OR)) \ LOGIC_NODE_ENTRY(XOR, STRING(XOR)) \ LOGIC_NODE_ENTRY(NOT, STRING(NOT)) \ LOGIC_NODE_ENTRY(LESS_THAN, STRING(LESS_THAN)) \ LOGIC_NODE_ENTRY(LESS_EQ, STRING(LESS_EQ)) \ LOGIC_NODE_ENTRY(GREATER_THAN, STRING(GREATER_THAN)) \ LOGIC_NODE_ENTRY(GREATER_EQ, STRING(GREATER_EQ)) \ LOGIC_NODE_ENTRY(EQUAL, STRING(EQUAL)) \ LOGIC_NODE_ENTRY(WHILE, STRING(WHILE)) \ LOGIC_NODE_ENTRY(ADD, STRING(ADD)) \ LOGIC_NODE_ENTRY(SUBTRACT, STRING(SUBTRACT)) \ LOGIC_NODE_ENTRY(MULTIPLY, STRING(MULTIPLY)) \ LOGIC_NODE_ENTRY(DIVIDE, STRING(DIVIDE)) // for visual linking gameplay enum struct LOGIC_NODE_TYPE { #define LOGIC_NODE_ENTRY(a, b) a, LOGIC_NODE_TYPE_LIST #undef LOGIC_NODE_ENTRY ENUM_COUNT }; const char* const logic_node_type_strings[] = { #define LOGIC_NODE_ENTRY(a, b) b, LOGIC_NODE_TYPE_LIST #undef LOGIC_NODE_ENTRY }; struct LogicInput { float64 value; operator float64(void) { return this->value; } }; struct LogicNode { Vec3 position; LOGIC_NODE_TYPE type; LogicInput* in; usize in_count; usize in_received; LogicNode** out; usize out_count; bool is_negated; union { struct { LogicNode* out; usize out_count; float64* value_ptr; } value_n; struct { LogicNode* out; usize out_count; } none_n; struct { LogicNode** out; usize out_count; float64* in; usize in_received; usize in_count; bool negated; } and_n; struct { LogicNode* out; usize out_count; bool negated; } or_n; struct { LogicNode* out; usize out_count; bool negated; } xor_n; struct { LogicNode* out; usize out_count; bool negated; } not_n; struct { LogicNode* out; usize out_count; bool negated; } less_than_n; struct { LogicNode* out; usize out_count; bool negated; } less_eq_n; struct { LogicNode* out; usize out_count; bool negated; } greater_than_n; struct { LogicNode* out; usize out_count; bool negated; } greater_eq_n; struct { LogicNode* out; usize out_count; bool negated; } equal_n; struct { LogicNode* out_true; // multiple out or use a separate node to feed multiple outputs? TODO LogicNode* out_false; usize out_count_true; usize out_count_false; } while_n; struct { LogicNode* out; usize out_count; float64 value; } add_n; struct { LogicNode* out; usize out_count; float64 value; } subtract_n; struct { LogicNode* out; usize out_count; float64 value; } multiply_n; struct { LogicNode* out; usize out_count; float64 value; } divide_n; // struct { // } for_n; }; }; // TODO set input of child node in parent node, must move data outside the union #define LOGIC_NODE_PRINT void LogicNode_traverse(LogicNode* v, float64 value, std::string tabs); void LogicNode_handle_value(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << *(v->value_n.value_ptr) << std::endl; #endif // TODO multiple outs LogicNode_traverse(v->value_n.out, *(v->value_n.value_ptr), tabs + " "); } void LogicNode_handle_none(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << " : " << value << std::endl; #endif } void LogicNode_handle_and(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif v->and_n.in[v->and_n.in_received] = value; v->and_n.in_received += 1; if (v->and_n.in_received == v->and_n.in_count) { v->and_n.in_received = 0; bool out_val = true; for (usize i = 0; i < v->and_n.in_count && out_val == true; i += 1) { out_val &= (bool)v->and_n.in[i]; } for (usize i = 0; i < v->and_n.out_count; i += 1) { LogicNode_traverse(v->and_n.out[i], out_val, tabs + " "); } } } void LogicNode_handle_or(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_xor(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_not(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_less_than(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_less_eq(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_greater_than(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_greater_eq(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_equal(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_while(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_add(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_subtract(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_multiply(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_handle_divide(LogicNode* v, float64 value, std::string tabs) { #ifdef LOGIC_NODE_PRINT std::cout << tabs << logic_node_type_strings[(usize)v->type] << std::endl; #endif } void LogicNode_traverse(LogicNode* v, float64 value, std::string tabs) { using T = LOGIC_NODE_TYPE; switch (v->type) { case T::VALUE: LogicNode_handle_value(v, value, tabs); break; case T::NONE: LogicNode_handle_none(v, value, tabs); break; case T::AND: LogicNode_handle_and(v, value, tabs); break; case T::OR: LogicNode_handle_or(v, value, tabs); break; case T::XOR: LogicNode_handle_xor(v, value, tabs); break; case T::NOT: LogicNode_handle_not(v, value, tabs); break; case T::LESS_THAN: LogicNode_handle_less_than(v, value, tabs); break; case T::LESS_EQ: LogicNode_handle_less_eq(v, value, tabs); break; case T::GREATER_THAN: LogicNode_handle_greater_than(v, value, tabs); break; case T::GREATER_EQ: LogicNode_handle_greater_eq(v, value, tabs); break; case T::EQUAL: LogicNode_handle_equal(v, value, tabs); break; case T::WHILE: LogicNode_handle_while(v, value, tabs); break; case T::ADD: LogicNode_handle_add(v, value, tabs); break; case T::SUBTRACT: LogicNode_handle_subtract(v, value, tabs); break; case T::MULTIPLY: LogicNode_handle_multiply(v, value, tabs); break; case T::DIVIDE: LogicNode_handle_divide(v, value, tabs); break; default: break; } } WindowState window_state; #define MAX_CONTROLLERS (1) //SDL_GameController* controller_handles[MAX_CONTROLLERS]; //int controller_index = 0; SDL_GameController* controller_handle = nullptr; char* controller_mapping = nullptr; bool poll_input_events(input_sys::Input* input, SDL_Event* event) { using namespace input_sys; keys_advance_history(input); #ifdef EDITOR mouse_advance_history(input); #endif while (SDL_PollEvent(event)) { switch (event->type) { case SDL_QUIT: if (controller_handle != nullptr) { SDL_GameControllerClose(controller_handle); } return false; case SDL_WINDOWEVENT: switch (event->window.event) { // case SDL_WINDOWEVENT_SHOWN: // SDL_Log("Window %d shown", event->window.windowID); // break; // case SDL_WINDOWEVENT_HIDDEN: // SDL_Log("Window %d hidden", event->window.windowID); // break; // case SDL_WINDOWEVENT_EXPOSED: // SDL_Log("Window %d exposed", event->window.windowID); // break; // case SDL_WINDOWEVENT_MOVED: // SDL_Log("Window %d moved to %d,%d", // event->window.windowID, event->window.data1, // event->window.data2); // break; // case SDL_WINDOWEVENT_RESIZED: // SDL_Log("Window %d resized to %dx%d", // event->window.windowID, event->window.data1, // event->window.data2); // break; // case SDL_WINDOWEVENT_SIZE_t_delta_sD: // SDL_Log("Window %d size changed to %dx%d", // event->window.windowID, event->window.data1, // event->window.data2); // break; case SDL_WINDOWEVENT_MINIMIZED: window_state.minimized = true; // SDL_Log("Window %d minimized", event->window.windowID); break; // case SDL_WINDOWEVENT_MAXIMIZED: // SDL_Log("Window %d maximized", event->window.windowID); // break; case SDL_WINDOWEVENT_RESTORED: window_state.minimized = false; window_state.restored = true; // SDL_Log("Window %d restored", event->window.windowID); break; // case SDL_WINDOWEVENT_ENTER: // SDL_Log("Mouse entered window %d", // event->window.windowID); // break; // case SDL_WINDOWEVENT_LEAVE: // SDL_Log("Mouse left window %d", event->window.windowID); // break; case SDL_WINDOWEVENT_FOCUS_GAINED: window_state.focused = true; // SDL_Log("Window %d gained keyboard focus", // event->window.windowID); break; case SDL_WINDOWEVENT_FOCUS_LOST: window_state.focused = false; // SDL_Log("Window %d lost keyboard focus", // event->window.windowID); break; // case SDL_WINDOWEVENT_CLOSE: // SDL_Log("Window %d closed", event->window.windowID); // break; // #if SDL_VERSION_ATLEAST(2, 0, 5) // case SDL_WINDOWEVENT_TAKE_FOCUS: // SDL_Log("Window %d is offered a focus", event->window.windowID); // break; // case SDL_WINDOWEVENT_HIT_TEST: // SDL_Log("Window %d has a special hit test", event->window.windowID); // break; // #endif default: // SDL_Log("Window %d got unknown event %d", // event->window.windowID, event->window.event); break; } break; case SDL_CONTROLLERDEVICEADDED: if (SDL_IsGameController(event->cdevice.which)) { controller_handle = SDL_GameControllerOpen(event->cdevice.which); fprintf( stdout, "ADDING CONTROLLER (%s) TO PORT (%d)\n", SDL_GameControllerName(controller_handle), event->cdevice.which ); controller_mapping = SDL_GameControllerMapping(controller_handle); SDL_Log("CONTROLLER IS MAPPED AS \"%s\".", controller_mapping); SDL_free(controller_mapping); } else { fprintf(stderr, "CONTROLLER INCOMPATIBLE"); } break; case SDL_CONTROLLERDEVICEREMOVED: if (controller_handle != nullptr) { fprintf( stdout, "REMOVING CONTROLLER (%s) FROM PORT (%d)\n", SDL_GameControllerName(controller_handle), event->cdevice.which ); SDL_GameControllerClose(controller_handle); input_sys::init(input); } break; case SDL_CONTROLLERBUTTONDOWN: switch (event->cbutton.button) { case SDL_CONTROLLER_BUTTON_A: std::cout << "DOWN_BUTTON_A" << std::endl; key_set_down(input, CONTROL::JUMP); break; case SDL_CONTROLLER_BUTTON_B: std::cout << "DOWN_BUTTON_B" << std::endl; break; case SDL_CONTROLLER_BUTTON_X: std::cout << "DOWN_BUTTON_X" << std::endl; break; case SDL_CONTROLLER_BUTTON_Y: std::cout << "DOWN_BUTTON_Y" << std::endl; break; case SDL_CONTROLLER_BUTTON_BACK: std::cout << "DOWN_BUTTON_BACK" << std::endl; #ifdef EDITOR key_set_down(input, CONTROL::EDIT_MODE); #endif break; case SDL_CONTROLLER_BUTTON_GUIDE: std::cout << "DOWN_BUTTON_GUIDE" << std::endl; key_set_down(input, CONTROL::RESET_POSITION); break; case SDL_CONTROLLER_BUTTON_START: std::cout << "DOWN_BUTTON_START" << std::endl; break; case SDL_CONTROLLER_BUTTON_LEFTSTICK: std::cout << "DOWN_BUTTON_LEFTSTICK" << std::endl; break; case SDL_CONTROLLER_BUTTON_RIGHTSTICK: std::cout << "DOWN_BUTTON_RIGHTSTICK" << std::endl; break; case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: std::cout << "DOWN_BUTTON_LEFTSHOULDER" << std::endl; break; case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: std::cout << "DOWN_BUTTON_RIGHTSHOULDER" << std::endl; break; case SDL_CONTROLLER_BUTTON_DPAD_UP: std::cout << "DOWN_BUTTON_DPAD_UP" << std::endl; key_set_down(input, CONTROL::UP); break; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: std::cout << "DOWN_BUTTON_DPAD_DOWN" << std::endl; key_set_down(input, CONTROL::DOWN); break; case SDL_CONTROLLER_BUTTON_DPAD_LEFT: std::cout << "DOWN_BUTTON_DPAD_LEFT" << std::endl; key_set_down(input, CONTROL::LEFT); break; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: std::cout << "DOWN_BUTTON_DPAD_RIGHT" << std::endl; key_set_down(input, CONTROL::RIGHT); break; default: std::cout << "UNKNOWN" << std::endl; break; } break; case SDL_CONTROLLERBUTTONUP: switch (event->cbutton.button) { case SDL_CONTROLLER_BUTTON_A: std::cout << "UP_BUTTON_A" << std::endl; key_set_up(input, CONTROL::JUMP); break; case SDL_CONTROLLER_BUTTON_B: std::cout << "UP_BUTTON_B" << std::endl; break; case SDL_CONTROLLER_BUTTON_X: std::cout << "UP_BUTTON_X" << std::endl; break; case SDL_CONTROLLER_BUTTON_Y: std::cout << "UP_BUTTON_Y" << std::endl; break; case SDL_CONTROLLER_BUTTON_BACK: std::cout << "UP_BUTTON_BACK" << std::endl; #ifdef EDITOR key_set_up(input, CONTROL::EDIT_MODE); #endif break; case SDL_CONTROLLER_BUTTON_GUIDE: std::cout << "UP_BUTTON_GUIDE" << std::endl; key_set_up(input, CONTROL::RESET_POSITION); break; case SDL_CONTROLLER_BUTTON_START: std::cout << "UP_BUTTON_START" << std::endl; break; case SDL_CONTROLLER_BUTTON_LEFTSTICK: std::cout << "UP_BUTTON_LEFTSTICK" << std::endl; break; case SDL_CONTROLLER_BUTTON_RIGHTSTICK: std::cout << "UP_BUTTON_RIGHTSTICK" << std::endl; break; case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: std::cout << "UP_BUTTON_LEFTSHOULDER" << std::endl; break; case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: std::cout << "UP_BUTTON_RIGHTSHOULDER" << std::endl; break; case SDL_CONTROLLER_BUTTON_DPAD_UP: std::cout << "UP_BUTTON_DPAD_UP" << std::endl; key_set_up(input, CONTROL::UP); break; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: std::cout << "UP_BUTTON_DPAD_DOWN" << std::endl; key_set_up(input, CONTROL::DOWN); break; case SDL_CONTROLLER_BUTTON_DPAD_LEFT: std::cout << "UP_BUTTON_DPAD_LEFT" << std::endl; key_set_up(input, CONTROL::LEFT); break; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: std::cout << "UP_BUTTON_DPAD_RIGHT" << std::endl; key_set_up(input, CONTROL::RIGHT); break; default: std::cout << "UNKNOWN" << std::endl; break; } break; case SDL_CONTROLLERAXISMOTION: #define JOYSTICK_DEADZONE (8000) switch (event->caxis.axis) { case SDL_CONTROLLER_AXIS_MAX: std::cout << "AXIS_MAX " << event->caxis.value << std::endl; break; case SDL_CONTROLLER_AXIS_LEFTY: if (glm::abs(event->caxis.value) > JOYSTICK_DEADZONE) { std::cout << "AXIS_LEFTY " << event->caxis.value << std::endl; } break; case SDL_CONTROLLER_AXIS_RIGHTY: if (glm::abs(event->caxis.value) > JOYSTICK_DEADZONE) { std::cout << "AXIS_RIGHTY " << event->caxis.value << std::endl; } break; case SDL_CONTROLLER_AXIS_LEFTX: if (glm::abs(event->caxis.value) > JOYSTICK_DEADZONE) { std::cout << "AXIS_LEFTX " << event->caxis.value << std::endl; } break; case SDL_CONTROLLER_AXIS_RIGHTX: if (glm::abs(event->caxis.value) > JOYSTICK_DEADZONE) { std::cout << "AXIS_RIGHTX " << event->caxis.value << std::endl; } break; case SDL_CONTROLLER_AXIS_TRIGGERLEFT: std::cout << "AXIS_TRIGGERLEFT " << event->caxis.value << std::endl; break; case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: std::cout << "AXIS_TRIGGERRIGHT " << event->caxis.value << std::endl; break; default: //std::cout << "UNKNOWN" << std::endl; break; } break; case SDL_KEYDOWN: switch (event->key.keysym.scancode) { case SDL_SCANCODE_W: key_set_down(input, CONTROL::UP); break; case SDL_SCANCODE_S: key_set_down(input, CONTROL::DOWN); break; case SDL_SCANCODE_A: key_set_down(input, CONTROL::LEFT); break; case SDL_SCANCODE_D: key_set_down(input, CONTROL::RIGHT); break; case SDL_SCANCODE_J: case SDL_SCANCODE_K: case SDL_SCANCODE_L: key_set_down(input, CONTROL::JUMP); break; case SDL_SCANCODE_0: key_set_down(input, CONTROL::RESET_POSITION); break; case SDL_SCANCODE_C: key_set_down(input, CONTROL::FREE_CAM); break; #ifdef EDITOR case SDL_SCANCODE_E: key_set_down(input, CONTROL::EDIT_MODE); break; case SDL_SCANCODE_P: key_set_down(input, CONTROL::PHYSICS); break; case SDL_SCANCODE_V: key_set_down(input, CONTROL::EDIT_VERBOSE); break; case SDL_SCANCODE_GRAVE: key_set_down(input, CONTROL::LOAD_CONFIG); break; case SDL_SCANCODE_T: key_set_down(input, CONTROL::TEMP); break; case SDL_SCANCODE_N: key_set_down(input, CONTROL::ROTATE_ANTICLOCKWISE); break; case SDL_SCANCODE_M: key_set_down(input, CONTROL::ROTATE_CLOCKWISE); break; case SDL_SCANCODE_LSHIFT: key_set_down(input, CONTROL::SHIFT); break; #endif case SDL_SCANCODE_UP: key_set_down(input, CONTROL::ZOOM_IN); break; case SDL_SCANCODE_DOWN: key_set_down(input, CONTROL::ZOOM_OUT); break; default: break; } break; case SDL_KEYUP: switch (event->key.keysym.scancode) { case SDL_SCANCODE_W: key_set_up(input, CONTROL::UP); break; case SDL_SCANCODE_S: key_set_up(input, CONTROL::DOWN); break; case SDL_SCANCODE_A: key_set_up(input, CONTROL::LEFT); break; case SDL_SCANCODE_D: key_set_up(input, CONTROL::RIGHT); break; case SDL_SCANCODE_J: case SDL_SCANCODE_K: case SDL_SCANCODE_L: key_set_up(input, CONTROL::JUMP); break; case SDL_SCANCODE_0: key_set_up(input, CONTROL::RESET_POSITION); break; case SDL_SCANCODE_C: key_set_up(input, CONTROL::FREE_CAM); break; #ifdef EDITOR case SDL_SCANCODE_E: key_set_up(input, CONTROL::EDIT_MODE); break; case SDL_SCANCODE_P: key_set_up(input, CONTROL::PHYSICS); break; case SDL_SCANCODE_V: key_set_up(input, CONTROL::EDIT_VERBOSE); break; case SDL_SCANCODE_GRAVE: key_set_up(input, CONTROL::LOAD_CONFIG); break; case SDL_SCANCODE_T: key_set_up(input, CONTROL::TEMP); break; case SDL_SCANCODE_N: key_set_up(input, CONTROL::ROTATE_ANTICLOCKWISE); break; case SDL_SCANCODE_M: key_set_up(input, CONTROL::ROTATE_CLOCKWISE); break; case SDL_SCANCODE_LSHIFT: key_set_up(input, CONTROL::SHIFT); break; #endif case SDL_SCANCODE_UP: key_set_up(input, CONTROL::ZOOM_IN); break; case SDL_SCANCODE_DOWN: key_set_up(input, CONTROL::ZOOM_OUT); break; default: break; } break; case SDL_MOUSEBUTTONDOWN: switch (event->button.button) { case SDL_BUTTON_LEFT: mouse_set_down(input, MOUSE_BUTTON::LEFT); break; case SDL_BUTTON_RIGHT: mouse_set_down(input, MOUSE_BUTTON::RIGHT); break; } break; case SDL_MOUSEBUTTONUP: switch (event->button.button) { case SDL_BUTTON_LEFT: mouse_set_up(input, MOUSE_BUTTON::LEFT); break; case SDL_BUTTON_RIGHT: mouse_set_up(input, MOUSE_BUTTON::RIGHT); break; } break; default: break; } } #ifdef EDITOR SDL_GetMouseState(&input->mouse_x, &input->mouse_y); #endif if (window_state.minimized) { SDL_Delay(1000); } else if (!window_state.focused) { SDL_Delay(64); } return true; } template <usize N> void draw_player_collision(Player* you, sd::Render_Batch<N>* ctx) { const Vec3 off(0.5, 0.5, 0.0); BoxComponent* bc = &you->bound; Vec3 top_left = bc->position() + off; Vec3 top_right = top_left + Vec3(bc->width, 0.0, 0.0); Vec3 bottom_right = top_left + Vec3(bc->width, bc->height, 0.0); Vec3 bottom_left = top_left + Vec3(0.0, bc->height, 0.0); { // bound ctx->draw_type = sd::LINES; sd::line(ctx, top_left, top_right); sd::line(ctx, top_right, bottom_right); sd::line(ctx, bottom_right, bottom_left); sd::line(ctx, bottom_left, top_left); } { // floor sensors ctx->color = Color::RED; auto floor_sensor_rays = you->floor_sensor_rays(); floor_sensor_rays.first.first += off; floor_sensor_rays.first.second += off; floor_sensor_rays.second.first += off; floor_sensor_rays.second.second += off; sd::line(ctx, floor_sensor_rays.first.first, floor_sensor_rays.first.second); sd::line(ctx, floor_sensor_rays.second.first, floor_sensor_rays.second.second); } { // side sensors auto side_sensor_rays = you->side_sensor_rays(); side_sensor_rays.first.first += off; side_sensor_rays.first.second += off; side_sensor_rays.second.first += off; side_sensor_rays.second.second += off; ctx->color = Vec4(1.0, 165.0 / 255, 0.0, 1.0); sd::line(ctx, side_sensor_rays.first.first, side_sensor_rays.first.second); ctx->color = Vec4(148.0 / 255, 0.0, 211.0 / 255, 1.0); sd::line(ctx, side_sensor_rays.second.first, side_sensor_rays.second.second); } } template <usize N> void BoxComponent_draw(BoxComponent* bc, sd::Render_Batch<N>* ctx) { const Vec3 off(0.5, 0.5, 0.0); Vec3 top_left = bc->position() + off; Vec3 top_right = top_left + Vec3(bc->width, 0.0, 0.0); Vec3 bottom_right = top_left + Vec3(bc->width, bc->height, 0.0); Vec3 bottom_left = top_left + Vec3(0.0, bc->height, 0.0); ctx->draw_type = sd::LINES; sd::line(ctx, top_left, top_right); sd::line(ctx, top_right, bottom_right); sd::line(ctx, bottom_right, bottom_left); sd::line(ctx, bottom_left, top_left); } bool temp_test_collision(Player* you, Collider* c, CollisionStatus* status) { auto sensors = you->floor_sensor_rays(); vec3_pair* ray0 = &sensors.first; vec3_pair* ray1 = &sensors.second; std::pair<Vec3, Vec3> collider = { c->a, c->b }; // printf("COLLIDER: "); // Collider_print(c); // printf("\nagainst\n"); // vec3_pair_print(&ray0.first, &ray0.second); // printf("\nand\n"); // vec3_pair_print(&ray1.first, &ray1.second); // printf("\n-------------------------\n"); Vec3 va(POSITIVE_INFINITY); Vec3 vb(POSITIVE_INFINITY); Vec3* choice = &va; bool possibly_collided = false; if (line_segment_intersection(ray0, &collider, &va)) { choice = &va; possibly_collided = true; } if (line_segment_intersection(ray1, &collider, &vb)) { choice = (va.y < vb.y) ? &va : &vb; possibly_collided = true; } if (!possibly_collided) { return false; } Vec3* out = &status->intersection; // TODO FIX BUG: HEIGHT OVERRIDDEN BY SUCCESSIVE COLLIDERS EVEN IF LOWER, // MUST COMPARE ALL COLLIDERS BEFORE MODIFYING VALUE // std::cout << "ON_GROUND: " << ((you->on_ground) ? "TRUE" : "FALSE") << std::endl; if (!you->on_ground && you->bound.spatial.y + you->bound.height >= choice->y) { f64 new_y = choice->y; // if (!first_check && new_y >= you->bound.spatial.y) { // return false; // } //you->bound.spatial.y = new_y; if (new_y > out->y) { return false; } out->x = choice->x; out->y = choice->y; out->z = 0.0; status->collider = c; return true; } else if (you->on_ground) { f64 new_y = choice->y; // if (!first_check && new_y >= you->bound.spatial.y) { // return false; // } //you->bound.spatial.y = new_y; if (new_y > out->y) { return false; } out->x = choice->x; out->y = choice->y; out->z = 0.0; status->collider = c; // Vec3* a = &c->a; // Vec3* b = &c->b; //std::cout << glm::degrees(atan2pos_64(b->y - a->y, b->x - a->x)) << std::endl; //vec3_pair_print(&c->a, &c->b); return true; } return false; } char temp_test_collision_sides(Player* you, Collider* c, CollisionStatus* l, CollisionStatus* r) { auto sensors = you->side_sensor_rays(); std::pair<Vec3, Vec3>* ray0 = &sensors.first; std::pair<Vec3, Vec3>* ray1 = &sensors.second; std::pair<Vec3, Vec3> collider = { c->a, c->b }; Vec3 vl(NEGATIVE_INFINITY); Vec3 vr(POSITIVE_INFINITY); bool collision_l = false; bool collision_r = false; if (line_segment_intersection(ray0, &collider, &vl)) { collision_l = true; } if (line_segment_intersection(ray1, &collider, &vr)) { collision_r = true; } if (!(collision_l || collision_r)) { return 0; } Vec3* out_l = &l->intersection; Vec3* out_r = &r->intersection; if (collision_l && collision_r) { if (vl.x > out_l->x) { out_l->x = vl.x; out_l->y = vl.y; out_l->z = 0.0; l->collider = c; } if (vr.x < out_r->x) { out_r->x = vr.x; out_r->y = vr.y; out_r->z = 0.0; r->collider = c; } return 'b'; } else if (collision_l) { if (vl.x > out_l->x) { out_l->x = vl.x; out_l->y = vl.y; out_l->z = 0.0; l->collider = c; } return 'l'; } else { // if (collision_r) if (vr.x < out_r->x) { out_r->x = vr.x; out_r->y = vr.y; out_r->z = 0.0; r->collider = c; } return 'r'; } } struct AirPhysicsConfig { std::string path; FILE* fd; struct stat stat; time_t t_prev_mod; f64 gravity; f64 player_initial_velocity; f64 player_initial_velocity_short; }; bool load_config(AirPhysicsConfig* conf) { #ifdef EDITOR check_file_status(conf->path.c_str(), &conf->stat); if (conf->stat.st_mtime != conf->t_prev_mod) { conf->t_prev_mod = conf->stat.st_mtime; char buff[512]; std::string conf_string = file_io::read_file(conf->fd); if (conf_string.length() == 0 || conf_string.find("DEFAULT") == 0) { puts("USING DEFAULT PARAMETERS"); conf->gravity = physics::GRAVITY_DEFAULT; conf->player_initial_velocity = Player::JUMP_VELOCITY_DEFAULT; conf->player_initial_velocity_short = Player::JUMP_VELOCITY_SHORT_DEFAULT; rewind(conf->fd); return true; } puts("MODIFYING PARAMETERS"); printf("%s\n", conf_string.c_str()); char seps[] = " ,:;\t\n"; char* token = strtok((char*)conf_string.c_str(), seps); sscanf(token, "%lf", &conf->gravity); token = strtok(NULL, seps); sscanf(token, "%lf", &conf->player_initial_velocity); token = strtok(NULL, seps); sscanf(token, "%lf", &conf->player_initial_velocity_short); rewind(conf->fd); printf("%lf : %lf : %lf\n", conf->gravity, conf->player_initial_velocity, conf->player_initial_velocity_short); return true; } #endif return false; } #ifdef METATESTING #include "metatesting.cpp" #endif #include <time.h> int main(int argc, char* argv[]) { /* struct { LogicNode* out; usize count; float64* value_ptr; } value_n; struct { LogicNode* out; usize count; } none_n; struct { LogicNode** out; usize count; float64* in; usize input_received; usize input_count; bool negated; } and_n; */ srand(time(NULL)); float64 avals[] = {(float64)(rand() % 2), (float64)(rand() % 2), (float64)(rand() % 2)}; float64 bvals[] = {(float64)(rand() % 2), (float64)(rand() % 2), (float64)(rand() % 2)}; float64 root_a_val = 0.0; float64 root_b_val = 0.0; LogicNode root_a; root_a.type = LOGIC_NODE_TYPE::VALUE; root_a.value_n.out_count = 1; root_a.value_n.value_ptr = &root_a_val; LogicNode root_b; root_b.type = LOGIC_NODE_TYPE::VALUE; root_b.value_n.out_count = 1; root_b.value_n.value_ptr = &root_b_val; LogicNode and_gate; and_gate.type = LOGIC_NODE_TYPE::AND; and_gate.and_n.in = new float64[2]; and_gate.and_n.in_received = 0; and_gate.and_n.in_count = 2; and_gate.and_n.out = new LogicNode*[1]; and_gate.and_n.out_count = 1; LogicNode leaf; leaf.type = LOGIC_NODE_TYPE::NONE; root_a.value_n.out = &and_gate; root_b.value_n.out = &and_gate; and_gate.and_n.out[0] = &leaf; foreach (i, 3) { root_a_val = avals[i]; root_b_val = bvals[i]; LogicNode_traverse(&root_a, 0.0, ""); LogicNode_traverse(&root_b, 0.0, ""); std::cout << "------------------------" << std::endl; } delete[] and_gate.and_n.in; delete[] and_gate.and_n.out; //return 0; // auto b = Buffer<usize, 10>::Buffer_make(); // b.count = 0; // for (usize i = 0; i < 10; i += 1) { // b.push_back(i); // } // WEE(b); // WEE(b.slice(1, 3)); // return 0; #ifdef METATESTING puts("metatesting, main program disabled"); metatesting(); return EXIT_SUCCESS; #endif using namespace input_sys; int control_lock_time = 0; bool control_lock = false; //RingBuffer_init(&buff); // Thing_array[0].speed = 1.0f; // TEST change Thing[4].speed to 2.0f // ucharptr ptr = (ucharptr)&Thing_array[0]; // ptr += (4 * meta_arrays[0].element_size); // ptr += Thing_meta_data[1].offset; // *((f32*)ptr) = 2.0f; // std::cout << Thing_array[4].speed << std::endl; std::cout << StaticArrayCount(config_state) << std::endl; // modify for (usize k = 0; k < 2; k += 1) { for (usize i = 0; i < StaticArrayCount(config_state); i += 1) { using pt = PROPERTY_TYPE; switch (config_state[i].type) { case pt::PROP_f64: std::cout << *cast(f64*, config_state[i].ptr) << std::endl; *cast(f64*, config_state[i].ptr) *= 2.0; } } } // reset to defaults for (usize i = 0; i < StaticArrayCount(config_state); i += 1) { using pt = PROPERTY_TYPE; switch (config_state[i].type) { case pt::PROP_f64: *cast(f64*, config_state[i].ptr) = config_state[i].f_f64; } } CommandLineArgs cmd; if (!parse_command_line_args(&cmd, argc, argv)) { return EXIT_FAILURE; } // initialize SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) < 0) { fprintf(stderr, "%s\n", "SDL could not initialize"); return EXIT_FAILURE; } // MOUSE ///////////////////////////////////////////// // hide the cursor // ignore mouse movement events #ifndef EDITOR SDL_ShowCursor(SDL_DISABLE); SDL_SetEventFilter(ignore_mouse_movement, NULL); /////////////////////////// #endif // openGL initialization /////////////////////////////////////////////////// SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1); // SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); // create the window if (NULL == (window = SDL_CreateWindow( WINDOW_HEADER, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) { fprintf(stderr, "Window could not be created\n"); return EXIT_FAILURE; } window_state.focused = true; window_state.minimized = false; //SDL_SetWindowFullscreen(window, true); int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG; if(!(IMG_Init(imgFlags) & imgFlags)) { fprintf(stderr, "SDL_image could not initialize, SDL_image Error: %s\n", IMG_GetError()); SDL_DestroyWindow(window); return EXIT_FAILURE; } program_data.context = SDL_GL_CreateContext(window); glewExperimental = GL_TRUE; glewInit(); ConfigState_load_runtime(); bool status = false; std::string glsl_perlin_noise = Shader_retrieve_src_from_file("shaders/perlin_noise.glsl", &status); if (!status) { fprintf(stderr, "ERROR: failed to load shader addon source"); return EXIT_FAILURE; } // SHADERS Shader shader_2d; if (false == Shader_load_from_file( &shader_2d, "shaders/parallax/parallax_v2_vrt.glsl", "shaders/parallax/parallax_v2_frg.glsl", glsl_perlin_noise, glsl_perlin_noise )) { fprintf(stderr, "ERROR: shader_2d\n"); return EXIT_FAILURE; } Shader shader_grid; if (false == Shader_load_from_file( &shader_grid, "shaders/default_2d/grid_vrt.glsl", "shaders/default_2d/grid_frg.glsl" )) { fprintf(stderr, "ERROR: shader_grid\n"); return EXIT_FAILURE; } /////////////// const GLfloat ASPECT = (GLfloat)SCREEN_WIDTH / (GLfloat)SCREEN_HEIGHT; size_t STRIDE = 5; // QUADS size_t POINTS_PER_QUAD = 4; size_t POINTS_PER_TRI = 3; size_t TRIS_PER_QUAD = 2; GLfloat wf = 1.0f; GLfloat hf = 1.0f * (512.0 / 360.0); const GLfloat OFF = 0.0f * wf * ASPECT; const GLfloat y_off_left = (16.0f / 45.0f); const GLfloat x_off_right = (512.0f / 640.0f); Vec2 tex_res(2048.0f, 1024.0f); Vec3 world_bguv_factor = Vec3(Vec2(1.0f) / tex_res, 1.0f); GLuint layers_per_row = (GLuint)(tex_res.x / SCREEN_WIDTH); // GLfloat x_off = (GLfloat)(GLdouble)(SCREEN_WIDTH / tex_res.x); // GLfloat y_off = (GLfloat)(GLdouble)(SCREEN_HEIGHT / tex_res.x); GLfloat x_ratio = SCREEN_WIDTH / tex_res.x; GLfloat y_ratio = SCREEN_HEIGHT / tex_res.y; GLfloat X_OFF = (tex_res.x - SCREEN_WIDTH) / 2.0f; GLfloat Y_OFF = (tex_res.y - SCREEN_HEIGHT) / 2.0f; GLfloat T[] = { 0.0f - X_OFF, 0.0f - Y_OFF, 0.0f, 0.0f, 0.0f, // top left 0.0f - X_OFF, tex_res.y - Y_OFF, 0.0f, 0.0f, 1.0f, // bottom left tex_res.x - X_OFF, tex_res.y - Y_OFF, 0.0f, 1.0f, 1.0f, // bottom right tex_res.x - X_OFF, 0.0f - Y_OFF, 0.0f, 1.0f, 0.0f, // top right }; GLuint TI[] = { 0, 1, 2, 2, 3, 0, }; //print_array(T, 4, 6); // TOTAL ALLOCATION // const size_t BATCH_COUNT = 1024; // const size_t GUESS_VERTS_PER_DRAW = 4; ////////////////////////////////////////////////// VertexAttributeArray vao_2d2; VertexBufferData tri_data; VertexAttributeArray_init(&vao_2d2, STRIDE); glBindVertexArray(vao_2d2.vao); VertexBufferData_init_inplace( &tri_data, StaticArrayCount(T), T, StaticArrayCount(TI), TI ); gl_bind_buffers_and_upload_data(&tri_data, GL_STATIC_DRAW); // POSITION gl_set_and_enable_vertex_attrib_ptr(0, 3, GL_FLOAT, GL_FALSE, 0, &vao_2d2); // UV gl_set_and_enable_vertex_attrib_ptr(1, 2, GL_FLOAT, GL_FALSE, 3, &vao_2d2); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // GLData grid; // GLData_init_inplace(&grid, STRIDE, StaticArrayCount(T) / 15, T, StaticArrayCount(TI) / 15, TI); // glBindVertexArray(grid.vao); // gl_bind_buffers_and_upload_data(&grid.vbd, GL_STATIC_DRAW, grid.vbd.v_cap, grid.vbd.i_cap, StaticArrayCount(T) / 15, 0); // // POSITION // gl_set_and_enable_vertex_attrib_ptr(0, 3, GL_FLOAT, GL_FALSE, 0, &grid.vao); // // UV // gl_set_and_enable_vertex_attrib_ptr(1, 2, GL_FLOAT, GL_FALSE, 3, &grid.vao); // glBindBuffer(GL_ARRAY_BUFFER, 0); // glBindVertexArray(0); /////////////////////////////////////////////////////////////////////////////////////////////////////////// glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glEnable(GL_MULTISAMPLE); // glEnable(GL_DEPTH_TEST); // glDepthRange(0, 1); // glDepthFunc(GL_LEQUAL); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ONE); //glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX); #ifdef SDL_H { SDL_version compiled; SDL_version linked; SDL_VERSION(&compiled); SDL_GetVersion(&linked); printf( "COMPILED AGAINST SDL VERSION %d.%d.%d.\n", compiled.major, compiled.minor, compiled.patch ); printf( "LINKED AGAINST SDL VERSION %d.%d.%d.\n", linked.major, linked.minor, linked.patch ); } #endif printf("USING GL VERSION: %s\n", glGetString(GL_VERSION)); mat4 mat_ident(1.0f); mat4 mat_projection = glm::ortho( 0.0f, 1.0f * SCREEN_WIDTH, 1.0f * SCREEN_HEIGHT, 0.0f, 0.0f, 1.0f * 10.0f ); //Mat4 mat_projection = glm::perspective(glm::radians(45.0f), (GLfloat)SCREEN_WIDTH / (GLfloat)SCREEN_HEIGHT, 0.1f, 100.0f); ////////////////// // TEST INPUT Vec3 start_pos(0.0f, 0.0f, 1.0f); FreeCamera main_cam; FreeCamera_init(&main_cam, start_pos); main_cam.orientation = Quat(); main_cam.speed = PLAYER_BASE_SPEED; main_cam.offset = Vec2(SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0); main_cam.target = Vec2(0); main_cam.scale = 1.0; // ViewCamera_init( // &main_cam, // start_pos, // ViewCamera_default_speed, // -1000.0f, // 1000.0f, // 0.0f, // 0.0f, // 0.0f, // 0.0f // ); const f64 POS_ACC = 1.08; const f64 NEG_ACC = 1.0 / POS_ACC; // double up_acc = 110.0; // double down_acc = 110.0; // double left_acc = 110.0; // double right_acc = 110.0; // double forwards_acc = 110.0; // double backwards_acc = 110.0; double up_acc = 1.0; double down_acc = 1.0; double left_acc = 1.0; double right_acc = 1.0; double forwards_acc = 1.0; double backwards_acc = 1.0; double max_acc = 1000.0; ///////////////// // MAIN LOOP #ifdef DEBUG_PRINT Vec3 prev_pos(0.0); #endif // Texture tex0; // if (GL_texture_gen_and_load_1(&tex0, "./textures/bg_test_3_3.png", GL_TRUE, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE) == GL_FALSE) { // return EXIT_FAILURE; // } Texture bgs[5]; foreach(i, 5) { if (GL_FALSE == GL_texture_gen_and_load_1( &bgs[i], ("./textures/separate_test_2/" + std::to_string(i) + ".png").c_str(), GL_TRUE, GL_REPEAT, GL_CLAMP_TO_EDGE )) { return EXIT_FAILURE; } } gl_get_errors(); glUseProgram(shader_2d); //UniformLocation RES_LOC = glGetUniformLocation(shader_2d, "u_resolution"); //UniformLocation COUNT_LAYERS_LOC = glGetUniformLocation(shader_2d, "u_count_layers"); UniformLocation MAT_LOC = glGetUniformLocation(shader_2d, "u_matrix"); UniformLocation TIME_LOC = glGetUniformLocation(shader_2d, "u_time"); UniformLocation CAM_LOC = glGetUniformLocation(shader_2d, "u_position_cam"); UniformLocation SCALE_LOC = glGetUniformLocation(shader_2d, "u_scale"); glUniform1f(SCALE_LOC, (GLfloat)1.0); //UniformLocation ASPECT_LOC = glGetUniformLocation(shader_2d, "u_aspect"); const GLuint UVAL_COUNT_LAYERS = 5; //glUniform2fv(RES_LOC, 1, glm::value_ptr(Vec2(SCREEN_WIDTH, SCREEN_HEIGHT))); //glUniform1i(COUNT_LAYERS_LOC, UVAL_COUNT_LAYERS); //glUniform1f(ASPECT_LOC, (GLfloat)SCREEN_WIDTH / (GLfloat)SCREEN_HEIGHT); // TEXTURE 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, bgs[0]); glUniform1i(glGetUniformLocation(shader_2d, "tex0"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, bgs[1]); glUniform1i(glGetUniformLocation(shader_2d, "tex1"), 1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, bgs[2]); glUniform1i(glGetUniformLocation(shader_2d, "tex2"), 2); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, bgs[3]); glUniform1i(glGetUniformLocation(shader_2d, "tex3"), 3); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, bgs[4]); glUniform1i(glGetUniformLocation(shader_2d, "tex4"), 4); gl_get_errors(); #ifdef SD auto drawctx = sd::Render_Batch_make(mat_projection); #endif Toggle free_cam_toggle = false; #ifdef EDITOR glUseProgram(shader_grid); UniformLocation COLOR_LOC_GRID = glGetUniformLocation(shader_grid, "u_color"); glUniform4fv(COLOR_LOC_GRID, 1, glm::value_ptr(Vec4(0.25f, 0.25f, 0.25f, 0.5f))); UniformLocation SQUARE_PIXEL_LOC_GRID = glGetUniformLocation(shader_grid, "u_grid_square_pix"); GLfloat grid_square_pixel_size = 16.0f; glUniform1f(SQUARE_PIXEL_LOC_GRID, tex_res.x / grid_square_pixel_size); UniformLocation MAT_LOC_GRID = glGetUniformLocation(shader_grid, "u_matrix"); UniformLocation CAM_LOC_GRID = glGetUniformLocation(shader_grid, "u_position_cam"); UniformLocation SCALE_LOC_GRID = glGetUniformLocation(shader_grid, "u_scale"); glUniform1f(SCALE_LOC_GRID, (GLfloat)1.0); sd::Render_Batch<> existing; sd::Render_Batch<256> in_prog; Toggle drawing = false; Toggle deletion = false; if (!existing.init(mat_projection)) { fprintf(stderr, "FAILED TO INITIALIZE EDITOR DATA \"existing\"\n"); return EXIT_FAILURE; } if (!in_prog.init(mat_projection)) { fprintf(stderr, "FAILED TO INITIALIZE EDITOR DATA \"in_prog\"\n"); return EXIT_FAILURE; } #endif size_t display_mode_count = 0; SDL_DisplayMode mode; if (SDL_GetDisplayMode(0, 0, &mode) != 0) { SDL_Log("SDL_GetDisplayMode failed: %s", SDL_GetError()); return EXIT_FAILURE; } printf("REFRESH_RATE: %d\n", mode.refresh_rate); SDL_GL_SetSwapInterval(1); const f64 INTERVAL = MS_PER_S / mode.refresh_rate; const f64 REFRESH_RATE = mode.refresh_rate * (60.0 / mode.refresh_rate); f64 frequency = SDL_GetPerformanceFrequency(); u64 t_now = SDL_GetPerformanceCounter(); u64 t_prev = 0.0; u64 t_start = t_now; u64 t_delta = 0; f64 t_now_s = (f64)t_now / frequency; f64 t_prev_s = 0.0; f64 t_since_start_s = 0.0; f64 t_delta_s = 0.0; #ifdef FPS_COUNT f64 frame_time = 0.0; u32 frame_count = 0; u32 fps = 0; #endif input_sys::Input input = {}; input_sys::init(&input); #define CONTROLLER_MAPPING_FILE "./mapping/gamecontrollerdb.txt" if (SDL_GameControllerAddMappingsFromFile(CONTROLLER_MAPPING_FILE) < 0) { fprintf(stderr, "FAILED TO LOAD CONTROLLER MAPPINGS FROM %s\n", CONTROLLER_MAPPING_FILE); } // for (int joystick_index = 0; joystick_index < max_joysticks; ++joystick_index) { // if (!SDL_IsGameController(joystick_index)) { // std::cout << "NOT GAME CONTROLLER" << std::endl; // continue; // } // if (controller_index >= MAX_CONTROLLERS) { // break; // } // controller_handles[controller_index] = SDL_GameControllerOpen(joystick_index); // fprintf(stdout, "CONTROLLER: %s\n", SDL_GameControllerName(controller_handles[controller_index])); // } bool is_running = true; SDL_Event event; #ifdef EDITOR Toggle grid_toggle = false; Toggle physics_toggle = false; Toggle verbose_view_toggle = false; Vec3 in_progress_line[2]; in_progress_line[0] = Vec3(0.0f); in_progress_line[1] = Vec3(0.0f); //// collision_map.next_free_slot()->a = Vec3(0.0, 5 * 128, 0.0); collision_map.next_free_slot()->b = Vec3(SCREEN_WIDTH, 5 * 128, 0.0); collision_map.count += 1; collision_map.next_free_slot()->a = Vec3(512.0, 3 * 128, 0.0); collision_map.next_free_slot()->b = Vec3(768.0, 3 * 128, 0.0); collision_map.count += 1; existing.begin(); existing.draw_type = sd::LINES; existing.color = Color::BLACK; foreach (i, collision_map.count) { SD_ASSERT(existing.line(collision_map[i].a, collision_map[i].b)); } existing.end_no_reset(); Toggle temp = false; //// #endif Player you; Player_init(&you, SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0, 0.0, true, 0, 20, 40); you.state_change_time = t_now; // f64 X[8] = { // glm::degrees(atan2pos_64(0.0, 1.0)), // glm::degrees(atan2pos_64(0.5, 0.5)), // glm::degrees(atan2pos_64(1.0, 0.0)), // glm::degrees(atan2pos_64(0.5, -0.5)), // glm::degrees(atan2pos_64(0.0, -1.0)), // glm::degrees(atan2pos_64(-0.5, -0.5)), // glm::degrees(atan2pos_64(-1.0, 0.0)), // glm::degrees(atan2pos_64(-0.5, 0.5)) // }; // print_array(X, 8); // return 0; // Vec2 a(0, 0); // Vec2 b(1, 1); // std::cout << glm::degrees(atan2pos_64(b.y - a.y, b.x - a.x)) << std::endl; #define AIR_CONFIG_PATH "./config/air.txt" AirPhysicsConfig air_physics_conf; air_physics_conf.path = AIR_CONFIG_PATH; air_physics_conf.fd = fopen(air_physics_conf.path.c_str(), "r"); if (air_physics_conf.fd == nullptr) { fprintf(stderr, "ERROR: CANNOT OPEN AIR CONFIG FILE"); } air_physics_conf.gravity = physics::gravity; air_physics_conf.player_initial_velocity = Player::JUMP_VELOCITY_DEFAULT; air_physics_conf.player_initial_velocity_short = Player::JUMP_VELOCITY_SHORT_DEFAULT; air_physics_conf.t_prev_mod = -1; if (cmd.hot_config) { if (load_config(&air_physics_conf)) { physics::gravity = air_physics_conf.gravity; you.initial_jump_velocity = air_physics_conf.player_initial_velocity; you.initial_jump_velocity_short = air_physics_conf.player_initial_velocity_short; } } //fclose(jump_conf_fd); // audio AudioSystem_init(); AudioArgs audio_args; AudioArgs_init(&audio_args, 1); mal_decoder_config decoder_conf; decoder_conf.format = mal_format_f32; decoder_conf.channels = 2; decoder_conf.sampleRate = 44100; mal_result result = mal_decoder_init_file_wav( "audio/time_rush_v_2_0_1_export_16_bit.wav", &decoder_conf, &audio_args.decoders[0] ); if (result != MAL_SUCCESS) { fprintf(stderr, "ERROR: FAILED TO DECODE AUDIO\n"); return -2; } mal_device_config config = mal_device_config_init_playback( audio_args.decoders[0].outputFormat, audio_args.decoders[0].outputChannels, audio_args.decoders[0].outputSampleRate, on_send_frames_to_device ); if (mal_device_init( NULL, mal_device_type_playback, NULL, &config, &audio_args.decoders[0], &audio_system.device ) != MAL_SUCCESS) { fprintf(stderr, "ERROR: FAILED TO OPEN PLAYBACK DEVICE\n"); mal_decoder_uninit(&audio_args.decoders[0]); return -3; } if (mal_device_start(&audio_system.device) != MAL_SUCCESS) { fprintf(stderr, "ERROR: FAILED TO START PLAYBACK DEVICE\n"); mal_device_uninit(&audio_system.device); mal_decoder_uninit(&audio_args.decoders[0]); return -4; } // printf("press enter to quit..."); // getchar(); // mal_device_uninit(&device); // mal_decoder_uninit(&audio_args.decoders[0]); // return EXIT_SUCCESS; { int w = 0; int h = 0; SDL_GetWindowSize(window, &w, &h); std::cout << "WIDTH: " << w << " HEIGHT: " << h << std::endl; } while (is_running) { t_prev = t_now; t_prev_s = t_now_s; t_now = SDL_GetPerformanceCounter(); t_now_s = (f64)t_now / frequency; t_delta = (t_now - t_prev); t_delta_s = (f64)t_delta / frequency; f64 t_since_start_s = ((f64)(t_now - t_start)) / frequency; // INPUT ///////////////////////////////// if (!poll_input_events(&input, &event)) { is_running = false; continue; } else if (window_state.minimized) { continue; } else if (window_state.restored) { window_state.restored = false; SDL_GL_SwapWindow(window); continue; } bool free_cam_is_on = key_is_toggled(&input, CONTROL::FREE_CAM, &free_cam_toggle); bool camera_locked = key_is_held(&input, CONTROL::UP); if (free_cam_is_on) { main_cam.is_catching_up = true; } else if (camera_locked) { main_cam.is_catching_up = true; } bool left_held = false; bool right_held = false; { //main_cam.orientation = Quat(); if (free_cam_is_on) { if (key_is_held(&input, CONTROL::SHIFT)) { if (key_is_held(&input, CONTROL::UP)) { main_cam.scale += (t_delta_s * 4.0); } else if (key_is_held(&input, CONTROL::DOWN)) { main_cam.scale -= (t_delta_s * 4.0); } main_cam.scale = glm::clamp(main_cam.scale, 0.0625f, 4.0f); // if (key_is_pressed(&input, CONTROL::UP)) { // main_cam.scale = glm::min(4.0, main_cam.scale * 2.0); // } else if (key_is_pressed(&input, CONTROL::DOWN)) { // main_cam.scale = glm::max(0.015625, main_cam.scale / 2.0); // } } else { if (key_is_held(&input, CONTROL::UP)) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::UPWARDS, t_delta_s * up_acc); up_acc *= POS_ACC; up_acc = glm::min(max_acc, up_acc); } else { if (up_acc > 1.0) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::UPWARDS, t_delta_s * up_acc); } up_acc = glm::max(1.0, up_acc * NEG_ACC); } if (key_is_held(&input, CONTROL::DOWN)) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::DOWNWARDS, t_delta_s * down_acc); down_acc *= POS_ACC; down_acc = glm::min(max_acc, down_acc); } else { if (down_acc > 1.0) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::DOWNWARDS, t_delta_s * down_acc); } down_acc = glm::max(1.0, down_acc * NEG_ACC); } } } if (key_is_held(&input, CONTROL::LEFT)) { if (free_cam_is_on) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::LEFTWARDS, t_delta_s * left_acc); } else { // TEMP left_held = true; //Player_move_test(&you, MOVEMENT_DIRECTION::LEFTWARDS, t_delta_s * left_acc); } left_acc *= POS_ACC; left_acc = glm::min(max_acc, left_acc); } else { if (left_acc > 1.0) { if (free_cam_is_on) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::LEFTWARDS, t_delta_s * left_acc); } else { // TEMP //Player_move_test(&you, MOVEMENT_DIRECTION::LEFTWARDS, t_delta_s * left_acc); } } left_acc = glm::max(1.0, left_acc * NEG_ACC); left_acc = glm::min(max_acc, left_acc); } if (key_is_held(&input, CONTROL::RIGHT)) { if (free_cam_is_on) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::RIGHTWARDS, t_delta_s * right_acc); } else { // TEMP right_held = true; //Player_move_test(&you, MOVEMENT_DIRECTION::RIGHTWARDS, t_delta_s * right_acc); } right_acc *= POS_ACC; right_acc = glm::min(max_acc, right_acc); } else { if (right_acc > 1.0) { if (free_cam_is_on) { FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::RIGHTWARDS, t_delta_s * right_acc); } else { // TEMP //Player_move_test(&you, MOVEMENT_DIRECTION::RIGHTWARDS, t_delta_s * right_acc); } } right_acc = glm::max(1.0, right_acc * NEG_ACC); } const f64 dt_factor = DELTA_TIME_FACTOR(t_delta_s, REFRESH_RATE); const f64 friction = Player::GROUND_ACCELERATION_DEFAULT; // TODO ground to air, air to ground angles, probably keep a single variable to share between ground and air instead (rewrite) //std::cout << you.bound.spatial.w << std::endl; float64 angle = you.bound.spatial.w; // TODO RE-ADD STATEMENT std::cout << "ANGLE: " << angle << std::endl; if (you.on_ground) { //std::cout << "BEFORE" << you.velocity_ground.x << std::endl; you.velocity_ground.x -= (.125 * 4) * glm::sin(angle) * dt_factor; //std::cout << "SUBTRACTING " << (.125 * 4) * glm::sin(angle) * dt_factor << std::endl; //std::cout << "AFTER " << you.velocity_ground.x << std::endl; #define ANGLE_TOO_STEEP ((PI / 8) * 3) // if (((angle <= -(glm::pi<f64>() / 8) * 3) && you.velocity_ground.x < 0.0) || // ((angle >= (glm::pi<f64>() / 8) * 3) && you.velocity_ground.x > 0.0)) { if (left_held && -angle < ANGLE_TOO_STEEP) { if (you.velocity_ground.x > 0.0) { you.velocity_ground.x -= Player::GROUND_NEGATIVE_ACCELERATIION_DEFAULT * dt_factor; } else { you.velocity_ground.x -= you.acceleration_ground * dt_factor; } } else if (right_held && angle < ANGLE_TOO_STEEP) { if (you.velocity_ground.x < 0.0) { you.velocity_ground.x += Player::GROUND_NEGATIVE_ACCELERATIION_DEFAULT * dt_factor; //std::cout << "SUBTRACTING SLOPE FACTOR: " << (.125 * 4) * glm::sin(angle) << std::endl; //std::cout << "ADDING DECCELERATION: " << Player::GROUND_NEGATIVE_ACCELERATIION_DEFAULT << std::endl; //std::cout << "DIFF DEC - SLOPE: " << Player::GROUND_NEGATIVE_ACCELERATIION_DEFAULT - (.125 * 4) * glm::sin(angle) << std::endl; } else { you.velocity_ground.x += you.acceleration_ground * dt_factor; } } else if (you.velocity_ground.x != 0.0) { // TODO improve friction if (glm::abs(you.velocity_ground.x) < friction * dt_factor) { you.velocity_ground.x = 0.0; } else { you.velocity_ground.x -= friction * glm::sign(you.velocity_ground.x) * dt_factor; } } } else { // TODO switch between velocity_ground and velocity_air or just use one velocity for both if (left_held) { you.velocity_ground.x -= you.acceleration_air * dt_factor; } else if (right_held) { you.velocity_ground.x += you.acceleration_air * dt_factor; } if (you.velocity_air.y < 0 && you.velocity_air.y > -4.0) { if (glm::abs(you.velocity_ground.x) >= 16.0) { you.velocity_ground.x *= 0.90; } } } if (you.velocity_ground.x < -you.max_speed) { you.velocity_ground.x = -you.max_speed; } else if (you.velocity_ground.x > you.max_speed) { you.velocity_ground.x = you.max_speed; } float64 y_comp = -glm::sin(angle); float64 x_comp = glm::cos(angle); // TODO RE-ADD STATEMENT std::cout << "V: " << you.velocity_ground.x << ":" << x_comp << ":" << y_comp << " SLOPE FACTOR: " << (.125 * 4) * glm::sin(angle) * dt_factor << std::endl; if (you.on_ground) { // if (((angle <= -(glm::pi<f64>() / 8) * 3) && you.velocity_ground.x < 0.0) || // ((angle >= (glm::pi<f64>() / 8) * 3) && you.velocity_ground.x > 0.0)) { // you.velocity_ground.x = -you.velocity_ground.x * x_comp; // you.velocity_ground.y = -you.velocity_ground.y * y_comp; // } you.bound.spatial.x += you.velocity_ground.x * x_comp; you.bound.spatial.y += you.velocity_ground.x * y_comp; //draw_player_collision(&you, &drawctx); } else { you.bound.spatial.x += you.velocity_ground.x; } //printf("%f %f\n", you.velocity_ground.x, you.velocity_air.y); { bool collided_l = false; bool collided_r = false; CollisionStatus status_l; CollisionStatus_init(&status_l, Vec3(NEGATIVE_INFINITY, NEGATIVE_INFINITY, 0.0)); CollisionStatus status_r; CollisionStatus_init(&status_r); // this will be off by one movement, need to reorganize so camera updated after play is updated, // also cannot draw bg yet... will need to sequence things differently drawctx.begin(); drawctx.transform_matrix = FreeCamera_calc_view_matrix(&main_cam); for (auto it = collision_map.begin(); it != collision_map.next_free_slot(); it += 1) { //Collider_print(it); switch (temp_test_collision_sides(&you, it, &status_l, &status_r)) { case 'l': { // left drawctx.line(Vec3(0.0), status_l.intersection); collided_l = true; break; } case 'r': { // right drawctx.line(Vec3(0.0), status_r.intersection); collided_r = true; break; } case 'b': { // both collided_l = true; collided_r = true; break; } default: { // none break; } } } drawctx.end_no_reset(); // TODO slopes if (collided_l) { f64 angle = atan2_64(status_l.collider->b.y - status_l.collider->a.y, status_l.collider->b.x - status_l.collider->a.x); angle = glm::abs(angle); if (angle > ((PI / 8) * 3)) { //std::cout << "COLLIDED L" << std::endl; you.bound.spatial.x = status_l.intersection.x; you.velocity_ground.x = 0.0; } } if (collided_r) { f64 angle = atan2_64(status_r.collider->b.y - status_r.collider->a.y, status_r.collider->b.x - status_r.collider->a.x); angle = glm::abs(angle); //std::cout << "COLLIDED R" << std::endl; if (angle > ((PI / 8) * 3)) { you.bound.spatial.x = status_r.intersection.x - you.bound.width; you.velocity_ground.x = 0.0; } } } // if (*forwards) { // FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::FORWARDS, t_delta_s * forwards_acc); // forwards_acc *= POS_ACC; // forwards_acc = glm::min(max_acc, forwards_acc); // } else { // if (forwards_acc > 1.0) { // FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::FORWARDS, t_delta_s * forwards_acc); // } // forwards_acc = glm::max(1.0, forwards_acc * NEG_ACC); // } // if (*backwards) { // FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::BACKWARDS, t_delta_s * backwards_acc); // backwards_acc *= POS_ACC; // backwards_acc = glm::min(max_acc, backwards_acc); // } else { // if (backwards_acc > 1.0) { // FreeCamera_process_directional_movement(&main_cam, MOVEMENT_DIRECTION::BACKWARDS, t_delta_s * backwards_acc); // } // backwards_acc = glm::max(1.0, backwards_acc * NEG_ACC); // } if (key_is_pressed(&input, CONTROL::RESET_POSITION)) { // FreeCamera_init( // &main_cam, // start_pos, // ViewCamera_default_speed, // -1000.0f, // 1000.0f, // 0.0f, // 0.0f, // 0.0f, // 0.0f // ); main_cam.position = start_pos; main_cam.orientation = Quat(); main_cam.is_catching_up = false; main_cam.scale = 1.0; up_acc = 1.0; down_acc = 1.0; left_acc = 1.0; right_acc = 1.0; backwards_acc = 1.0; forwards_acc = 1.0; Player_init(&you, SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0, 0.0, true, 0, 20, 40); you.state_change_time = t_now; you.on_ground = false; } if (!free_cam_is_on && !(camera_locked)) { FreeCamera_target_set(&main_cam, you.bound.calc_position_center()); FreeCamera_target_follow(&main_cam, t_delta_s); //up_acc = 1.0; //down_acc = 1.0; } } // AUDIO TEST switch (key_is_toggled_4_states(&input, CONTROL::TEMP, &temp)) { case TOGGLE_BRANCH::PRESSED_ON: { AudioCommand* cmd = (AudioCommand*)xmalloc(sizeof(*cmd)); cmd->type = AUDIO_COMMAND_TYPE::ADJUST_MASTER_VOLUME; cmd->adjust_master_volume.duration = 5.0f; cmd->adjust_master_volume.from = 1.0f; cmd->adjust_master_volume.to = 0.0f; cmd->adjust_master_volume.t_delta = 0.0f; cmd->adjust_master_volume.t_prev = 0.0f; if (ck_ring_enqueue_spsc(&audio_args.fifo.ring, audio_args.fifo.buffer, (void*)cmd) == false) { fprintf(stderr, "ERROR: OUT OF AUDIO QUEUE SPACE\n"); } break; } case TOGGLE_BRANCH::ON: { break; } case TOGGLE_BRANCH::PRESSED_OFF: { AudioCommand* cmd = (AudioCommand*)xmalloc(sizeof(*cmd)); cmd->type = AUDIO_COMMAND_TYPE::ADJUST_MASTER_VOLUME; cmd->adjust_master_volume.duration = 5.0f; cmd->adjust_master_volume.from = 0.0f; cmd->adjust_master_volume.to = 1.0f; cmd->adjust_master_volume.t_delta = 0.0f; cmd->adjust_master_volume.t_prev = 0.0f; if (ck_ring_enqueue_spsc(&audio_args.fifo.ring, audio_args.fifo.buffer, (void*)cmd) == false) { fprintf(stderr, "ERROR: OUT OF AUDIO QUEUE SPACE\n"); } break; } case TOGGLE_BRANCH::OFF: { break; } default: { break; } } //main_cam.rotate((GLfloat)curr_time / MS_PER_S, 0.0f, 0.0f, 1.0f); ////////////////// // DRAW glClearColor(97.0 / 255.0, 201.0 / 255.0, 255.0 / 255.0, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shader_2d); //glUniformMatrix4fv(MAT_LOC, 1, GL_FALSE, glm::value_ptr(ViewCamera_calc_view_matrix(&main_cam) * mat_ident)); glUniformMatrix4fv(MAT_LOC, 1, GL_FALSE, glm::value_ptr( mat_projection /**FreeCamera_calc_view_matrix(&main_cam)*/ /*glm::translate(mat_ident, Vec3(glm::sin(((double)t_now / frequency)), 0.0, 0.0)) * */ /*glm::scale(mat_ident, Vec3(0.25, 0.25, 1.0))* */ ) ); glUniform1f(TIME_LOC, t_since_start_s); Vec3 pos = main_cam.position; #ifdef DEBUG_PRINT if (pos.x != prev_pos.x || pos.y != prev_pos.y || pos.z != prev_pos.z) { std::cout << "VIEW_POSITION{x : " << pos.x << ", y : " << pos.y << ", z: " << pos.z << "}" << std::endl; } prev_pos.x = pos.x; prev_pos.y = pos.y; prev_pos.z = pos.z; #endif // Vec3 VV = pos * world_bguv_factor; // vec3_print(&VV); // std::cout << std::endl; glUniform1f(SCALE_LOC, main_cam.scale); glUniform3fv(CAM_LOC, 1, glm::value_ptr(pos * world_bguv_factor)); //glEnable(GL_DEPTH_TEST); //glClear(GL_DEPTH_BUFFER_BIT); // glDepthRange(0, 1); { //Vec2 P = Vec2(pos * world_bguv_factor); //P.y = glm::clamp(P.y, -1.45f, 1.45f); //f64 x_off = P.x; //f64 y_off = P.y; //Vec2 t4c = Vec2(0, 0); //t4c.x += (x_off / 1.0); //t4c.y += (y_off / 1.0); //vec2_println(t4c); //t4c = SCALED(t4c, vec2(x_off / 1.0, y_off / 1.0), scaler); //t4c = fract(t4c); //vec2_println(t4c); } //glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glDisable(GL_DEPTH_TEST); glBindVertexArray(vao_2d2.vao); glDrawElements(GL_TRIANGLES, tri_data.i_count, GL_UNSIGNED_INT, 0); //glBindVertexArray(0); #ifdef SD glEnable(GL_DEPTH_TEST); glDepthRange(0, 1); glClear(GL_DEPTH_BUFFER_BIT); Mat4 cam = FreeCamera_calc_view_matrix(&main_cam); // drawctx.begin(); // //drawctx.transform_matrix = FreeCamera_calc_view_matrix(&main_cam); // drawctx.transform_matrix = Mat4(1.0f); // // drawctx.draw_type = GL_LINES; // // drawctx.color = Color::RED; // // drawctx.vertex({0.5, 0.0, -1.0}); // // drawctx.vertex({1.0, 1.0, -1.0}); // // drawctx.draw_type = GL_LINES; // // drawctx.color = Color::GREEN; // // drawctx.line({0.0, 0.0, -5.0}, {1.0, 1.0, -5.0}); // // drawctx.color = Color::GREEN; // // drawctx.circle(0.25, {0.0, 0.0, 0.0}); // drawctx.draw_type = GL_TRIANGLES; // GLfloat CX = (SCREEN_WIDTH / 2.0f); // GLfloat CY = 384.0f; // drawctx.color = Vec4(252.0f / 255.0f, 212.0f / 255.0f, 64.0f / 255.0f, 1.0f); // drawctx.transform_matrix = cam; // drawctx.circle(90.0f, {CX, CY, -1.0}); // drawctx.color = Vec4(0.0f, 0.0f, 0.0f, 1.0f); // drawctx.transform_matrix = glm::translate(cam, Vec3(CX - 27.0f, CY - 25.0f, 0.0f)); // drawctx.circle(10.0f, {0.0f, 0.0f, 0.0f}); // drawctx.color = Vec4(0.0f, 0.0f, 0.0f, 1.0f); // drawctx.transform_matrix = glm::translate(cam, Vec3(CX + 27.0f, CY - 25.0f, 0.0f)); // drawctx.circle(10.0f, {0.0f, 0.0f, 0.0f}); // drawctx.draw_type = GL_LINES; // #define BASE_TILE_SIZE (128.0f) // #define TILE_SCALE (2.0f) // CX = 5.0f / TILE_SCALE; // CY = 3.0f / TILE_SCALE; // Mat4 model(1.0f); // model = glm::scale(model, Vec3(BASE_TILE_SIZE * TILE_SCALE, BASE_TILE_SIZE * TILE_SCALE, 1.0f)); // model = glm::translate(model, Vec3({CX, CY, 0.0})); // model = glm::rotate(model, (GLfloat)t_since_start, Vec3(0.0f, 0.0f, 1.0f)); // model = glm::translate(model, Vec3({-CX, -CY, 0.0})); // drawctx.transform_matrix = cam * model; // drawctx.color = Vec4(1.0f, 0.0f, 0.0f, 1.0f); // { // GLfloat off = 1.0f; // // horizontal // drawctx.line(Vec3(CX - off, CY - off, 0.0f), Vec3(CX + off, CY - off, 0.0f)); // drawctx.line(Vec3(CX - off, CY + off, 0.0f), Vec3(CX + off, CY + off, 0.0f)); // // vertical // drawctx.line(Vec3(CX - off, CY - off, 0.0f), Vec3(CX - off, CY + off, 0.0f)); // drawctx.line(Vec3(CX + off, CY - off, 0.0f), Vec3(CX + off, CY + off, 0.0f)); // } // drawctx.end(); #endif #ifdef EDITOR if (key_is_toggled(&input, CONTROL::EDIT_MODE, &grid_toggle)) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClear(GL_DEPTH_BUFFER_BIT); glUseProgram(shader_grid); glUniform1f(glGetUniformLocation(shader_grid, "u_time"), t_since_start_s); glUniform1f(SCALE_LOC_GRID, main_cam.scale); if (key_is_pressed(&input, CONTROL::ZOOM_IN)) { grid_square_pixel_size *= 2; grid_square_pixel_size = glm::clamp(grid_square_pixel_size, 4.0f, 128.0f); glUniform1f(SQUARE_PIXEL_LOC_GRID, tex_res.x / grid_square_pixel_size); } else if (key_is_pressed(&input, CONTROL::ZOOM_OUT)) { grid_square_pixel_size /= 2; grid_square_pixel_size = glm::clamp(grid_square_pixel_size, 4.0f, 128.0f); glUniform1f(SQUARE_PIXEL_LOC_GRID, tex_res.x / grid_square_pixel_size); } glUniformMatrix4fv(MAT_LOC_GRID, 1, GL_FALSE, glm::value_ptr( mat_projection ) ); glUniform3fv(CAM_LOC_GRID, 1, glm::value_ptr(pos)); glBindVertexArray(vao_2d2.vao); glDrawElements(GL_TRIANGLES, tri_data.i_count, GL_UNSIGNED_INT, 0); //Mat4 mat_screen_to_world = FreeCamera_calc_view_matrix_reverse(&main_cam); Vec4 mouse = Vec4((int)input.mouse_x, (int)input.mouse_y, 0.0f, 1.0f); mouse = glm::inverse(cam) * mouse; i32 grid_len = (tex_res.x / grid_square_pixel_size); // puts("{"); // puts("BEFORE SNAP: "); // vec2_println(Vec2(mouse)); // puts("AFTER SNAP: "); // vec2_println(Vec2(snap_to_grid(mouse.x, grid_len), snap_to_grid(mouse.y, grid_len))); // puts("}\n"); // {// SCALING WITH MOUSE INPUT IS NOT CORRECT, WILL LIKELY NEED TO CHANGE A LOT // Vector2 o_mouse = vec2(mouse); // { // // manual // Vector2 m2 = o_mouse; // Vector2 c1 = vec2(main_cam.position); // m2 -= (c1 + ((vec2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)))); // m2 /= main_cam.scale; // m2 += (c1 + ((vec2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)))); // mouse = vec4(m2, 1.0, 1.0); // std::cout << "{ORIGINAL:" << std::endl; // vec2_print(&o_mouse); // std::cout << std::endl; // } // // matrix // // snap the mouse to the default grid // vec2 m = vec2( // o_mouse.x, //snap_to_grid(o_mouse.x, grid_len), // o_mouse.y //snap_to_grid(o_mouse.y, grid_len) // ); // std::cout << "PRE TRANSFORM:" << std::endl; // vec2_print(&m); // std::cout << "}" << std::endl; // vec2 cam = vec2(main_cam.position); // std::cout << "CAM: " << std::endl; // vec2_println(cam); // m -= (cam + main_cam.offset); // m /= main_cam.scale; // m += (cam + main_cam.offset); // std::cout << "POST TRANSFORM:" << std::endl; // vec2_print(&m); // std::cout << "}" << std::endl; // { // std::cout << "QUICK: " << std::endl; // // vec2 m_raw = vec2((int)input.mouse_x, (int)input.mouse_y); // #define LEN_TEST (8) // vec2 m_raw = Vec2( // ((float)input.mouse_x / SCREEN_WIDTH) * LEN_TEST, // ((float)input.mouse_y / SCREEN_HEIGHT) * LEN_TEST); // mat4 mat = mat4(1.0f); // #define POS 0, 0 // mat = glm::translate(mat, Vec3(Vec2(POS) + Vec2(LEN_TEST / 2), 0)); // mat = glm::scale(mat, Vec3(1.0 / main_cam.scale, 1.0 / main_cam.scale, 1)); // mat = glm::translate(mat, -Vec3(Vec2(POS) + Vec2(LEN_TEST / 2), 0)); // mat = glm::translate(mat, Vec3(Vec2(POS), 0)); // mat4 mat2 = glm::translate(Mat4(1.0f), Vec3(Vec2(POS) + Vec2(LEN_TEST / 2), 0)) * // glm::scale(Vec3(1.0 / main_cam.scale, 1.0 / main_cam.scale, 1)) * // glm::translate(-Vec3(Vec2(POS) + Vec2(LEN_TEST / 2), 0)) * // glm::translate(Vec3(Vec2(POS), 0)); // if (mat == mat2) { // puts("WEE"); // mat = mat2; // } else { // puts("NO"); // } // #undef POS // #undef LEN_TEST // vec2 out = Vec2(mat * Vec4(m_raw, 0, 1)); // std::cout << "BEFORE SNAP: " << std::endl; // vec2_println(out); // out.x = snap_to_grid_f(out.x, 1); // out.y = snap_to_grid_f(out.y, 1); // vec2_println(out); // std::cout << std::endl << std::endl; // } // } //printf("CURSOR: [x: %f, y: %f]\n", mouse.x, mouse.y); // if (mouse_is_toggled(&input, MOUSE_BUTTON::LEFT, &drawing)) { // printf("TOGGLED DRAWING ON\n"); // } else if (mouse_is_pressed(&input, MOUSE_BUTTON::LEFT) && !drawing) { // printf("ENDING DRAWING\n"); // } // if (drawing) { // printf("DRAWING\n"); // } glClear(GL_DEPTH_BUFFER_BIT); // vec4_print(&mouse); // std::cout << std::endl; // vec3_print(&main_cam.position); // std::cout << std::endl; //printf("CURSOR_SNAPPED: [x: %d, y: %d]\n", snap_to_grid(mouse.x, grid_len / main_cam.scale), snap_to_grid(mouse.y, grid_len / main_cam.scale)); if (mouse_is_toggled(&input, MOUSE_BUTTON::RIGHT, &deletion)) { drawing = false; existing.begin(); existing.transform_matrix = cam; existing.draw_type = sd::LINES; //existing.transform_matrix = cam; existing.end_no_reset(); glClear(GL_DEPTH_BUFFER_BIT); if (mouse_is_pressed(&input, MOUSE_BUTTON::LEFT)) { in_prog.begin(); { in_prog.draw_type = sd::TRIANGLES; in_prog.transform_matrix = cam; in_prog.color = Color::RED; sd::circle( &in_prog, 10.0f * (1.0 / main_cam.scale), Vec3( mouse.x, mouse.y, 1.0f ), 32 ); } in_prog.end(); // Vec3 M = Vec3(mouse); // vec3_print(&M); // std::cout << std::endl; auto it = collision_map.begin(); f64 min_dist = dist_to_segment_squared(it->a, it->b, mouse); Collider* nearest_seg = it; usize selection = 0; it += 1; usize idx = 1; for (; it != collision_map.next_free_slot(); it += 1) { f64 d2 = dist_to_segment_squared(it->a, it->b, mouse); if (d2 < min_dist) { min_dist = d2; nearest_seg = it; selection = idx; } idx += 1; } if (min_dist <= COLLIDER_MAX_SELECTION_DISTANCE * (1.0 / main_cam.scale)) { in_prog.begin(); in_prog.draw_type = sd::LINES; in_prog.transform_matrix = cam; in_prog.color = Color::RED; in_prog.line(nearest_seg->a, nearest_seg->b); in_prog.end(); collision_map[selection] = collision_map[collision_map.count - 1]; collision_map.count -= 1; sd::remove_line_swap_end(&existing, selection); } } else { in_prog.begin(); { in_prog.draw_type = sd::TRIANGLES; in_prog.transform_matrix = cam; in_prog.color = Color::RED; sd::circle( &in_prog, 5.0f * (1.0 / main_cam.scale), Vec3( mouse.x, mouse.y, 1.0f ), 32 ); } in_prog.end(); } } else { switch (mouse_is_toggled_4_states(&input, MOUSE_BUTTON::LEFT, &drawing)) { case TOGGLE_BRANCH::PRESSED_ON: //printf("TOGGLED DRAWING ON\n"); in_progress_line[0].x = snap_to_grid(mouse.x, grid_len); in_progress_line[0].y = snap_to_grid(mouse.y, grid_len); in_progress_line[0].z = mouse.z; collision_map.next_free_slot()->a = in_progress_line[0]; collision_map.next_free_slot()->a.z = 0; case TOGGLE_BRANCH::ON: //printf("\tDRAWING\n"); in_progress_line[1].x = snap_to_grid(mouse.x, grid_len); in_progress_line[1].y = snap_to_grid(mouse.y, grid_len); in_progress_line[1].z = mouse.z; collision_map.next_free_slot()->b = in_progress_line[1]; collision_map.next_free_slot()->b.z = 0; in_prog.begin(); in_prog.draw_type = sd::LINES; in_prog.transform_matrix = cam; in_prog.color = Color::BLACK; in_prog.line(in_progress_line[0], in_progress_line[1]); { in_prog.draw_type = sd::TRIANGLES; in_prog.transform_matrix = cam; in_prog.color = Color::BLUE; sd::circle( &in_prog, 5.0f * (1.0 / main_cam.scale), Vec3( snap_to_grid(mouse.x, grid_len), snap_to_grid(mouse.y, grid_len), 1.0f ), 32 ); } in_prog.end(); existing.begin(); existing.transform_matrix = cam; existing.draw_type = sd::LINES; //existing.transform_matrix = cam; existing.end_no_reset(); break; case TOGGLE_BRANCH::PRESSED_OFF: //printf("ENDING DRAWING\n"); collision_map.count += 1; in_prog.begin(); { in_prog.draw_type = sd::TRIANGLES; in_prog.transform_matrix = cam; in_prog.color = Color::GREEN; sd::circle( &in_prog, 10.0f * (1.0 / main_cam.scale), Vec3( snap_to_grid(mouse.x, grid_len), snap_to_grid(mouse.y, grid_len), 1.0f ), 32 ); } in_prog.end(); existing.begin(); existing.transform_matrix = cam; existing.draw_type = sd::LINES; //existing.transform_matrix = cam; //sort_segment(in_progress_line); existing.line(in_progress_line[0], in_progress_line[1]); // { // f64 dy = in_progress_line[1].y - in_progress_line[0].y; // f64 dx = in_progress_line[1].x - in_progress_line[0].x; // existing.color = Color::BLUE; // Vec3 na(-dy, dx, 0.0); // Vec3 nb(dy, -dx, 0.0); // //na = glm::normalize(na); // //nb = glm::normalize(nb); // existing.line(na, nb); // existing.color = Color::BLACK; // vec3_pair_print(&na, &nb); // } existing.end_no_reset(); break; case TOGGLE_BRANCH::OFF: in_prog.begin(); { in_prog.draw_type = sd::TRIANGLES; in_prog.transform_matrix = cam; in_prog.color = Color::BLUE; sd::circle( &in_prog, 5.0f * (1.0 / main_cam.scale), Vec3( snap_to_grid(mouse.x, grid_len), snap_to_grid(mouse.y, grid_len), 1.0f ), 32 ); } in_prog.end(); existing.begin(); existing.transform_matrix = cam; existing.draw_type = sd::LINES; //existing.transform_matrix = cam; existing.end_no_reset(); break; default: break; } } drawctx.begin(); glClear(GL_DEPTH_BUFFER_BIT); drawctx.draw_type = sd::LINES; drawctx.color = Color::BLUE; drawctx.transform_matrix = cam; //draw_lines_from_image(&drawctx, "./test_paths/C.bmp", {Vec3(1.0f), Vec3(0.0f)}); // f64 WEE = ((f64)(t_now - you.state_change_time)) / frequency; // if (/*key_is_toggled(&input, CONTROL::PHYSICS, &physics_toggle) && */!you.on_ground) { // you.bound.spatial.y = you.bound.spatial.y + 1 * 9.81 * (WEE * WEE); // } else if (key_is_pressed(&input, CONTROL::JUMP)) { // TEMPORARY // you.bound.spatial.y -= you.bound.height * 4; // } drawctx.end(); drawctx.begin(); glClear(GL_DEPTH_BUFFER_BIT); drawctx.color = Color::GREEN; drawctx.transform_matrix = cam; if (cmd.hot_config && air_physics_conf.fd != nullptr && key_is_pressed(&input, CONTROL::LOAD_CONFIG)) { if (load_config(&air_physics_conf)) { physics::gravity = air_physics_conf.gravity; you.initial_jump_velocity= air_physics_conf.player_initial_velocity; you.initial_jump_velocity_short = air_physics_conf.player_initial_velocity_short; } //fseek(air_physics_conf.fd, 0L, SEEK_SET); } //std::cout << (GRAVITY_DEFAULT * t_delta_s * INTERVAL) << std::endl; //std::cout << t_delta_s * INTERVAL << std::endl; if (!you.on_ground) { //std::cout << "MULTIPLIER V1 " << (INTERVAL / t_delta_s) / 1000 << std::endl; //std::cout << "MULTIPLIER V2 " << (1 / (t_delta_s * REFRESH_RATE)) << std::endl; // TODO JUMP needs to take angles into consideration when dealing with the impulse if (!key_is_held(&input, CONTROL::JUMP)) { if (you.velocity_air.y < you.initial_jump_velocity_short) { you.velocity_air.y = you.initial_jump_velocity_short; } } you.velocity_air.y += (physics::gravity * DELTA_TIME_FACTOR(t_delta_s, REFRESH_RATE)); if (you.velocity_air.y > 16) { you.velocity_air.y = 16; } you.bound.spatial.x += you.velocity_air.x; you.bound.spatial.y += you.velocity_air.y; } bool collided = false; CollisionStatus status; CollisionStatus_init(&status); for (auto it = collision_map.begin(); it != collision_map.next_free_slot(); it += 1) { //Collider_print(it); if (temp_test_collision(&you, it, &status)) { //printf("COLLISION\n"); drawctx.line(Vec3(0.0), status.intersection); you.on_ground = true; // you.state_change_time = t_now; collided = true; //puts("COLLIDED"); } else { //puts("NO COLLISION"); } } // Vec2 tang = .1 * angular_impulse(glm::pi<double>() / 30.0, Vec2(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5), Vec2(you.bound.spatial.x, you.bound.spatial.y)); // drawctx.circle(glm::distance(Vec2(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5), Vec2(you.bound.calc_position_center())), Vec3(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5, 1.0)); // drawctx.color = Vec4(1.0, 1.0, 0.0, 1.0); // drawctx.line(Vec2(you.bound.calc_position_center()), tang + Vec2(you.bound.calc_position_center())); if (!collided) { you.on_ground = false; } else { if (you.on_ground) { if (key_is_pressed(&input, CONTROL::JUMP)) { you.velocity_air.y = you.initial_jump_velocity; //you.velocity_air.x += tang.x; //you.velocity_air.y += tang.y; you.on_ground = false; // temp move this // send data args as pointer to pre-allocated buffer AudioCommand* cmd = (AudioCommand*)xmalloc(sizeof(*cmd)); cmd->type = AUDIO_COMMAND_TYPE::DELAY; cmd->delay.decay = 0.4; cmd->delay.channel_a_offset_percent = 0.0; cmd->delay.channel_b_offset_percent = 0.05; if (ck_ring_enqueue_spsc(&audio_args.fifo.ring, audio_args.fifo.buffer, (void*)cmd) == false) { fprintf(stderr, "ERROR: OUT OF AUDIO QUEUE SPACE\n"); } } else { you.velocity_air = Vec3(0.0); } } //you.bound.spatial.x = out.x - (1 * you.bound.width); <-- ENABLE TO MAKE THE FLOOR A TREADMILL you.bound.spatial.y = status.intersection.y - (1 * you.bound.height); Collider* col = status.collider; Vec3* a = &col->a; Vec3* b = &col->b; you.bound.spatial.w = atan2_64(b->y - a->y, b->x - a->x); // draw surface and normals if (key_is_toggled(&input, CONTROL::EDIT_VERBOSE, &verbose_view_toggle)) { f64 dy = col->b.y - col->a.y; f64 dx = col->b.x - col->a.x; auto na = Vec3{-dy, dx, 0.0}; auto nb = Vec3{dy, -dx, 0.0}; //na = glm::normalize(na); //nb = glm::normalize(nb); drawctx.color = Color::CYAN; sd::line(&drawctx, status.collider->a, status.collider->b); drawctx.color = Color::BLUE; sd::line(&drawctx,/* na + */col->a, nb + col->a); //existing.color = Color::BLACK; //vec3_pair_print(&na, &nb); //std::cout << glm::degrees(you.bound.spatial.w) << std::endl; } } drawctx.color = Color::BLUE; draw_player_collision(&you, &drawctx); drawctx.end(); glDisable(GL_BLEND); // if (collision_map.count > 0) { // printf("{"); // for (auto it = collision_map.begin(); it != collision_map.next_free_slot(); ++it) // { // printf("\n"); // Collider_print(it); // } // printf("\n}\n"); // } //existing.projection_matrix = mat_projection * FreeCamera_calc_view_matrix(&main_cam); //existing.render(&existing); //in_prog.transform_matrix = FreeCamera_calc_view_matrix(&main_cam); //in_prog.render(&in_prog); sd::batch_render(&in_prog); } //drawctx.transform_matrix = FreeCamera_calc_view_matrix(&main_cam); //drawctx.render(&drawctx); sd::batch_render(&drawctx); #endif SDL_GL_SwapWindow(window); #ifdef FPS_COUNT frame_count += 1; if (t_now_s - frame_time > 1.0) { fps = frame_count; frame_count = 0; frame_time = t_now_s; printf("%f\n", (double)fps); } #endif ////////////////// } mal_device_uninit(&audio_system.device); mal_decoder_uninit(&audio_args.decoders[0]); if (air_physics_conf.fd != nullptr) { fclose(air_physics_conf.fd); } VertexAttributeArray_delete(&vao_2d2); VertexBufferData_delete_inplace(&tri_data); #ifdef SD sd::free(&drawctx); #endif #ifdef EDITOR sd::free(&in_prog); sd::free(&existing); glDeleteProgram(shader_grid); #endif glDeleteProgram(shader_2d); SDL_GL_DeleteContext(program_data.context); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return EXIT_SUCCESS; }
#ifndef CINEMASIMULATION_H #define CINEMASIMULATION_H #include "ServiceDesk.h" class CinemaSimulation { public: CinemaSimulation(int simulationLen, int timeBetweenPeople); void run(); void printStats() const; protected: private: int timeBetweenPeople; int incomingPeopleCountdown; int simulationLen; ServiceDesk tickets; ServiceDesk popcorn; ServiceDesk glasses; void tick(); void addPeopleToTicketQueue(int numPeople); }; #endif // CINEMASIMULATION_H
#pragma once #include <cstdlib> #include <iostream> #include "Windows.h" #include <string> using namespace std; void TakeName(); void TimerIO(); void Update();
//ex14.cpp 的pair写法 #include <bits/stdc++.h> using namespace std; char maze[205][205]; bool vis[205][205]; int step[205][205]; int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; queue<pair<int,int>> p; int n, m; bool in(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; } int bfs(int x, int y) { p.push(make_pair(x, y)); vis[x][y] = 1; while(!p.empty()) { pair<int, int> now = p.front(); p.pop(); for (int i = 0; i < 4; ++i) { int tx = now.first + dir[i][0]; int ty = now.second + dir[i][1]; if(in(tx, ty) && maze[tx][ty] != '#' && !vis[tx][ty]) { if (maze[tx][ty] == 'a') { return step[tx][ty] = step[now.first][now.second] + 1; } else if (maze[tx][ty] == 'x') { vis[x][y] = 1; p.push(make_pair(tx, ty)); step[tx][ty] = step[now.first][now.second] + 2; } else { vis[x][y] = 1; p.push(make_pair(tx, ty)); step[tx][ty] = step[now.first][now.second] + 1; } } } } return -1; } int main(){ freopen("note.txt", "r", stdin); freopen("ans.txt", "w", stdout); int i, j; int x, y; int ans = -1; cin >> n >> m; for (i = 0; i < n; ++i) { cin >> maze[i]; } for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { if (maze[i][j] == 'r') { x = i; y = j; break; } } if (maze[i][j] == 'r') break; } ans = bfs(x, y); if (ans == -1){ cout << "Impossible" << endl; } else { cout << ans << endl; } return 0; }
/****************************************************************************/ /* C++ library for creating a game (i.e., set of all strongly connected */ /* components) */ /* Written by SCHULZ Quentin, quentin.schulz@utbm.fr , Nov. 2013 */ /****************************************************************************/ #include "stronglyconnectedcomponents.hpp" StronglyConnectedComponents::StronglyConnectedComponents() {} StronglyConnectedComponents::StronglyConnectedComponents(StronglyConnectedComponents& scc):levels(scc.levels) {} StronglyConnectedComponents::~StronglyConnectedComponents() {levels.clear();} /*Set the list of levels (i.e., strongly connected components in a game) **stack is the whole set of vertices in the game **return a set of all strongly connected components contained in a game*/ vector<Level*> StronglyConnectedComponents::getStronglyConnectedComponents(vector<Vertex*>& stack) { Level* temp = new Level(); while(stack.size()>0) { temp->getLevel(stack, stack[stack.size()-1]); levels.push_back(temp); temp = new Level(); } return levels; } ostream& operator<<(ostream& o, StronglyConnectedComponents const& scc){ o<<"Strongly Connected Components"<<endl; for (int i(0); i<scc.levels.size(); ++i) { o << i+1 << ": "; o << *scc.levels[i] << endl; } if (!scc.reducedMatrix.size()) return o; o<<endl<<"Reduced Matrix"<<endl; for (int i(0); i<scc.reducedMatrix.size(); ++i) { for (int k(0); k<scc.reducedMatrix.size(); ++k) o << scc.reducedMatrix[i][k]; o << endl; } return o; } /*Create the reduced matrix (i.e., the matrix containing the number of direct passages between strongly **connected components)*/ void StronglyConnectedComponents::createReducedMatrix() { vector<int> temp; int tempValue(0); for (int i(0); i<levels.size(); ++i) { temp.clear(); for (int j(0); j<levels.size(); ++j) { tempValue=0; if (j!=i) for (int k(0); k<levels[i]->getLevel().size(); ++k) for(int h(0); h<levels[j]->getLevel().size(); ++h) if (levels[i]->getLevel()[k]->isParentOf(levels[j]->getLevel()[h])) ++tempValue; temp.push_back(tempValue); } reducedMatrix.push_back(temp); } } /*Set maximal distance for each vertex on the way from startLevel to endLevel **startLevel is the index of the level where the longest path should begin **endLevel is the index of the level where the longest path should end **count is the current distance of the path (number of strongly connected components visited)*/ void StronglyConnectedComponents::createLongestPath(int startLevel, int endLevel, int count) { vector<Level*> temp; if(startLevel<reducedMatrix.size() && endLevel<reducedMatrix.size()) { if(levels[startLevel]->getDistance()!=0) { if (count==0) { levels[startLevel]->setDistance(0); levels[startLevel]->setMarked(true); if(startLevel!=endLevel) { for (int i(0); i<reducedMatrix.size(); ++i) /*If there exists a direct path between startLevel and i levels and i level is not marked as visited*/ if(reducedMatrix[startLevel][i]!=0 && !levels[i]->isMarked()) createLongestPath(i, endLevel, count+1); } } else { if(levels[startLevel]->getDistance()<count) { levels[startLevel]->setDistance(count); levels[startLevel]->setMarked(true); if(startLevel!=endLevel) { for (int i(0); i<reducedMatrix.size(); ++i) if(reducedMatrix[startLevel][i]!=0 && !levels[i]->isMarked()) createLongestPath(i, endLevel, count+1); } } } } levels[startLevel]->setMarked(false); } else cout << "Out of bounds !"; } /*Print the longest path thanks to a queue starting from endLevel index **endLevel is the end level from which we should retrieve the whole longest path to the beginning of the game*/ void StronglyConnectedComponents::printLongestPath(int endLevel) { vector<int> longestPath; int current(levels[endLevel]->getDistance()), i(0); while(current>=0) { i=0; while(i<levels.size() && current!=levels[i]->getDistance()) ++i; longestPath.insert(longestPath.begin(), i+1); --current; } cout<<"\nLongest Path from beginning to end of the game\n"; for (int i(0); i<longestPath.size(); ++i) { if (i!=longestPath.size()-1) cout << longestPath[i]<<"-->"; else cout << longestPath[i]; } cout << endl; } vector<vector<int> >& StronglyConnectedComponents::getReducedMatrix() {return reducedMatrix;} vector<Level*>& StronglyConnectedComponents::getLevels() {return levels;}
#include"ArkRcon.h" using namespace std; ArkRcon::ArkRcon() { } ArkRcon::~ArkRcon() { WSACleanup(); for (auto& i : this->_server)delete(i); } bool ArkRcon::init() { WORD sockVersion = MAKEWORD(2, 2); WSADATA data; if (WSAStartup(sockVersion, &data) != 0) { LOG("WSA init Error"); return false; } return true; } void ArkRcon::updateplayerlist() { DEBUGLOGFIN; for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); i->updatePlayerList(); } DEBUGLOGFRE; } void ArkRcon::clearRecv() { DEBUGLOGFIN; for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); i->clearRecv(); } DEBUGLOGFRE; } void ArkRcon::broadcast(const std::string& data) { DEBUGLOGFIN; for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); i->broadcast(data); } DEBUGLOGFRE; } void ArkRcon::updateGameName() { DEBUGLOGFIN; for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); i->updateGameName(); } DEBUGLOGFRE; } void ArkRcon::sendCmdAndWiatForItRecv(const std::string& data) { DEBUGLOGFIN; for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); i->sendCmdAndWiatForRecv(data); } DEBUGLOGFRE; } void ArkRcon::shutConnect() { DEBUGLOGFIN; for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); i->shutConnect(); } DEBUGLOGFRE; } void ArkRcon::reconnect() { DEBUGLOGFIN; for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); i->init(); } DEBUGLOGFRE; } void ArkRcon::kick(const std::string& steamid) { DEBUGLOGFIN; for (auto& i : this->_server) { auto players = i->getPlayers(); for (auto& j : players) { if (j.steamId == steamid) { i->sendCmdAndWiatForRecv("kickplayer " + steamid); DEBUGLOG("steamid:" + steamid + "--name:" + j.steamName + "--kicked!"); break; } } } DEBUGLOGFRE; } std::vector<std::pair<std::string, bool>>* ArkRcon::getState() { DEBUGLOGFIN auto re = new vector<pair<string, bool>>(); for (auto& i : this->_server) { DEBUGLOG("Server name:" + i->getServerName()); (*re).push_back(make_pair(i->getServerName(), i->connectedState())); } DEBUGLOGFRE; return re; } bool ArkRcon::addServer(Rcon_addr addr) { DEBUGLOGFIN; bool re = false; auto server = new ArkServer(); auto flag = server->init(addr); if (flag) { DEBUGLOG(server->getServerName() + " connected succeed"); LOG(server->getServerName() + " connect succeed!"); server->updatePlayerList(); re = true; } else { DEBUGLOG(server->getServerName()+" connected failed"); LOG(server->getServerName() + " connect failed!"); } this->_server.push_back(server); DEBUGLOGFRE; return re; }
// // BulletNode.h // Boids // // Created by Yanjie Chen on 3/13/15. // // #ifndef __Boids__BulletNode__ #define __Boids__BulletNode__ #include "cocos2d.h" #include "../data/DamageCalculate.h" #include <spine/spine-cocos2dx.h> #define DEFAULT_BULLET_SPEED 500.0 class BulletNode : public cocos2d::Node { protected: static int _global_bullet_id; cocos2d::ValueMap _bullet_data; class BattleLayer* _battle_layer; int _bullet_id; int _target_id; float _speed; class TargetNode* _source_unit; DamageCalculate* _damage_calculator; cocos2d::ValueMap _buff_data; cocos2d::Point _target_pos; cocos2d::Node* _bullet; cocos2d::MotionStreak* _streak; cocos2d::Point _init_pos; bool _is_paracurve; bool _track_target; bool _need_rotate; float _accumulator; float _duration; float _damage_radius; bool _should_recycle; bool _show_hit_effect; std::string _hit_name; std::string _hit_type; bool _show_bomb_effect; std::string _bomb_name; std::string _bomb_type; float _hit_scale; bool _will_miss; std::string _bullet_shape; protected: void shoot( int emit_pos_type = 0 ); bool doesHitTarget( const cocos2d::Point& source_pos, const cocos2d::Point& target_pos, float delta ); public: BulletNode(); virtual ~BulletNode(); static int getNextBulletId(); static BulletNode* create( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual bool init( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual void shootAt( class TargetNode* target, int emit_pos_type = 0 ); virtual void shootAtPosition( const cocos2d::Point& pos ); virtual void updateFrame( float delta ); int getBulletId() { return _bullet_id; } void setBulletId( int bullet_id ) { _bullet_id = bullet_id; } int getTargetId() { return _target_id; } void setTargetId( int target_id ) { _target_id = target_id; } void setSourceUnit( class TargetNode* source_unit ); void setDamageCalculator( DamageCalculate* calculator ); void setShouldRecycle( bool b ); bool shouldRecycle() { return _should_recycle; } float getDuration() { return _duration; } void setDuration( float duration ) { _duration = duration; } virtual void hitTarget( class TargetNode* target_unit, bool with_buff = false ); const std::string& getBulletShape() { return _bullet_shape; } void setBulletShape( const std::string& shape ) { _bullet_shape = shape; } }; class DirectionalBulletNode : public BulletNode { private: cocos2d::Point _dir; cocos2d::ValueMapIntKey _excluded_targets; public: DirectionalBulletNode(); virtual ~DirectionalBulletNode(); static DirectionalBulletNode* create( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual bool init( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); void shootAlong( const cocos2d::Point& dir, float duration ); virtual void updateFrame( float delta ); }; class DirectionalLastingBulletNode : public BulletNode { protected: cocos2d::Point _dir; cocos2d::Point _to_pos; float _last_distance_to_pos; bool _reach_to_pos; float _damage_interval; float _damage_elapse; float _lasting_damage; cocos2d::ValueMapIntKey _excluded_targets; public: DirectionalLastingBulletNode(); virtual ~DirectionalLastingBulletNode(); static DirectionalLastingBulletNode* create( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual bool init( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); void shootTo( const cocos2d::Point& from_pos, const cocos2d::Point& to_pos ); virtual void updateFrame( float delta ); }; class FixedPosBulletNode : public BulletNode { public: FixedPosBulletNode(); virtual ~FixedPosBulletNode(); static FixedPosBulletNode* create( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data); virtual bool init( class TargetNode* unit_node, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual void shootAtPosition( const cocos2d::Point& pos, int layer = 7 ); virtual void updateFrame( float delta ); void onSkeletonAnimationEvent( int track_index, spEvent* event ); void onSkeletonAnimationCompleted( int track_index ); }; class BombBulletNode : public DirectionalLastingBulletNode { public: BombBulletNode(); virtual ~BombBulletNode(); static BombBulletNode* create( class TargetNode* shooter, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual bool init( class TargetNode* shooter, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual void updateFrame( float delta ); }; class CircleBulletNode : public BulletNode { private: float _elapse; float _angle; float _radius; cocos2d::Point _center_bias; cocos2d::ValueMapIntKey _excluded_targets; public: CircleBulletNode(); virtual ~CircleBulletNode(); static CircleBulletNode* create( class TargetNode* shooter, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual bool init( class TargetNode* shooter, const cocos2d::ValueMap& bullet_data, DamageCalculate* damage_calculator, const cocos2d::ValueMap& buff_data ); virtual void updateFrame( float delta ); void shootToward( const cocos2d::Point& dir, float radius ); }; #endif /* defined(__Boids__BulletNode__) */
#ifndef BULLET_CLASS_HPP # define BULLET_CLASS_HPP #include "GameElement.class.hpp" class Bullet : public GameElement { std::string _name; public: Bullet(); Bullet(std::string name); Bullet(Bullet const & rhs); Bullet & operator=(Bullet const &); ~Bullet(); }; #endif
// // Created by user on 8/26/2021. // #include "UdpSocket.h" UdpSocket::UdpSocket(const char * const othersIp, int othersPort) { this->socketId = socket(AF_INET, SOCK_DGRAM, 0); if (this->socketId < 0) { perror("error creating socket"); } memset(&this->othersin, 0, sizeof(this->othersin)); this->othersin.sin_family = AF_INET; this->othersin.sin_addr.s_addr = inet_addr(othersIp); this->othersin.sin_port = htons(othersPort); this->send("are you ready"); } UdpSocket::UdpSocket(int myPort, const char *myIp) { this->socketId = socket(AF_INET, SOCK_DGRAM, 0); if (this->socketId < 0) { perror("error creating socket"); } struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; if (strcmp(myIp, "") != 0) { sin.sin_addr.s_addr = inet_addr(myIp); } else { sin.sin_addr.s_addr = INADDR_ANY; } sin.sin_port = htons(myPort); if (bind(this->socketId, (struct sockaddr *) &sin, sizeof(sin)) < 0){ perror("error binding to socket"); } memset(&this->othersin, 0, sizeof(this->othersin)); } void UdpSocket::send(const string &message) const { long bytesSent = sendto(socketId, message.c_str(), message.size(), 0, (struct sockaddr *) &this->othersin, sizeof(this->othersin)); if (bytesSent < 0) { perror("error sending message"); } } string UdpSocket::receive() { unsigned int fromLen = sizeof(struct sockaddr_in); char buffer[BUFFER]; long bytes = recvfrom(this->socketId, buffer, sizeof(buffer), 0, (struct sockaddr *) &this->othersin, &fromLen); if (bytes < 0) { throw runtime_error("error reading from socket"); } string str(buffer); return str; } void UdpSocket::close() { if (!this->closed) { ::close(this->socketId); this->closed = true; } } bool UdpSocket::isClosed() const { return this->closed; }
/* value.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 12 Apr 2014 FreeBSD-style copyright and disclaimer apply reflect::Value reflection implementation. */ #include "value.h" /******************************************************************************/ /* VALUE */ /******************************************************************************/ reflectTypeImpl(reflect::Value) { // \todo Reflect Value }
#ifndef SYNC_BLOCKCHAIN_H #define SYNC_BLOCKCHAIN_H #include <bitcoin/blockchain/blockchain.hpp> using namespace libbitcoin; struct transaction_index_t { size_t depth, offset; }; class sync_blockchain { public: sync_blockchain(blockchain& chain); message::block block_header(size_t depth) const; message::block block_header(size_t depth, std::error_code& ec) const; message::block block_header(const hash_digest& block_hash) const; message::block block_header(const hash_digest& block_hash, std::error_code& ec) const; message::inventory_list block_transaction_hashes( size_t depth) const; message::inventory_list block_transaction_hashes( size_t depth, std::error_code& ec) const; message::inventory_list block_transaction_hashes( const hash_digest& block_hash) const; message::inventory_list block_transaction_hashes( const hash_digest& block_hash, std::error_code& ec) const; size_t block_depth(const hash_digest& block_hash) const; size_t block_depth(const hash_digest& block_hash, std::error_code& ec) const; size_t last_depth() const; size_t last_depth(std::error_code& ec) const; message::transaction transaction( const hash_digest& transaction_hash) const; message::transaction transaction( const hash_digest& transaction_hash, std::error_code& ec) const; transaction_index_t transaction_index( const hash_digest& transaction_hash) const; transaction_index_t transaction_index( const hash_digest& transaction_hash, std::error_code& ec) const; message::input_point spend( const message::output_point& outpoint) const; message::input_point spend( const message::output_point& outpoint, std::error_code& ec) const; message::output_point_list outputs( const payment_address& address) const; message::output_point_list outputs( const payment_address& address, std::error_code& ec) const; private: blockchain& chain_; }; #endif
#include<iostream> #define OJ 98 using namespace std; int main() { #ifndef OJ freopen("201512-1.txt","r",stdin); #endif long long n; cin>>n; long res=0; while(n!=0) { res+=n%10; n/=10; } cout<<res; #ifndef OJ fclose(stdin); #endif return 0; }
/* * SPDX-FileCopyrightText: (C) 2017-2022 Matthias Fehring <mf@huessenbergnetz.de> * SPDX-License-Identifier: BSD-3-Clause */ #include "validatordate_p.h" #include <QDate> using namespace Cutelyst; ValidatorDate::ValidatorDate(const QString &field, const char *inputFormat, const Cutelyst::ValidatorMessages &messages, const QString &defValKey) : ValidatorRule(*new ValidatorDatePrivate(field, inputFormat, messages, defValKey)) { } ValidatorDate::~ValidatorDate() { } ValidatorReturnType ValidatorDate::validate(Context *c, const ParamsMultiMap &params) const { ValidatorReturnType result; Q_D(const ValidatorDate); const QString v = value(params); if (!v.isEmpty()) { const QDate date = d->extractDate(c, v, d->inputFormat); if (!date.isValid()) { result.errorMessage = validationError(c); qCDebug(C_VALIDATOR, "ValidatorDate: Validation failed for value \"%s\" in field %s in %s::%s: not a valid date.", qPrintable(v), qPrintable(field()), qPrintable(c->controllerName()), qPrintable(c->actionName())); } else { result.value.setValue(date); } } else { defaultValue(c, &result, "ValidatorDate"); } return result; } QString ValidatorDate::genericValidationError(Context *c, const QVariant &errorData) const { QString error; Q_D(const ValidatorDate); Q_UNUSED(errorData) const QString _label = label(c); if (_label.isEmpty()) { if (d->inputFormat) { //: %1 will be replaced by the date format error = c->translate("Cutelyst::ValidatorDate", "Not a valid date according to the following date format: %1").arg(c->translate(d->translationContext.data(), d->inputFormat)); } else { error = c->translate("Cutelyst::ValidatorDate", "Not a valid date."); } } else { if (d->inputFormat) { //: %1 will be replaced by the field label, %2 will be replaced by the date format error = c->translate("Cutelyst::ValidatorDate", "The value in the “%1” field can not be parsed as date according to the following scheme: %2").arg(_label, c->translate(d->translationContext.data(), d->inputFormat)); } else { //: %1 will be replaced by the field label error = c->translate("Cutelyst::ValidatorDate", "The value in the “%1” field can not be parsed as date.").arg(_label); } } return error; }
#include<cstdio> #include<queue> #include<iostream> #include<algorithm> using namespace std; struct node { int time; int num; int pri; char msg[100]; bool friend operator < (node a, node b) { if(a.pri == b.pri) return a.time > b.time; return a.pri > b.pri; } }; int main() { priority_queue<node> q; char get[5]; int k = 0; struct node no; while(~scanf("%s",get)) { if(get[0] == 'G') { if(q.empty()) { cout << "EMPTY QUEUE!" << endl; } else { no = q.top(); q.pop(); cout << no.msg << " " << no.num << endl; } } else { cin >> no.msg >> no.num >> no.pri; no.time = k++; q.push(no); } } return 0; }
#ifndef CREATEPAGEDIALOG_H #define CREATEPAGEDIALOG_H #include <QDialog> namespace Ui { class CreatePageDialog; } class CreatePageDialog : public QDialog { Q_OBJECT static int m_create_page_counter; explicit CreatePageDialog(QStringList modules, QWidget *parent = 0); ~CreatePageDialog(); public: struct PageParam { QString title; QString icon_path; QString module_tag; }; static PageParam getCreatePageParam(QStringList modules, bool &ok); private: Ui::CreatePageDialog *ui; private slots: void slotGetIconClicked(); }; #endif // CREATEPAGEDIALOG_H
#include <cstdio> #include <iostream> #include <string> using namespace std; typedef long long ll; const int maxn = 105; const int w[5][5] = { { 5, -1, -2, -1, -3 }, { -1, 5, -3, -2, -4 }, { -2, -3, 5, -2, -2 }, { -1, -2, -2, 5, -1 }, { -3, -4, -2, -1, 0 } }; int alen, blen, dp[maxn][maxn] = { 0 }; string a, b; int id(char x) { switch (x) { case 'A': return 0; case 'C': return 1; case 'G': return 2; case 'T': return 3; default: return 4; } } int score(char x, char y) { return w[id(x)][id(y)]; } int main() { // #define DEBUG #ifdef DEBUG freopen("d:\\.in", "r", stdin); freopen("d:\\.out", "w", stdout); #endif cin >> alen >> a >> blen >> b; for (int i = 1; i <= a.size(); ++i) dp[i][0] = dp[i - 1][0] + score(a[i - 1], '-'); for (int j = 1; j <= b.size(); ++j) dp[0][j] = dp[0][j - 1] + score('-', b[j - 1]); for (int i = 1; i <= a.size(); ++i) for (int j = 1; j <= b.size(); ++j) dp[i][j] = max(dp[i - 1][j - 1] + score(a[i - 1], b[j - 1]), max(dp[i - 1][j] + score(a[i - 1], '-'), dp[i][j - 1] + score('-', b[j - 1]))); cout << dp[a.size()][b.size()]; return 0; }
#include "FoundationPch.h" #include "Foundation/Math/SimdSphere.h"
#pragma once #include <fstream> #define assert(X, ...) \ do { \ if (!(X)) { \ printf("assert failed in %s:%d: ", __FILE__, __LINE__); \ printf(__VA_ARGS__); \ } \ } while (0) #define die(msg) do { puts(msg); exit(1); } while (0)
/* * Shader.cpp * * Created on: 21 сент. 2017 г. * Author: Соня */ #include "Shader.h" #include "Common.h" Shader::Shader(String vertex_filename, String fragment_filename) { if (vertex_filename.size() == 0 || fragment_filename.size() == 0) Msg::Error(L"Shader: ошибка не указан один из шейдеров"); String VertexData, FragmentData; v_file.open(vertex_filename); f_file.open(fragment_filename); StringStream vShaderStream, fShaderStream; vShaderStream << v_file.rdbuf(); fShaderStream << f_file.rdbuf(); v_file.close(); f_file.close(); VertexData = vShaderStream.str(); FragmentData = fShaderStream.str(); const char* v_VertexData = VertexData.c_str(); const char* f_FragmentData = FragmentData.c_str(); // vertex uint vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &v_VertexData, NULL); glCompileShader(vertex); // fragment uint fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &f_FragmentData, NULL); glCompileShader(fragment); program_id = glCreateProgram(); glAttachShader(program_id, vertex); glAttachShader(program_id, fragment); glBindFragDataLocation(program_id, 0, "outColor"); glLinkProgram(program_id); glUseProgram(program_id); glDeleteShader(vertex); glDeleteShader(fragment); } Shader::~Shader() { } void Shader::Bind() { }
#include <cstdio> #include <iostream> using namespace std; typedef long long ll; struct Comod { int id, cost, weight, father, cnt, son[2]; Comod() { cnt = son[0] = son[1] = 0; } }; const int maxn = 32000, maxm = 60; // n-总钱数,m-商品数 int n, m, dp[maxn] = { 0 }; Comod comod[maxm]; int main() { // #define DEBUG #ifdef DEBUG freopen("d:\\.in", "r", stdin); freopen("d:\\.out", "w", stdout); #endif cin >> n >> m; for (int i = 1; i <= m; ++i) { comod[i].id = i; cin >> comod[i].cost >> comod[i].weight >> comod[i].father; int father = comod[i].father; // 如果是附件 if (father) comod[father].son[comod[father].cnt++] = i; } for (int i = 1; i <= m; ++i) // 主件才要处理,附件跟随主件处理 if (comod[i].father == 0) for (int j = n; j >= 0; --j) for (int k = 0; k < (1 << comod[i].cnt); ++k) { // 0-主件;1-主件+附件1;2-主件+附件2;3-主件+附件1+附件2 int cost = comod[i].cost, weight = comod[i].weight * comod[i].cost; int son0 = comod[i].son[0], son1 = comod[i].son[1]; if (k & 1) { cost += comod[son0].cost; weight += comod[son0].weight * comod[son0].cost; } if (k & 2) { cost += comod[son1].cost; weight += comod[son1].weight * comod[son1].cost; } if (j >= cost) dp[j] = max(dp[j], dp[j - cost] + weight); } cout << dp[n]; return 0; }
#include <SoftwareSerial.h> #include <SPI.h> #define o1 7 #define o2 8 SoftwareSerial BTserial(5,6); // 5 for tx, 4 rx int state = 0; void setup() { // put your setup code here, to run once: BTserial.begin(38400); Serial.begin(9600); Serial.println("Hello"); SPI.begin(); pinMode(o1, OUTPUT); pinMode(o2, OUTPUT); } void loop() { // put your main code here, to run repeatedly: if(Serial.available() > 0){ // Checks whether data is comming from the serial port state = Serial.read(); // Reads the data from the serial port } if (state == '1') { digitalWrite(o1, LOW); // Turn H-bridge OFF digitalWrite(o2, LOW); Serial.println("OFF"); } else if (state == '0') { analogWrite(o1, 50); digitalWrite(o2, LOW); Serial.println("ON"); } delay(200); }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TESTDYNAMICALLYLOADEDCELLMODELS_HPP_ #define TESTDYNAMICALLYLOADEDCELLMODELS_HPP_ #include <cxxtest/TestSuite.h> #include <boost/assign.hpp> #include <boost/shared_ptr.hpp> #include "ChasteSerialization.hpp" #ifdef CHASTE_CAN_CHECKPOINT_DLLS #include "CheckpointArchiveTypes.hpp" #include "ArchiveLocationInfo.hpp" #endif // CHASTE_CAN_CHECKPOINT_DLLS #include "RunAndCheckIonicModels.hpp" #include "DynamicLoadingHelperFunctions.hpp" #include "DynamicCellModelLoader.hpp" #include "DynamicModelLoaderRegistry.hpp" #include "CellMLLoader.hpp" #include "CellMLToSharedLibraryConverter.hpp" #include "SimpleStimulus.hpp" #include "EulerIvpOdeSolver.hpp" #include "ChasteBuildRoot.hpp" #include "HeartConfig.hpp" #include "FileFinder.hpp" #include "HeartFileFinder.hpp" #include "ChasteSyscalls.hpp" #include "AbstractDynamicallyLoadableEntity.hpp" #include "AbstractCardiacCellInterface.hpp" #include "AbstractCvodeCell.hpp" #include "PetscSetupAndFinalize.hpp" class TestDynamicallyLoadedCellModels : public CxxTest::TestSuite { private: void RunLr91Test(DynamicCellModelLoader& rLoader, unsigned vIndex=4u, bool testTables=false, double tolerance=1e-3, double tableTestV=-100000) { AbstractCardiacCellInterface* p_cell = CreateLr91CellFromLoader(rLoader, vIndex); SimulateLr91AndCompare(p_cell, tolerance); if (testTables) { double v = p_cell->GetVoltage(); p_cell->SetVoltage(tableTestV); TS_ASSERT_THROWS_CONTAINS(p_cell->GetIIonic(), "membrane_voltage outside lookup table range"); p_cell->SetVoltage(v); } delete p_cell; } void SimulateLr91AndCompare(AbstractCardiacCellInterface* pCell, double tolerance=1e-3) { double end_time = 1000.0; //One second in milliseconds // Solve and write to file clock_t ck_start = clock(); // Don't use RunOdeSolverWithIonicModel() as this is hardcoded to AbstractCardiacCells OdeSolution solution1 = pCell->Compute(0.0, end_time); solution1.WriteToFile("TestIonicModels", "DynamicallyLoadableLr91", "ms", 100, false, 4); clock_t ck_end = clock(); double forward = (double)(ck_end - ck_start)/CLOCKS_PER_SEC; std::cout << "\n\tSolve time: " << forward << std::endl; // Compare with 'normal' LR91 model results CheckCellModelResults("DynamicallyLoadableLr91", "Lr91DelayedStim", tolerance); // Test GetIIonic against hardcoded result from TestIonicModels.hpp // Don't use RunOdeSolverWithIonicModel() as this is hardcoded to AbstractCardiacCells OdeSolution solution2 = pCell->Compute(0.0, 60.0); solution2.WriteToFile("TestIonicModels", "DynamicallyLoadableLr91GetIIonic", "ms", 100, false, 4); // For coverage TS_ASSERT_DELTA(pCell->GetIntracellularCalciumConcentration(), 0.0012, 1e-4); TS_ASSERT_DELTA(pCell->GetIIonic(), 1.9411, tolerance); } AbstractCardiacCellInterface* CreateLr91CellFromLoader(DynamicCellModelLoader& rLoader, unsigned vIndex=4u) { AbstractCardiacCellInterface* p_cell = CreateCellWithStandardStimulus(rLoader); TS_ASSERT_EQUALS(p_cell->GetVoltageIndex(), vIndex); return p_cell; } mode_t ResetMode(FileFinder& rFile, mode_t mode) { struct stat our_stats; int retcode = stat(rFile.GetAbsolutePath().c_str(), &our_stats); EXCEPT_IF_NOT(retcode == 0); chmod(rFile.GetAbsolutePath().c_str(), mode); return our_stats.st_mode; } std::string mArchivingDirName; FileFinder mArchivingModel; void SaveSoForArchivingTest(FileFinder& rSoFile) { mArchivingDirName = "TestDynamicallyLoadedCellModelsArchiving"; OutputFileHandler handler(mArchivingDirName); mArchivingModel = handler.CopyFileTo(rSoFile); } public: /** * This test demonstrates the easiest way to load a single cell model from CellML, * using the CellMLLoader class. */ void TestCellmlLoaderClass() { FileFinder cellml_file("heart/src/odes/cellml/LuoRudy1991.cellml", RelativeTo::ChasteSourceRoot); // Stimulus to use for simulation, so it matches other tests in this suite boost::shared_ptr<AbstractStimulusFunction> p_stimulus(new SimpleStimulus(-25.5, 2.0, 50.0)); { OutputFileHandler handler("TestCardiacCellMLLoader", true); // Note that the --cvode flag will be ignored since we call the LoadCardiacCell method. std::vector<std::string> options = boost::assign::list_of("--cvode")("--expose-annotated-variables"); CellMLLoader loader(cellml_file, handler, options); boost::shared_ptr<AbstractCardiacCell> p_cell = loader.LoadCardiacCell(); TS_ASSERT_EQUALS(p_cell->GetSystemName(), "luo_rudy_1991"); p_cell->SetStimulusFunction(p_stimulus); SimulateLr91AndCompare(p_cell.get()); // Are sources from the conversion preserved? FileFinder cpp_file(handler.GetRelativePath() + "/LuoRudy1991.cpp", RelativeTo::ChasteTestOutput); TS_ASSERT(cpp_file.Exists()); TS_ASSERT(cpp_file.IsNewerThan(cellml_file)); FileFinder hpp_file(handler.GetRelativePath() + "/LuoRudy1991.hpp", RelativeTo::ChasteTestOutput); TS_ASSERT(hpp_file.Exists()); TS_ASSERT(hpp_file.IsNewerThan(cellml_file)); // We can't now call LoadCvodeCell on this loader #ifdef CHASTE_CVODE TS_ASSERT_THROWS_THIS(loader.LoadCvodeCell(), "You cannot call both LoadCvodeCell and LoadCardiacCell on the same CellMLLoader."); #endif } #ifdef CHASTE_CVODE { OutputFileHandler handler("TestCvodeCellMLLoader", true); std::vector<std::string> options = boost::assign::list_of("--expose-annotated-variables"); CellMLLoader loader(cellml_file, handler, options); boost::shared_ptr<AbstractCvodeCell> p_cell = loader.LoadCvodeCell(); TS_ASSERT_EQUALS(p_cell->GetSystemName(), "luo_rudy_1991"); p_cell->SetStimulusFunction(p_stimulus); SimulateLr91AndCompare(p_cell.get(), 1.0); // Large tolerance due to different ODE solver // We can't now call LoadCardiacCell on this loader TS_ASSERT_THROWS_THIS(loader.LoadCardiacCell(), "You cannot call both LoadCvodeCell and LoadCardiacCell on the same CellMLLoader."); } #endif } /** * This is based on TestOdeSolverForLR91WithDelayedSimpleStimulus from * TestIonicModels.hpp. */ void TestDynamicallyLoadedLr91() { // Load the cell model dynamically std::string model_name = "libDynamicallyLoadableLr91."; model_name += CellMLToSharedLibraryConverter::msSoSuffix; // All tests use the registry, as not doing so can lead to segfaults... DynamicCellModelLoaderPtr p_loader = DynamicModelLoaderRegistry::Instance()->GetLoader( ChasteComponentBuildDir("heart") + "dynamic/" + model_name); RunLr91Test(*p_loader); // The .so also gets copied into the source folder DynamicCellModelLoaderPtr p_loader2 = DynamicModelLoaderRegistry::Instance()->GetLoader( std::string(ChasteBuildRootDir()) + "heart/dynamic/" + model_name); RunLr91Test(*p_loader2); } void TestExceptions() { // Try loading a .so that doesn't exist std::string file_name = "non-existent-file-we-hope"; TS_ASSERT_THROWS_CONTAINS(DynamicCellModelLoader::Create(file_name), "Unable to load .so file '" + file_name + "':"); // Try loading a .so that doesn't define a cell model file_name = "libNotACellModel."; file_name += CellMLToSharedLibraryConverter::msSoSuffix; TS_ASSERT_THROWS_CONTAINS(DynamicCellModelLoader::Create(ChasteComponentBuildDir("heart") + "dynamic/" + file_name), "Failed to load cell creation function from .so file"); } void TestCellmlConverter() { // Copy CellML file into output dir std::string dirname = "TestCellmlConverter"; OutputFileHandler handler(dirname); FileFinder cellml_file_src("heart/dynamic/luo_rudy_1991_dyn.cellml", RelativeTo::ChasteSourceRoot); CellMLToSharedLibraryConverter converter(true); // Convert a real CellML file FileFinder cellml_file = handler.CopyFileTo(cellml_file_src); TS_ASSERT(cellml_file.Exists()); FileFinder so_file(dirname + "/libluo_rudy_1991_dyn."+CellMLToSharedLibraryConverter::msSoSuffix, RelativeTo::ChasteTestOutput); TS_ASSERT(!so_file.Exists()); DynamicCellModelLoaderPtr p_loader = converter.Convert(cellml_file); SaveSoForArchivingTest(so_file); TS_ASSERT(so_file.Exists()); TS_ASSERT(so_file.IsNewerThan(cellml_file)); // Converting a .so should be a "no-op" DynamicCellModelLoaderPtr p_loader2 = converter.Convert(so_file); TS_ASSERT(so_file.Exists()); TS_ASSERT(p_loader2 == p_loader); RunLr91Test(*p_loader, 0u); // Cover exceptions std::string file_name = "test.no.file"; FileFinder no_exist(dirname + "/" + file_name, RelativeTo::ChasteTestOutput); TS_ASSERT_THROWS_THIS(converter.Convert(no_exist), "Dynamically loadable cell model '" + no_exist.GetAbsolutePath() + "' does not exist."); file_name = "test"; FileFinder no_ext(dirname + "/" + file_name, RelativeTo::ChasteTestOutput); PetscTools::Barrier("TestCellmlConverter_pre_touch"); if (PetscTools::AmMaster()) { out_stream fp = handler.OpenOutputFile(file_name); fp->close(); } PetscTools::Barrier("TestCellmlConverter_post_touch"); TS_ASSERT_THROWS_THIS(converter.Convert(no_ext), "File does not have an extension: " + no_ext.GetAbsolutePath()); FileFinder unsupp_ext("global/src/FileFinder.hpp", RelativeTo::ChasteSourceRoot); TS_ASSERT_THROWS_THIS(converter.Convert(unsupp_ext), "Unsupported extension '.hpp' of file '" + unsupp_ext.GetAbsolutePath() + "'; must be .so, .dylib or .cellml"); TRY_IF_MASTER( so_file.Remove() ); TS_ASSERT_THROWS_THIS(converter.Convert(cellml_file, false), "Unable to convert .cellml to .so unless called collectively, due to possible race conditions."); // This one is tricky! mode_t old_mode = ResetMode(cellml_file, 0); TS_ASSERT_THROWS_CONTAINS(converter.Convert(cellml_file), "Conversion of CellML to Chaste shared object failed."); ResetMode(cellml_file, old_mode); // What if the Chaste build tree is missing? FileFinder::FakePath(RelativeTo::ChasteBuildRoot, "/tmp/not-a-chaste-source-tree"); TS_ASSERT_THROWS_THIS(converter.Convert(cellml_file), "No Chaste build tree found at '/tmp/not-a-chaste-source-tree' - you need the source to use CellML models directly in Chaste."); FileFinder::StopFaking(); // Or a required project is missing? { FileFinder build_root("", RelativeTo::ChasteBuildRoot); CellMLToSharedLibraryConverter failed_converter(true, "not_a_project"); TS_ASSERT_THROWS_CONTAINS(failed_converter.Convert(cellml_file), "Unable to convert CellML model: required Chaste component 'not_a_project' does not exist in '" + build_root.GetAbsolutePath() + "'."); } // Or we can't create the temp folder for some other reason? { OutputFileHandler fake_chaste_tree("FakeChaste/heart"); FileFinder::FakePath(RelativeTo::ChasteBuildRoot, fake_chaste_tree.GetChasteTestOutputDirectory() + "FakeChaste"); TS_ASSERT_THROWS_CONTAINS(converter.Convert(cellml_file), "Failed to create temporary folder '"); FileFinder::StopFaking(); } } void TestCellmlConverterWithOptions() { // Copy CellML file into output dir std::string dirname = "TestCellmlConverterWithOptions"; std::string model = "LuoRudy1991"; OutputFileHandler handler(dirname + "/plain"); FileFinder cellml_file("heart/src/odes/cellml/" + model + ".cellml", RelativeTo::ChasteSourceRoot); FileFinder copied_file = handler.CopyFileTo(cellml_file); // Do the conversions preserving generated sources CellMLToSharedLibraryConverter converter(true); // Create options file & convert std::vector<std::string> args; args.push_back("--opt"); converter.SetOptions(args); // Ensure that conversion works if CWD != ChasteSourceRoot EXPECT0(chdir, "heart"); DynamicCellModelLoaderPtr p_loader = converter.Convert(copied_file); EXPECT0(chdir, ".."); RunLr91Test(*p_loader, 0u, true, 0.01); // Implementation of lookup tables has improved... // Check the sources exist TS_ASSERT(handler.FindFile(model + ".cpp").Exists()); TS_ASSERT(handler.FindFile(model + ".hpp").Exists()); { // Backward Euler args.push_back("--backward-euler"); OutputFileHandler handler2(dirname + "/BE"); FileFinder copied_file2 = handler2.CopyFileTo(cellml_file); converter.SetOptions(args); p_loader = converter.Convert(copied_file2); RunLr91Test(*p_loader, 0u, true, 0.3); } #ifdef CHASTE_CVODE { // With a for_model section and Cvode args[1] = "--cvode"; OutputFileHandler handler3(dirname + "/CO"); FileFinder copied_file3 = handler3.CopyFileTo(cellml_file); converter.SetOptions(args); p_loader = converter.Convert(copied_file3); RunLr91Test(*p_loader, 0u, true, 1, 560.0); // Large tolerance due to different ODE solver } #endif } // // void TestArchiving() // { //#ifdef CHASTE_CAN_CHECKPOINT_DLLS // // // Get a loader for the .so and load a cell model // CellMLToSharedLibraryConverter converter; // DynamicCellModelLoaderPtr p_loader = converter.Convert(mArchivingModel); // AbstractCardiacCellInterface* p_cell = CreateLr91CellFromLoader(*p_loader, 0u); // // // Archive it // OutputFileHandler handler(mArchivingDirName, false); // handler.SetArchiveDirectory(); // std::string archive_filename1 = ArchiveLocationInfo::GetProcessUniqueFilePath("first-save.arch"); // { // AbstractCardiacCellInterface* const p_const_cell = p_cell; // std::ofstream ofs(archive_filename1.c_str()); // boost::archive::text_oarchive output_arch(ofs); // ///\todo #2417 this archiving throws exception on Mac OSX // try // { // output_arch << p_const_cell; // } // catch(boost::archive::archive_exception& boost_exception) // { // TS_ASSERT_EQUALS(boost_exception.code, boost::archive::archive_exception::unregistered_class); // TS_FAIL("Archiving cell models in unavailable. Please refer to #2417"); // //Bail out // return; // } // } // // // Load from archive // AbstractCardiacCellInterface* p_loaded_cell1; // { // std::ifstream ifs(archive_filename1.c_str(), std::ios::binary); // boost::archive::text_iarchive input_arch(ifs); // input_arch >> p_loaded_cell1; // } // // // Archive the un-archived model // std::string archive_filename2 = ArchiveLocationInfo::GetProcessUniqueFilePath("second-save.arch"); // { // AbstractCardiacCellInterface* const p_const_cell = p_loaded_cell1; // std::ofstream ofs(archive_filename2.c_str()); // boost::archive::text_oarchive output_arch(ofs); // output_arch << p_const_cell; // } // // // Load from the new archive // AbstractCardiacCellInterface* p_loaded_cell2; // { // std::ifstream ifs(archive_filename2.c_str(), std::ios::binary); // boost::archive::text_iarchive input_arch(ifs); // input_arch >> p_loaded_cell2; // } // // // Check simulations of both loaded cells // SimulateLr91AndCompare(p_loaded_cell1); // delete p_loaded_cell1; // SimulateLr91AndCompare(p_loaded_cell2); // delete p_loaded_cell2; // delete p_cell; //#else // std::cout << "Note: this test can only actually test anything on Boost>=1.37 (on non-Mac systems #2417)." << std::endl; //#endif // CHASTE_CAN_CHECKPOINT_DLLS // } }; #endif /* TESTDYNAMICALLYLOADEDCELLMODELS_HPP_ */
#include "ObjLoader.h" ObjLoader::ObjLoader(string filename) { std::ifstream file(filename); std::string line; while (getline(file, line)) { if (line[0] == 'v') { Vertex Point; std::istringstream s(line.substr(2)); s >> Point.Position.x >> Point.Position.y >> Point.Position.z; vSets.push_back(Point); } else if (line[0] == 'f') { Index vIndex; std::istringstream vtns(line.substr(2)); vtns >> vIndex.i1 >> vIndex.i2 >> vIndex.i3; vIndex.i1 -= 1; vIndex.i2 -= 1; vIndex.i3 -= 1; fSets.push_back(vIndex); } } for (int i = 0; i < vSets.size(); ++i) { vSets[i].Normal = glm::vec3(0, 0, 0); } for (int i = 0; i < fSets.size(); ++i) { glm::vec3 v1(vSets[fSets[i].i2].Position - vSets[fSets[i].i1].Position); glm::vec3 v2(vSets[fSets[i].i3].Position - vSets[fSets[i].i1].Position); glm::vec3 normal = glm::normalize(glm::cross(v1, v2)); vSets[fSets[i].i1].Normal += normal; vSets[fSets[i].i2].Normal += normal; vSets[fSets[i].i3].Normal += normal; } for (int i = 0; i < vSets.size(); ++i) { vSets[i].Normal = glm::normalize(vSets[i].Normal); } file.close(); setupMesh(); } void ObjLoader::Draw() { glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, fSets.size() * 3, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void ObjLoader::setupMesh() { // create buffers/arrays glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); // load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, VBO); // A great thing about structs is that their memory layout is sequential for all its items. // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which // again translates to 3/2 floats which translates to a byte array. glBufferData(GL_ARRAY_BUFFER, vSets.size() * sizeof(Vertex), &vSets[0], GL_STATIC_DRAW); // set the vertex attribute pointers // vertex Positions glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, fSets.size() * sizeof(Index), &fSets[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); }
/* * UAE - The Un*x Amiga Emulator * * Win32 DirectInput/Windows XP RAWINPUT interface * * Copyright 2002 - 2011 Toni Wilen */ int rawinput_enabled_hid = -1; int xinput_enabled = 0; // 1 = keyboard // 2 = mouse // 4 = joystick int rawinput_log = 0; int tablet_log = 0; int no_rawinput = 0; int no_directinput = 0; int no_windowsmouse = 0; int winekeyboard = 0; int key_swap_hack = 0; #define _WIN32_WINNT 0x501 /* enable RAWINPUT support */ #define RAWINPUT_DEBUG 0 #define DI_DEBUG 1 #define IGNOREEVERYTHING 0 #define DEBUG_SCANCODE 0 #define OUTPUTDEBUG 0 #define NEGATIVEMINHACK 0 #include "sysconfig.h" #include <stdlib.h> #include <stdarg.h> #include <signal.h> #include <windows.h> #include <dinput.h> #include "sysdeps.h" #include "options.h" #include "traps.h" #include "rp.h" #include "inputdevice.h" #include "keybuf.h" #include "xwin.h" #include "uae.h" #include "catweasel.h" #include "keyboard.h" #include "custom.h" #include "render.h" #include "akiko.h" #include "clipboard.h" #include "tabletlibrary.h" #include "gui.h" #include <winioctl.h> #include <ntddkbd.h> #include <ntddpar.h> #include <setupapi.h> #include <devguid.h> #include <cfgmgr32.h> #include <wbemidl.h> #include <oleauto.h> extern "C" { #include <hidsdi.h> } #include <wintab.h> #include "wintablet.h" #include "win32.h" #define MAX_MAPPINGS 256 #define DID_MOUSE 1 #define DID_JOYSTICK 2 #define DID_KEYBOARD 3 #define DIDC_NONE 0 #define DIDC_DX 1 #define DIDC_RAW 2 #define DIDC_WIN 3 #define DIDC_CAT 4 #define DIDC_PARJOY 5 #define DIDC_XINPUT 6 #define AXISTYPE_NORMAL 0 #define AXISTYPE_POV_X 1 #define AXISTYPE_POV_Y 2 #define AXISTYPE_SLIDER 3 #define AXISTYPE_DIAL 4 #define MAX_ACQUIRE_ATTEMPTS 10 struct didata { int type; int acquired; int priority; int superdevice; GUID iguid; GUID pguid; TCHAR *name; bool fullname; TCHAR *sortname; TCHAR *configname; int vid, pid, mi; int connection; int acquireattempts; LPDIRECTINPUTDEVICE8 lpdi; HANDLE rawinput, rawhidhandle; HIDP_CAPS hidcaps; HIDP_VALUE_CAPS hidvcaps[MAX_MAPPINGS]; PCHAR hidbuffer, hidbufferprev; PHIDP_PREPARSED_DATA hidpreparseddata; int maxusagelistlength; PUSAGE_AND_PAGE usagelist, prevusagelist; int wininput; int catweasel; int coop; int xinput; HANDLE parjoy; PAR_QUERY_INFORMATION oldparjoystatus; uae_s16 axles; uae_s16 buttons, buttons_real; uae_s16 axismappings[MAX_MAPPINGS]; TCHAR *axisname[MAX_MAPPINGS]; uae_s16 axissort[MAX_MAPPINGS]; uae_s16 axistype[MAX_MAPPINGS]; bool analogstick; uae_s16 buttonmappings[MAX_MAPPINGS]; TCHAR *buttonname[MAX_MAPPINGS]; uae_s16 buttonsort[MAX_MAPPINGS]; uae_s16 buttonaxisparent[MAX_MAPPINGS]; uae_s16 buttonaxisparentdir[MAX_MAPPINGS]; uae_s16 buttonaxistype[MAX_MAPPINGS]; }; #define MAX_PARJOYPORTS 2 #define DI_BUFFER 30 #define DI_KBBUFFER 50 static LPDIRECTINPUT8 g_lpdi; static struct didata di_mouse[MAX_INPUT_DEVICES]; static struct didata di_keyboard[MAX_INPUT_DEVICES]; static struct didata di_joystick[MAX_INPUT_DEVICES]; #define MAX_RAW_HANDLES 500 static int raw_handles; static HANDLE rawinputhandles[MAX_RAW_HANDLES]; static int num_mouse, num_keyboard, num_joystick; static int dd_inited, mouse_inited, keyboard_inited, joystick_inited; static int stopoutput; static HANDLE kbhandle = INVALID_HANDLE_VALUE; static int originalleds, oldleds, newleds, disabledleds, ledstate; static int normalmouse, supermouse, rawmouse, winmouse, winmousenumber, lightpen, lightpennumber, winmousewheelbuttonstart; static int normalkb, superkb, rawkb; static bool rawinput_enabled_mouse, rawinput_enabled_keyboard; static bool rawinput_decided; static bool rawhid_found; static int rawinput_enabled_hid_reset; static uae_s16 axisold[MAX_INPUT_DEVICES][256], buttonold[MAX_INPUT_DEVICES][256]; static int dinput_enum_all; int dinput_winmouse (void) { if (winmouse) return winmousenumber; return -1; } int dinput_wheelbuttonstart (void) { return winmousewheelbuttonstart; } int dinput_lightpen (void) { if (lightpen) return lightpennumber; return -1; } #if 0 static LRESULT CALLBACK LowLevelKeyboardProc (int nCode, WPARAM wParam, LPARAM lParam) { write_log (_T("*")); if (nCode >= 0) { KBDLLHOOKSTRUCT *k = (KBDLLHOOKSTRUCT*)lParam; int vk = k->vkCode; int sc = k->scanCode; write_log (_T("%02x %02x\n"), vk, sc); } return CallNextHookEx (NULL, nCode, wParam, lParam); } static HHOOK kbhook; static void lock_kb (void) { if (kbhook) return; kbhook = SetWindowsHookEx (WH_KEYBOARD_LL, LowLevelKeyboardProc, hInst, 0); if (!kbhook) write_log (_T("SetWindowsHookEx %d\n"), GetLastError ()); else write_log (_T("***************************\n")); } static void unlock_kb (void) { if (!kbhook) return; write_log (_T("!!!!!!!!!!!!!!!!!!!!!!!!\n")); UnhookWindowsHookEx (kbhook); kbhook = NULL; } #endif static BYTE ledkeystate[256]; static uae_u32 get_leds (void) { uae_u32 led = 0; GetKeyboardState (ledkeystate); if (ledkeystate[VK_NUMLOCK] & 1) led |= KBLED_NUMLOCKM; if (ledkeystate[VK_CAPITAL] & 1) led |= KBLED_CAPSLOCKM; if (ledkeystate[VK_SCROLL] & 1) led |= KBLED_SCROLLLOCKM; if (currprefs.win32_kbledmode) { oldleds = led; } else if (!currprefs.win32_kbledmode && kbhandle != INVALID_HANDLE_VALUE) { KEYBOARD_INDICATOR_PARAMETERS InputBuffer; KEYBOARD_INDICATOR_PARAMETERS OutputBuffer; ULONG DataLength = sizeof(KEYBOARD_INDICATOR_PARAMETERS); ULONG ReturnedLength; memset (&InputBuffer, 0, sizeof (InputBuffer)); memset (&OutputBuffer, 0, sizeof (OutputBuffer)); if (!DeviceIoControl (kbhandle, IOCTL_KEYBOARD_QUERY_INDICATORS, &InputBuffer, DataLength, &OutputBuffer, DataLength, &ReturnedLength, NULL)) return 0; led = 0; if (OutputBuffer.LedFlags & KEYBOARD_NUM_LOCK_ON) led |= KBLED_NUMLOCKM; if (OutputBuffer.LedFlags & KEYBOARD_CAPS_LOCK_ON) led |= KBLED_CAPSLOCKM; if (OutputBuffer.LedFlags & KEYBOARD_SCROLL_LOCK_ON) led |= KBLED_SCROLLLOCKM; } return led; } static void kbevt (uae_u8 vk, uae_u8 sc) { keybd_event (vk, 0, 0, 0); keybd_event (vk, 0, KEYEVENTF_KEYUP, 0); } static void set_leds (uae_u32 led) { //write_log (_T("setleds %08x\n"), led); if (currprefs.win32_kbledmode) { if ((oldleds & KBLED_NUMLOCKM) != (led & KBLED_NUMLOCKM) && !(disabledleds & KBLED_NUMLOCKM)) { kbevt (VK_NUMLOCK, 0x45); oldleds ^= KBLED_NUMLOCKM; } if ((oldleds & KBLED_CAPSLOCKM) != (led & KBLED_CAPSLOCKM) && !(disabledleds & KBLED_CAPSLOCKM)) { kbevt (VK_CAPITAL, 0x3a); oldleds ^= KBLED_CAPSLOCKM; } if ((oldleds & KBLED_SCROLLLOCKM) != (led & KBLED_SCROLLLOCKM) && !(disabledleds & KBLED_SCROLLLOCKM)) { kbevt (VK_SCROLL, 0x46); oldleds ^= KBLED_SCROLLLOCKM; } } else if (kbhandle != INVALID_HANDLE_VALUE) { KEYBOARD_INDICATOR_PARAMETERS InputBuffer; ULONG DataLength = sizeof(KEYBOARD_INDICATOR_PARAMETERS); ULONG ReturnedLength; memset (&InputBuffer, 0, sizeof (InputBuffer)); oldleds = 0; if (led & KBLED_NUMLOCKM) { InputBuffer.LedFlags |= KEYBOARD_NUM_LOCK_ON; oldleds |= KBLED_NUMLOCKM; } if (led & KBLED_CAPSLOCKM) { InputBuffer.LedFlags |= KEYBOARD_CAPS_LOCK_ON; oldleds |= KBLED_CAPSLOCKM; } if (led & KBLED_SCROLLLOCKM) { InputBuffer.LedFlags |= KEYBOARD_SCROLL_LOCK_ON; oldleds |= KBLED_SCROLLLOCKM; } if (!DeviceIoControl (kbhandle, IOCTL_KEYBOARD_SET_INDICATORS, &InputBuffer, DataLength, NULL, 0, &ReturnedLength, NULL)) write_log (_T("kbleds: DeviceIoControl() failed %d\n"), GetLastError()); } } static void update_leds (void) { if (!currprefs.keyboard_leds_in_use) return; if (newleds != oldleds) set_leds (newleds); } void indicator_leds (int num, int state) { if (state == 0) ledstate &= ~(1 << num); else if (state > 0) ledstate |= 1 << num; disabledleds = 0; for (int i = 0; i < 3; i++) { if (state >= 0) { int l = currprefs.keyboard_leds[i]; if (l <= 0) { disabledleds |= 1 << i; } else { newleds &= ~(1 << i); if (l - 1 > LED_CD) { // all floppies if (ledstate & ((1 << LED_DF0) | (1 << LED_DF1) | (1 << LED_DF2) | (1 << LED_DF3))) newleds |= 1 << i; } else { if ((1 << (l - 1)) & ledstate) newleds |= 1 << i; } } } } } static int isrealbutton (struct didata *did, int num) { if (num >= did->buttons) return 0; if (did->buttonaxisparent[num] >= 0) return 0; return 1; } static void fixbuttons (struct didata *did) { if (did->buttons > 0) return; write_log (_T("'%s' has no buttons, adding single default button\n"), did->name); did->buttonmappings[0] = DIJOFS_BUTTON (0); did->buttonsort[0] = 0; did->buttonname[0] = my_strdup (_T("Button")); did->buttons++; } static void addplusminus (struct didata *did, int i) { TCHAR tmp[256]; int j; if (did->buttons + 1 >= ID_BUTTON_TOTAL) return; for (j = 0; j < 2; j++) { _stprintf (tmp, _T("%s [%c]"), did->axisname[i], j ? '+' : '-'); did->buttonname[did->buttons] = my_strdup (tmp); did->buttonmappings[did->buttons] = did->axismappings[i]; did->buttonsort[did->buttons] = 1000 + (did->axismappings[i] + did->axistype[i]) * 2 + j; did->buttonaxisparent[did->buttons] = i; did->buttonaxisparentdir[did->buttons] = j; did->buttonaxistype[did->buttons] = did->axistype[i]; did->buttons++; } } static void fixthings (struct didata *did) { int i; did->buttons_real = did->buttons; for (i = 0; i < did->axles; i++) addplusminus (did, i); } static void fixthings_mouse (struct didata *did) { int i; if (did == NULL) return; did->buttons_real = did->buttons; for (i = 0; i < did->axles; i++) { if (did->axissort[i] == -97) addplusminus (did, i); } } static int rawinput_available; static bool rawinput_registered; static int rawinput_reg; static int doregister_rawinput (bool add) { struct AmigaMonitor *mon = &AMonitors[0]; int num; RAWINPUTDEVICE rid[2 + 2 + MAX_INPUT_DEVICES] = { 0 }; if (!rawinput_available) return 0; rawinput_registered = add; memset (rid, 0, sizeof rid); num = 0; /* mouse */ rid[num].usUsagePage = 1; rid[num].usUsage = 2; if (!add) { rid[num].dwFlags = RIDEV_REMOVE; } else { if (mon->hMainWnd) { rid[num].dwFlags = RIDEV_INPUTSINK; rid[num].hwndTarget = mon->hMainWnd; } rid[num].dwFlags |= RIDEV_DEVNOTIFY; } num++; /* keyboard */ if (!rp_isactive()) { rid[num].usUsagePage = 1; rid[num].usUsage = 6; if (!add) { rid[num].dwFlags = RIDEV_REMOVE; } else { if (mon->hMainWnd) { rid[num].dwFlags = RIDEV_INPUTSINK; rid[num].hwndTarget = mon->hMainWnd; } rid[num].dwFlags |= RIDEV_NOHOTKEYS | RIDEV_DEVNOTIFY; } num++; /* joystick */ int off = num; // game pad rid[num].usUsagePage = 1; rid[num].usUsage = 4; if (!add) { rid[num].dwFlags = RIDEV_REMOVE; } else { if (mon->hMainWnd) { rid[num].dwFlags = RIDEV_INPUTSINK; rid[num].hwndTarget = mon->hMainWnd; } rid[num].dwFlags |= RIDEV_DEVNOTIFY; } num++; // joystick rid[num].usUsagePage = 1; rid[num].usUsage = 5; if (!add) { rid[num].dwFlags = RIDEV_REMOVE; } else { if (mon->hMainWnd) { rid[num].dwFlags = RIDEV_INPUTSINK; rid[num].hwndTarget = mon->hMainWnd; } rid[num].dwFlags |= RIDEV_DEVNOTIFY; } num++; } #if 0 for (int i = 0; i < num_joystick; i++) { struct didata *did = &di_joystick[i]; if (did->connection != DIDC_RAW) continue; int j; for (j = off; j < num; j++) { if (rid[j].usUsagePage == 1 && (rid[j].usUsage == 4 || rid[j].usUsage == 5)) break; if (rid[j].usUsage == did->hidcaps.Usage && rid[j].usUsagePage == did->hidcaps.UsagePage) break; } if (j == num) { rid[num].usUsagePage = did->hidcaps.UsagePage; rid[num].usUsage = did->hidcaps.Usage; if (!add) { rid[num].dwFlags = RIDEV_REMOVE; } else { if (hMainWnd) { rid[num].dwFlags = RIDEV_INPUTSINK; rid[num].hwndTarget = hMainWnd; } rid[num].dwFlags |= (os_vista ? RIDEV_DEVNOTIFY : 0); } #if RAWINPUT_DEBUG write_log(_T("RAWHID ADD=%d NUM=%d %04x/%04x\n"), add, num, did->hidcaps.Usage, did->hidcaps.UsagePage); #endif num++; } } #endif #if RAWINPUT_DEBUG write_log (_T("RegisterRawInputDevices: NUM=%d HWND=%p\n"), num, hMainWnd); #endif rawinput_reg = num; if (RegisterRawInputDevices (rid, num, sizeof(RAWINPUTDEVICE)) == FALSE) { write_log (_T("RAWINPUT %sregistration failed %d\n"), add ? _T("") : _T("un"), GetLastError ()); return 0; } return 1; } void rawinput_alloc(void) { doregister_rawinput(true); } void rawinput_release(void) { } static void cleardid (struct didata *did) { memset (did, 0, sizeof (*did)); for (int i = 0; i < MAX_MAPPINGS; i++) { did->axismappings[i] = -1; did->buttonmappings[i] = -1; did->buttonaxisparent[i] = -1; } did->parjoy = INVALID_HANDLE_VALUE; did->rawhidhandle = INVALID_HANDLE_VALUE; } #define MAX_KEYCODES 256 static uae_u8 di_keycodes[MAX_INPUT_DEVICES][MAX_KEYCODES]; static int keyboard_german; static int keyhack (int scancode, int pressed, int num) { static byte backslashstate, apostrophstate; //check ALT-F4 if (pressed && !(di_keycodes[num][DIK_F4] & 1) && scancode == DIK_F4) { if ((di_keycodes[num][DIK_LALT] & 1) && !currprefs.win32_ctrl_F11_is_quit) { #ifdef RETROPLATFORM if (rp_close ()) return -1; #endif if (!quit_ok()) return -1; uae_quit (); return -1; } } #ifdef SINGLEFILE if (pressed && scancode == DIK_ESCAPE) { uae_quit (); return -1; } #endif // release mouse if TAB and ALT is pressed if (pressed && (di_keycodes[num][DIK_LALT] & 1) && scancode == DIK_TAB) { disablecapture (); return -1; } #if 0 if (!keyboard_german) return scancode; //This code look so ugly because there is no Directinput //key for # (called numbersign on win standard message) //available //so here need to change qulifier state and restore it when key //is release if (scancode == DIK_BACKSLASH) // The # key { if ((di_keycodes[num][DIK_LSHIFT] & 1) || (di_keycodes[num][DIK_RSHIFT] & 1) || apostrophstate) { if (pressed) { apostrophstate=1; inputdevice_translatekeycode (num, DIK_RSHIFT, 0, false); inputdevice_translatekeycode (num, DIK_LSHIFT, 0, false); return 13; // the german ' key } else { //best is add a real keystatecheck here but it still work so apostrophstate = 0; inputdevice_translatekeycode (num, DIK_LALT, 0, true); inputdevice_translatekeycode (num, DIK_LSHIFT, 0, true); inputdevice_translatekeycode (num, 4, 0, true); // release also the # key return 13; } } if (pressed) { inputdevice_translatekeycode (num, DIK_LALT, 1, false); inputdevice_translatekeycode (num, DIK_LSHIFT, 1, false); return 4; // the german # key } else { inputdevice_translatekeycode (num, DIK_LALT, 0, true); inputdevice_translatekeycode (num, DIK_LSHIFT, 0, true); // Here is the same not nice but do the job return 4; // the german # key } } if (((di_keycodes[num][DIK_RALT] & 1)) || (backslashstate)) { switch (scancode) { case 12: if (pressed) { backslashstate=1; inputdevice_translatekeycode (num, DIK_RALT, 0, true); return DIK_BACKSLASH; } else { backslashstate=0; return DIK_BACKSLASH; } } } #endif return scancode; } static HMODULE wintab; typedef UINT(API* WTINFOW)(UINT, UINT, LPVOID); static WTINFOW pWTInfoW; typedef BOOL(API* WTCLOSE)(HCTX); static WTCLOSE pWTClose; typedef HCTX(API* WTOPENW)(HWND, LPLOGCONTEXTW, BOOL); static WTOPENW pWTOpenW; typedef BOOL(API* WTPACKET)(HCTX, UINT, LPVOID); WTPACKET pWTPacket; static int tablet; static int axmax, aymax, azmax; static int xmax, ymax, zmax; static int xres, yres; static int maxpres; static TCHAR *tabletname; static int tablet_x, tablet_y, tablet_z, tablet_pressure, tablet_buttons, tablet_proximity; static int tablet_ax, tablet_ay, tablet_az, tablet_flags; static int tablet_div; static void tablet_send (void) { static int eraser; if ((tablet_flags & TPS_INVERT) && tablet_pressure > 0) { tablet_buttons |= 2; eraser = 1; } else if (eraser) { tablet_buttons &= ~2; eraser = 0; } if (tablet_x < 0) return; inputdevice_tablet (tablet_x, tablet_y, tablet_z, tablet_pressure, tablet_buttons, tablet_proximity, tablet_ax, tablet_ay, tablet_az, dinput_lightpen()); tabletlib_tablet (tablet_x, tablet_y, tablet_z, tablet_pressure, maxpres, tablet_buttons, tablet_proximity, tablet_ax, tablet_ay, tablet_az); } void send_tablet_proximity (int inproxi) { if (tablet_proximity == inproxi) return; tablet_proximity = inproxi; if (!tablet_proximity) { tablet_flags &= ~TPS_INVERT; } if (tablet_log & 4) write_log (_T("TABLET: Proximity=%d\n"), inproxi); tablet_send (); } void send_tablet (int x, int y, int z, int pres, uae_u32 buttons, int flags, int ax, int ay, int az, int rx, int ry, int rz, RECT *r) { if (tablet_log & 4) write_log (_T("TABLET: B=%08X F=%08X X=%d Y=%d P=%d (%d,%d,%d)\n"), buttons, flags, x, y, pres, ax, ay, az); if (axmax > 0) ax = ax * 255 / axmax; else ax = 0; if (aymax > 0) ay = ay * 255 / aymax; else ay = 0; if (azmax > 0) az = az * 255 / azmax; else az = 0; pres = pres * 255 / maxpres; tablet_x = (x + tablet_div / 2) / tablet_div; tablet_y = ymax - (y + tablet_div / 2) / tablet_div; tablet_z = z; tablet_pressure = pres; tablet_buttons = buttons; tablet_ax = abs (ax); tablet_ay = abs (ay); tablet_az = abs (az); tablet_flags = flags; tablet_send (); } static int gettabletres (AXIS *a) { FIX32 r = a->axResolution; switch (a->axUnits) { case TU_INCHES: return r >> 16; case TU_CENTIMETERS: return (int)(((r / 65536.0) / 2.54) + 0.5); default: return -1; } } void *open_tablet (HWND hwnd) { static int initialized; LOGCONTEXT lc = { 0 }; AXIS tx = { 0 }, ty = { 0 }, tz = { 0 }; AXIS pres = { 0 }; int xm, ym, zm; if (!tablet) return 0; if (inputdevice_is_tablet () <= 0 && !is_touch_lightpen()) return 0; xmax = -1; ymax = -1; zmax = -1; pWTInfoW (WTI_DEFCONTEXT, 0, &lc); pWTInfoW (WTI_DEVICES, DVC_X, &tx); pWTInfoW (WTI_DEVICES, DVC_Y, &ty); pWTInfoW (WTI_DEVICES, DVC_NPRESSURE, &pres); pWTInfoW (WTI_DEVICES, DVC_XMARGIN, &xm); pWTInfoW (WTI_DEVICES, DVC_YMARGIN, &ym); pWTInfoW (WTI_DEVICES, DVC_ZMARGIN, &zm); xmax = tx.axMax; ymax = ty.axMax; if (pWTInfoW (WTI_DEVICES, DVC_Z, &tz)) zmax = tz.axMax; lc.lcOptions |= CXO_MESSAGES; lc.lcPktData = PACKETDATA; lc.lcPktMode = PACKETMODE; lc.lcMoveMask = PACKETDATA; lc.lcBtnUpMask = lc.lcBtnDnMask; lc.lcInExtX = tx.axMax; lc.lcInExtY = ty.axMax; if (zmax > 0) lc.lcInExtZ = tz.axMax; if (!initialized) { write_log (_T("Tablet '%s' parameters\n"), tabletname); write_log (_T("Xmax=%d,Ymax=%d,Zmax=%d\n"), xmax, ymax, zmax); write_log (_T("Xres=%.1f:%d,Yres=%.1f:%d,Zres=%.1f:%d\n"), tx.axResolution / 65536.0, tx.axUnits, ty.axResolution / 65536.0, ty.axUnits, tz.axResolution / 65536.0, tz.axUnits); write_log (_T("Xrotmax=%d,Yrotmax=%d,Zrotmax=%d\n"), axmax, aymax, azmax); write_log (_T("PressureMin=%d,PressureMax=%d\n"), pres.axMin, pres.axMax); } maxpres = pres.axMax; xres = gettabletres (&tx); yres = gettabletres (&ty); tablet_div = 1; while (xmax / tablet_div > 4095 || ymax / tablet_div > 4095) { tablet_div *= 2; } xmax /= tablet_div; ymax /= tablet_div; xres /= tablet_div; yres /= tablet_div; if (tablet_div > 1) write_log (_T("Divisor: %d (%d,%d)\n"), tablet_div, xmax, ymax); tablet_proximity = -1; tablet_x = -1; inputdevice_tablet_info (xmax, ymax, zmax, axmax, aymax, azmax, xres, yres); tabletlib_tablet_info (xmax, ymax, zmax, axmax, aymax, azmax, xres, yres); initialized = 1; return pWTOpenW (hwnd, &lc, TRUE); } int close_tablet (void *ctx) { if (!wintab) return 0; if (ctx != NULL) pWTClose ((HCTX)ctx); ctx = NULL; if (!tablet) return 0; return 1; } int is_touch_lightpen(void) { return dinput_lightpen() >= 0; } int is_tablet (void) { return (tablet || os_touch) ? 1 : 0; } static int initialize_tablet (void) { TCHAR name[MAX_DPATH]; struct tagAXIS ori[3]; int tilt = 0; wintab = WIN32_LoadLibrary(_T("wintab32.dll")); if (wintab == NULL) { write_log(_T("Tablet: no wintab32.dll\n")); return 0; } pWTOpenW = (WTOPENW)GetProcAddress(wintab, "WTOpenW"); pWTClose = (WTCLOSE)GetProcAddress(wintab, "WTClose"); pWTInfoW = (WTINFOW)GetProcAddress(wintab, "WTInfoW"); pWTPacket = (WTPACKET)GetProcAddress(wintab, "WTPacket"); if (!pWTOpenW || !pWTClose || !pWTInfoW || !pWTPacket) { write_log(_T("Tablet: wintab32.dll has missing functions!\n")); FreeModule(wintab); wintab = NULL; return 0; } if (!pWTInfoW(0, 0, NULL)) { write_log(_T("Tablet: WTInfo() returned failure\n")); FreeModule(wintab); wintab = NULL; return 0; } name[0] = 0; if (!pWTInfoW (WTI_DEVICES, DVC_NAME, name)) { write_log(_T("Tablet: WTInfo(DVC_NAME) returned failure\n")); FreeModule(wintab); wintab = NULL; return 0; } if (name[0] == 0) { write_log(_T("Tablet: WTInfo(DVC_NAME) returned NULL name\n")); FreeModule(wintab); wintab = NULL; return 0; } axmax = aymax = azmax = -1; tilt = pWTInfoW (WTI_DEVICES, DVC_ORIENTATION, ori); if (tilt) { if (ori[0].axMax > 0) axmax = ori[0].axMax; if (ori[1].axMax > 0) aymax = ori[1].axMax; if (ori[2].axMax > 0) azmax = ori[2].axMax; } write_log (_T("Tablet '%s' detected\n"), name); tabletname = my_strdup (name); tablet = TRUE; return 1; } #if 0 static int initialize_parjoyport (void) { for (int i = 0; i < MAX_PARJOYPORTS && num_joystick < MAX_INPUT_DEVICES; i++) { struct didata *did; TCHAR *p = i ? currprefs.win32_parjoyport1 : currprefs.win32_parjoyport0; if (p[0] == 0) continue; HANDLE ph = CreateFile (p, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (ph == INVALID_HANDLE_VALUE) { write_log (_T("PARJOY: '%s' failed to open: %u\n"), p, GetLastError ()); continue; } write_log (_T("PARJOY: '%s' open\n"), p); for (int j = 0; j < 2; j++) { TCHAR tmp[100]; did = di_joystick; did += num_joystick; cleardid(did); did->connection = DIDC_PARJOY; did->parjoy = ph; _stprintf (tmp, _T("Parallel joystick %d.%d"), i + 1, j + 1); did->name = my_strdup (tmp); did->sortname = my_strdup (tmp); _stprintf (tmp, _T("PARJOY%d.%d"), i, j); did->configname = my_strdup (tmp); did->buttons = did->buttons_real = 1; did->axles = 2; did->axissort[0] = 0; did->axisname[0] = my_strdup (_T("X Axis")); did->axissort[1] = 1; did->axisname[1] = my_strdup (_T("Y Axis")); for (j = 0; j < did->buttons; j++) { did->buttonsort[j] = j; _stprintf (tmp, _T("Button %d"), j + 1); did->buttonname[j] = my_strdup (tmp); } did->priority = -1; fixbuttons (did); fixthings (did); num_joystick++; } } return 0; } #endif static int initialize_catweasel (void) { int j, i; TCHAR tmp[MAX_DPATH]; struct didata *did; if (catweasel_ismouse ()) { for (i = 0; i < 2 && num_mouse < MAX_INPUT_DEVICES; i++) { did = di_mouse; did += num_mouse; cleardid(did); did->connection = DIDC_CAT; did->catweasel = i; _stprintf (tmp, _T("Catweasel mouse")); did->name = my_strdup (tmp); did->sortname = my_strdup (tmp); _stprintf (tmp, _T("CWMOUSE%d"), i); did->configname = my_strdup (tmp); did->buttons = did->buttons_real = 3; did->axles = 2; did->axissort[0] = 0; did->axisname[0] = my_strdup (_T("X Axis")); did->axissort[1] = 1; did->axisname[1] = my_strdup (_T("Y Axis")); for (j = 0; j < did->buttons; j++) { did->buttonsort[j] = j; _stprintf (tmp, _T("Button %d"), j + 1); did->buttonname[j] = my_strdup (tmp); } did->priority = -1; num_mouse++; } } if (catweasel_isjoystick ()) { for (i = 0; i < 2 && num_joystick < MAX_INPUT_DEVICES; i++) { did = di_joystick; did += num_joystick; cleardid(did); did->connection = DIDC_CAT; did->catweasel = i; _stprintf (tmp, _T("Catweasel joystick")); did->name = my_strdup (tmp); did->sortname = my_strdup (tmp); _stprintf (tmp, _T("CWJOY%d"), i); did->configname = my_strdup (tmp); did->buttons = did->buttons_real = (catweasel_isjoystick () & 0x80) ? 3 : 1; did->axles = 2; did->axissort[0] = 0; did->axisname[0] = my_strdup (_T("X Axis")); did->axissort[1] = 1; did->axisname[1] = my_strdup (_T("Y Axis")); for (j = 0; j < did->buttons; j++) { did->buttonsort[j] = j; _stprintf (tmp, _T("Button %d"), j + 1); did->buttonname[j] = my_strdup (tmp); } did->priority = -1; fixbuttons (did); fixthings (did); num_joystick++; } } return 1; } static void sortobjects (struct didata *did) { int i, j; uae_s16 tmpi; TCHAR *tmpc; for (i = 0; i < did->axles; i++) { for (j = i + 1; j < did->axles; j++) { if (did->axissort[i] > did->axissort[j]) { HIDP_VALUE_CAPS tmpvcaps; tmpi = did->axismappings[i]; did->axismappings[i] = did->axismappings[j]; did->axismappings[j] = tmpi; tmpi = did->axissort[i]; did->axissort[i] = did->axissort[j]; did->axissort[j] = tmpi; tmpi = did->axistype[i]; did->axistype[i] = did->axistype[j]; did->axistype[j] = tmpi; memcpy (&tmpvcaps, &did->hidvcaps[i], sizeof tmpvcaps); memcpy (&did->hidvcaps[i], &did->hidvcaps[j], sizeof tmpvcaps); memcpy (&did->hidvcaps[j], &tmpvcaps, sizeof tmpvcaps); tmpc = did->axisname[i]; did->axisname[i] = did->axisname[j]; did->axisname[j] = tmpc; } } } for (i = 0; i < did->buttons; i++) { for (j = i + 1; j < did->buttons; j++) { if (did->buttonsort[i] > did->buttonsort[j]) { tmpi = did->buttonmappings[i]; did->buttonmappings[i] = did->buttonmappings[j]; did->buttonmappings[j] = tmpi; tmpi = did->buttonsort[i]; did->buttonsort[i] = did->buttonsort[j]; did->buttonsort[j] = tmpi; tmpc = did->buttonname[i]; did->buttonname[i] = did->buttonname[j]; did->buttonname[j] = tmpc; tmpi = did->buttonaxisparent[i]; did->buttonaxisparent[i] = did->buttonaxisparent[j]; did->buttonaxisparent[j] = tmpi; tmpi = did->buttonaxisparentdir[i]; did->buttonaxisparentdir[i] = did->buttonaxisparentdir[j]; did->buttonaxisparentdir[j] = tmpi; tmpi = did->buttonaxistype[i]; did->buttonaxistype[i] = did->buttonaxistype[j]; did->buttonaxistype[j] = tmpi; } } } #if DI_DEBUG if (did->axles + did->buttons > 0) { write_log (_T("%s: [%04X/%04X]\n"), did->name, did->vid, did->pid); if (did->connection == DIDC_DX) write_log (_T("PGUID=%s\n"), outGUID (&did->pguid)); for (i = 0; i < did->axles; i++) { HIDP_VALUE_CAPS *caps = &did->hidvcaps[i]; write_log (_T("%02X %03d '%s' (%d, [%d - %d, %d - %d, %d %d %d])\n"), did->axismappings[i], did->axismappings[i], did->axisname[i], did->axissort[i], caps->LogicalMin, caps->LogicalMax, caps->PhysicalMin, caps->PhysicalMax, caps->BitSize, caps->Units, caps->UnitsExp); } for (i = 0; i < did->buttons; i++) { write_log (_T("%02X %03d '%s' (%d)\n"), did->buttonmappings[i], did->buttonmappings[i], did->buttonname[i], did->buttonsort[i]); } } #endif } #define RDP_DEVICE1 _T("\\??\\Root#") #define RDP_DEVICE2 _T("\\\\?\\Root#") static int rdpdevice(const TCHAR *buf) { if (!_tcsncmp (RDP_DEVICE1, buf, _tcslen (RDP_DEVICE1))) return 1; if (!_tcsncmp (RDP_DEVICE2, buf, _tcslen (RDP_DEVICE2))) return 1; return 0; } static void rawinputfixname (const TCHAR *name, const TCHAR *friendlyname) { int i, ii, j; TCHAR tmp[MAX_DPATH]; if (!name[0] || !friendlyname[0]) return; while (*name) { if (*name != '\\' && *name != '?') break; name++; } _tcscpy (tmp, name); for (i = 0; i < _tcslen (tmp); i++) { if (tmp[i] == '\\') tmp[i] = '#'; tmp[i] = _totupper (tmp[i]); } for (ii = 0; ii < 3; ii++) { int cnt; struct didata *did; if (ii == 0) { cnt = num_mouse; did = di_mouse; } else if (ii == 1) { cnt = num_keyboard; did = di_keyboard; } else { cnt = num_joystick; did = di_joystick; } for (i = 0; i < cnt; i++, did++) { TCHAR tmp2[MAX_DPATH], *p2; if (!did->rawinput || did->fullname) continue; for (j = 0; j < _tcslen (did->configname); j++) tmp2[j] = _totupper (did->configname[j]); tmp2[j] = 0; p2 = tmp2; while (*p2) { if (*p2 != '\\' && *p2 != '?') break; p2++; } if (_tcslen (p2) >= _tcslen (tmp) && !_tcsncmp (p2, tmp, _tcslen (tmp))) { write_log(_T("[%04X/%04X] '%s' (%s) -> '%s'\n"), did->vid, did->pid, did->configname, did->name, friendlyname); xfree (did->name); // if (did->vid > 0 && did->pid > 0) // _stprintf (tmp, _T("%s [%04X/%04X]"), friendlyname, did->vid, did->pid); // else _stprintf (tmp, _T("%s"), friendlyname); did->name = my_strdup (tmp); } } } } #define FGUIDS 4 static void rawinputfriendlynames (void) { HDEVINFO di; int i, ii; GUID guid[FGUIDS]; HidD_GetHidGuid (&guid[0]); guid[1] = GUID_DEVCLASS_HIDCLASS; guid[2] = GUID_DEVCLASS_MOUSE; guid[3] = GUID_DEVCLASS_KEYBOARD; for (ii = 0; ii < FGUIDS; ii++) { di = SetupDiGetClassDevs (&guid[ii], NULL, NULL, 0); if (di != INVALID_HANDLE_VALUE) { SP_DEVINFO_DATA dd; dd.cbSize = sizeof dd; for (i = 0; SetupDiEnumDeviceInfo (di, i, &dd); i++) { TCHAR devpath[MAX_DPATH]; DWORD size = 0; if (SetupDiGetDeviceInstanceId (di, &dd, devpath, sizeof devpath / sizeof(TCHAR), &size)) { DEVINST devinst = dd.DevInst; TCHAR *cg = outGUID (&guid[ii]); for (;;) { TCHAR devname[MAX_DPATH]; ULONG size2; TCHAR bufguid[MAX_DPATH]; size2 = sizeof bufguid / sizeof(TCHAR); if (CM_Get_DevNode_Registry_Property (devinst, CM_DRP_CLASSGUID, NULL, bufguid, &size2, 0) != CR_SUCCESS) break; if (_tcsicmp (cg, bufguid)) break; size2 = sizeof devname / sizeof(TCHAR); if (CM_Get_DevNode_Registry_Property (devinst, CM_DRP_FRIENDLYNAME, NULL, devname, &size2, 0) != CR_SUCCESS) { ULONG size2 = sizeof devname / sizeof(TCHAR); if (CM_Get_DevNode_Registry_Property (devinst, CM_DRP_DEVICEDESC, NULL, devname, &size2, 0) != CR_SUCCESS) devname[0] = 0; } rawinputfixname (devpath, devname); DEVINST parent = devinst; if (CM_Get_Parent (&devinst, parent, 0) != CR_SUCCESS) break; } } } SetupDiDestroyDeviceInfoList (di); } } } static const TCHAR *rawkeyboardlabels[256] = { _T("ESCAPE"), _T("1"),_T("2"),_T("3"),_T("4"),_T("5"),_T("6"),_T("7"),_T("8"),_T("9"),_T("0"), _T("MINUS"),_T("EQUALS"),_T("BACK"),_T("TAB"), _T("Q"),_T("W"),_T("E"),_T("R"),_T("T"),_T("Y"),_T("U"),_T("I"),_T("O"),_T("P"), _T("LBRACKET"),_T("RBRACKET"),_T("RETURN"),_T("LCONTROL"), _T("A"),_T("S"),_T("D"),_T("F"),_T("G"),_T("H"),_T("J"),_T("K"),_T("L"), _T("SEMICOLON"),_T("APOSTROPHE"),_T("GRAVE"),_T("LSHIFT"),_T("BACKSLASH"), _T("Z"),_T("X"),_T("C"),_T("V"),_T("B"),_T("N"),_T("M"), _T("COMMA"),_T("PERIOD"),_T("SLASH"),_T("RSHIFT"),_T("MULTIPLY"),_T("LMENU"),_T("SPACE"),_T("CAPITAL"), _T("F1"),_T("F2"),_T("F3"),_T("F4"),_T("F5"),_T("F6"),_T("F7"),_T("F8"),_T("F9"),_T("F10"), _T("NUMLOCK"),_T("SCROLL"),_T("NUMPAD7"),_T("NUMPAD8"),_T("NUMPAD9"),_T("SUBTRACT"), _T("NUMPAD4"),_T("NUMPAD5"),_T("NUMPAD6"),_T("ADD"),_T("NUMPAD1"),_T("NUMPAD2"),_T("NUMPAD3"),_T("NUMPAD0"), _T("DECIMAL"),NULL,NULL,_T("OEM_102"),_T("F11"),_T("F12"), NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, _T("F13"),_T("F14"),_T("F15"),NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, _T("NUMPADEQUALS"),NULL,NULL, _T("PREVTRACK"),NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, _T("NEXTTRACK"),NULL,NULL,_T("NUMPADENTER"),_T("RCONTROL"),NULL,NULL, _T("MUTE"),_T("CALCULATOR"),_T("PLAYPAUSE"),NULL,_T("MEDIASTOP"), NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, _T("VOLUMEDOWN"),NULL,_T("VOLUMEUP"),NULL,_T("WEBHOME"),_T("NUMPADCOMMA"),NULL, _T("DIVIDE"),NULL,_T("SYSRQ"),_T("RMENU"), NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, _T("PAUSE"),NULL,_T("HOME"),_T("UP"),_T("PREV"),NULL,_T("LEFT"),NULL,_T("RIGHT"),NULL,_T("END"), _T("DOWN"),_T("NEXT"),_T("INSERT"),_T("DELETE"), NULL,NULL,NULL,NULL,NULL,NULL,NULL, _T("LWIN"),_T("RWIN"),_T("APPS"),_T("POWER"),_T("SLEEP"), NULL,NULL,NULL, _T("WAKE"),NULL,_T("WEBSEARCH"),_T("WEBFAVORITES"),_T("WEBREFRESH"),_T("WEBSTOP"), _T("WEBFORWARD"),_T("WEBBACK"),_T("MYCOMPUTER"),_T("MAIL"),_T("MEDIASELECT"), _T("") }; static void getvidpid2 (const TCHAR *devname, int *id, const TCHAR *str) { TCHAR *dv = my_strdup (devname); for (int i = 0; i < _tcslen (dv); i++) dv[i] = _totupper (dv[i]); TCHAR *s = _tcsstr (dv, str); if (s) { int val = -1; _stscanf (s + _tcslen (str), _T("%X"), &val); *id = val; } xfree (dv); } static void getvidpid (const TCHAR *devname, int *vid, int *pid, int *mi) { *vid = *pid = *mi = -1; getvidpid2 (devname, vid, _T("VID_")); getvidpid2 (devname, pid, _T("PID_")); getvidpid2 (devname, mi, _T("MI_")); } static void addrkblabels (struct didata *did) { for (int k = 0; k < 254; k++) { TCHAR tmp[100]; tmp[0] = 0; if (rawkeyboardlabels[k] != NULL && rawkeyboardlabels[k][0]) _tcscpy (tmp, rawkeyboardlabels[k]); if (!tmp[0]) _stprintf (tmp, _T("KEY_%02X"), k + 1); did->buttonname[k] = my_strdup (tmp); did->buttonmappings[k] = k + 1; did->buttonsort[k] = k + 1; did->buttons++; } } struct hiddesc { int priority; int page, usage; TCHAR *name; int type; }; static const struct hiddesc hidtable[] = { { 0x30, 1, 0x30, _T("X Axis"), 0 }, { 0x31, 1, 0x31, _T("Y Axis"), 0 }, { 0x32, 1, 0x32, _T("Z Axis"), 0 }, { 0x33, 1, 0x33, _T("X Rotation"), 0 }, { 0x34, 1, 0x34, _T("Y Rotation"), 0 }, { 0x35, 1, 0x35, _T("Z Rotation"), 0 }, { 0x36, 1, 0x36, _T("Slider"), AXISTYPE_SLIDER }, { 0x37, 1, 0x37, _T("Dial"), AXISTYPE_DIAL }, { 0x38, 1, 0x38, _T("Wheel"), 0 }, { 0x39, 1, 0x39, _T("Hat Switch"), AXISTYPE_POV_X }, { 0x90, 1, 0x90, _T("D-pad Up"), 0 }, { 0x91, 1, 0x91, _T("D-pad Down"), 0 }, { 0x92, 1, 0x92, _T("D-pad Right"), 0 }, { 0x93, 1, 0x93, _T("D-pad Left"), 0 }, { 0xbb, 2, 0xbb, _T("Throttle"), AXISTYPE_SLIDER }, { 0xba, 2, 0xba, _T("Rudder"), 0 }, { 0 } }; static uae_u32 hidmask (int bits) { return bits >= 32 ? 0xffffffff : (1 << bits) - 1; } static int extractbits (uae_u32 val, int bits, bool issigned) { if (issigned) return (val & (bits >= 32 ? 0x80000000 : (1 << (bits - 1)))) ? val | (bits >= 32 ? 0x80000000 : (-1 << bits)) : val; else return val & hidmask (bits); } struct hidquirk { uae_u16 vid, pid; }; #define USB_VENDOR_ID_LOGITECH 0x046d #define USB_DEVICE_ID_LOGITECH_G13 0xc2ab #define USB_VENDOR_ID_AASHIMA 0x06d6 #define USB_DEVICE_ID_AASHIMA_GAMEPAD 0x0025 #define USB_DEVICE_ID_AASHIMA_PREDATOR 0x0026 #define USB_VENDOR_ID_ALPS 0x0433 #define USB_DEVICE_ID_IBM_GAMEPAD 0x1101 #define USB_VENDOR_ID_CHIC 0x05fe #define USB_DEVICE_ID_CHIC_GAMEPAD 0x0014 #define USB_VENDOR_ID_DWAV 0x0eef #define USB_DEVICE_ID_EGALAX_TOUCHCONTROLLER 0x0001 #define USB_VENDOR_ID_MOJO 0x8282 #define USB_DEVICE_ID_RETRO_ADAPTER 0x3201 #define USB_VENDOR_ID_HAPP 0x078b #define USB_DEVICE_ID_UGCI_DRIVING 0x0010 #define USB_DEVICE_ID_UGCI_FLYING 0x0020 #define USB_DEVICE_ID_UGCI_FIGHTING 0x0030 #define USB_VENDOR_ID_NATSU 0x08b7 #define USB_DEVICE_ID_NATSU_GAMEPAD 0x0001 #define USB_VENDOR_ID_NEC 0x073e #define USB_DEVICE_ID_NEC_USB_GAME_PAD 0x0301 #define USB_VENDOR_ID_NEXTWINDOW 0x1926 #define USB_DEVICE_ID_NEXTWINDOW_TOUCHSCREEN 0x0003 #define USB_VENDOR_ID_SAITEK 0x06a3 #define USB_DEVICE_ID_SAITEK_RUMBLEPAD 0xff17 #define USB_VENDOR_ID_TOPMAX 0x0663 #define USB_DEVICE_ID_TOPMAX_COBRAPAD 0x0103 static const struct hidquirk quirks[] = { { USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G13 }, { USB_VENDOR_ID_AASHIMA, USB_DEVICE_ID_AASHIMA_GAMEPAD }, { USB_VENDOR_ID_AASHIMA, USB_DEVICE_ID_AASHIMA_PREDATOR }, { USB_VENDOR_ID_ALPS, USB_DEVICE_ID_IBM_GAMEPAD }, { USB_VENDOR_ID_CHIC, USB_DEVICE_ID_CHIC_GAMEPAD }, { USB_VENDOR_ID_DWAV, USB_DEVICE_ID_EGALAX_TOUCHCONTROLLER }, // { USB_VENDOR_ID_MOJO, USB_DEVICE_ID_RETRO_ADAPTER }, { USB_VENDOR_ID_HAPP, USB_DEVICE_ID_UGCI_DRIVING }, { USB_VENDOR_ID_HAPP, USB_DEVICE_ID_UGCI_FLYING }, { USB_VENDOR_ID_HAPP, USB_DEVICE_ID_UGCI_FIGHTING }, { USB_VENDOR_ID_NATSU, USB_DEVICE_ID_NATSU_GAMEPAD }, { USB_VENDOR_ID_NEC, USB_DEVICE_ID_NEC_USB_GAME_PAD }, { USB_VENDOR_ID_NEXTWINDOW, USB_DEVICE_ID_NEXTWINDOW_TOUCHSCREEN }, { USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_RUMBLEPAD }, { USB_VENDOR_ID_TOPMAX, USB_DEVICE_ID_TOPMAX_COBRAPAD }, { 0 } }; // PC analog joystick to USB adapters static const struct hidquirk hidnorawinput[] = { { 0x0583, 0x2030 }, // Rockfire RM-203 1 { 0x0583, 0x2031 }, // Rockfire RM-203 2 { 0x0583, 0x2032 }, // Rockfire RM-203 3 { 0x0583, 0x2033 }, // Rockfire RM-203 4 { 0x079d, 0x0201 }, // "USB ADAPTOR" { 0 } }; static void fixhidvcaps (RID_DEVICE_INFO_HID *hid, HIDP_VALUE_CAPS *caps) { int pid = hid->dwProductId; int vid = hid->dwVendorId; caps->LogicalMin = extractbits(caps->LogicalMin, caps->BitSize, caps->LogicalMin < 0); caps->LogicalMax = extractbits(caps->LogicalMax, caps->BitSize, caps->LogicalMin < 0); caps->PhysicalMin = extractbits(caps->PhysicalMin, caps->BitSize, caps->PhysicalMin < 0); caps->PhysicalMax = extractbits(caps->PhysicalMax, caps->BitSize, caps->PhysicalMin < 0); for (int i = 0; quirks[i].vid; i++) { if (vid == quirks[i].vid && pid == quirks[i].pid) { caps->LogicalMin = 0; caps->LogicalMax = 255; break; } } } static void dumphidvaluecaps (PHIDP_VALUE_CAPS vcaps, int size) { for (int i = 0; i < size; i++) { HIDP_VALUE_CAPS caps = vcaps[i]; write_log (L"******** VALUE_CAPS: %d ********\n", i); write_log (L"UsagePage: %u\n", caps.UsagePage); write_log (L"ReportID: %u\n", caps.ReportID); write_log (L"IsAlias: %u\n", caps.IsAlias); write_log (L"BitField: %u\n", caps.BitField); write_log (L"LinkCollection: %u\n", caps.LinkCollection); write_log (L"LinkUsage: %u\n", caps.LinkUsage); write_log (L"LinkUsagePage: %u\n", caps.LinkUsagePage); write_log (L"IsRange: %u\n", caps.IsRange); write_log (L"IsStringRange: %u\n", caps.IsStringRange); write_log (L"IsDesignatorRange: %u\n", caps.IsDesignatorRange); write_log (L"IsAbsolute: %u\n", caps.IsAbsolute); write_log (L"HasNull: %u\n", caps.HasNull); write_log (L"BitSize: %u\n", caps.BitSize); write_log (L"ReportCount: %u\n", caps.ReportCount); write_log (L"UnitsExp: %u\n", caps.UnitsExp); write_log (L"Units: %u\n", caps.Units); write_log (L"LogicalMin: %u (%d)\n", caps.LogicalMin, extractbits (caps.LogicalMin, caps.BitSize, caps.LogicalMin < 0)); write_log (L"LogicalMax: %u (%d)\n", caps.LogicalMax, extractbits (caps.LogicalMax, caps.BitSize, caps.LogicalMin < 0)); write_log (L"PhysicalMin: %u (%d)\n", caps.PhysicalMin, extractbits (caps.PhysicalMin, caps.BitSize, caps.PhysicalMin < 0)); write_log (L"PhysicalMax: %u (%d)\n", caps.PhysicalMax, extractbits (caps.PhysicalMax, caps.BitSize, caps.PhysicalMax < 0)); if (caps.IsRange) { write_log (L"UsageMin: %u\n", caps.Range.UsageMin); write_log (L"UsageMax: %u\n", caps.Range.UsageMax); write_log (L"StringMin: %u\n", caps.Range.StringMin); write_log (L"StringMax: %u\n", caps.Range.StringMax); write_log (L"DesignatorMin: %u\n", caps.Range.DesignatorMin); write_log (L"DesignatorMax: %u\n", caps.Range.DesignatorMax); write_log (L"DataIndexMin: %u\n", caps.Range.DataIndexMin); write_log (L"DataIndexMax: %u\n", caps.Range.DataIndexMax); } else { write_log (L"Usage: %u\n", caps.NotRange.Usage); write_log (L"StringIndex: %u\n", caps.NotRange.StringIndex); write_log (L"DesignatorIndex: %u\n", caps.NotRange.DesignatorIndex); write_log (L"DataIndex: %u\n", caps.NotRange.DataIndex); } } } static void dumphidbuttoncaps (PHIDP_BUTTON_CAPS pcaps, int size) { for (int i = 0; i < size; i++) { HIDP_BUTTON_CAPS caps = pcaps[i]; write_log (L"******** BUTTON_CAPS: %d ********\n", i); write_log (L"UsagePage: %u\n", caps.UsagePage); write_log (L"ReportID: %u\n", caps.ReportID); write_log (L"IsAlias: %u\n", caps.IsAlias); write_log (L"BitField: %u\n", caps.BitField); write_log (L"LinkCollection: %u\n", caps.LinkCollection); write_log (L"LinkUsage: %u\n", caps.LinkUsage); write_log (L"LinkUsagePage: %u\n", caps.LinkUsagePage); write_log (L"IsRange: %u\n", caps.IsRange); write_log (L"IsStringRange: %u\n", caps.IsStringRange); write_log (L"IsDesignatorRange: %u\n", caps.IsDesignatorRange); write_log (L"IsAbsolute: %u\n", caps.IsAbsolute); if (caps.IsRange) { write_log (L"UsageMin: %u\n", caps.Range.UsageMin); write_log (L"UsageMax: %u\n", caps.Range.UsageMax); write_log (L"StringMin: %u\n", caps.Range.StringMin); write_log (L"StringMax: %u\n", caps.Range.StringMax); write_log (L"DesignatorMin: %u\n", caps.Range.DesignatorMin); write_log (L"DesignatorMax: %u\n", caps.Range.DesignatorMax); write_log (L"DataIndexMin: %u\n", caps.Range.DataIndexMin); write_log (L"DataIndexMax: %u\n", caps.Range.DataIndexMax); } else { write_log (L"Usage: %u\n", caps.NotRange.Usage); write_log (L"StringIndex: %u\n", caps.NotRange.StringIndex); write_log (L"DesignatorIndex: %u\n", caps.NotRange.DesignatorIndex); write_log (L"DataIndex: %u\n", caps.NotRange.DataIndex); } } } static void dumphidcaps (struct didata *did) { HIDP_CAPS caps = did->hidcaps; write_log (_T("Usage: %04x\n"), caps.Usage); write_log (_T("UsagePage: %04x\n"), caps.UsagePage); write_log (_T("InputReportByteLength: %u\n"), caps.InputReportByteLength); write_log (_T("OutputReportByteLength: %u\n"), caps.OutputReportByteLength); write_log (_T("FeatureReportByteLength: %u\n"), caps.FeatureReportByteLength); write_log (_T("NumberLinkCollectionNodes: %u\n"), caps.NumberLinkCollectionNodes); write_log (_T("NumberInputButtonCaps: %u\n"), caps.NumberInputButtonCaps); write_log (_T("NumberInputValueCaps: %u\n"), caps.NumberInputValueCaps); write_log (_T("NumberInputDataIndices: %u\n"), caps.NumberInputDataIndices); write_log (_T("NumberOutputButtonCaps: %u\n"), caps.NumberOutputButtonCaps); write_log (_T("NumberOutputValueCaps: %u\n"), caps.NumberOutputValueCaps); write_log (_T("NumberOutputDataIndices: %u\n"), caps.NumberOutputDataIndices); write_log (_T("NumberFeatureButtonCaps: %u\n"), caps.NumberFeatureButtonCaps); write_log (_T("NumberFeatureValueCaps: %u\n"), caps.NumberFeatureValueCaps); write_log (_T("NumberFeatureDataIndices: %u\n"), caps.NumberFeatureDataIndices); } static void dumphidend (void) { write_log (_T("\n")); } static const TCHAR *tohex(TCHAR *s) { static TCHAR out[128 * 6]; int len = 0; TCHAR *d = out; uae_u8 *ss = (uae_u8*)s; while (*s && len < 128 - 1) { if (len > 0) { *d++ = ' '; } _stprintf(d, _T("%02X %02X"), ss[0], ss[1]); d += _tcslen(d); ss += 2; s++; len++; } *d = 0; return out; } static void add_xinput_device(struct didata *did) { TCHAR tmp[256]; did->connection = DIDC_XINPUT; int buttoncnt = 0; for (int i = 1; i <= 16; i++) { did->buttonsort[buttoncnt] = i * 2; did->buttonmappings[buttoncnt] = i; _stprintf(tmp, _T("Button %d"), i); did->buttonname[buttoncnt] = my_strdup(tmp); buttoncnt++; } did->buttons = buttoncnt; fixbuttons(did); fixthings(did); } #define MAX_RAW_KEYBOARD 0 static bool initialize_rawinput (void) { RAWINPUTDEVICELIST *ridl = 0; UINT num = 500, vtmp; int gotnum, bufsize; int rnum_mouse, rnum_kb, rnum_hid, rnum_raw; TCHAR *bufp, *buf1, *buf2; int rmouse = 0, rkb = 0, rhid = 0; TCHAR tmp[100]; bufsize = 10000 * sizeof (TCHAR); bufp = xmalloc (TCHAR, 2 * bufsize / sizeof (TCHAR)); buf1 = bufp; buf2 = buf1 + 10000; if (GetRawInputDeviceList (NULL, &num, sizeof (RAWINPUTDEVICELIST)) != 0) { write_log (_T("RAWINPUT error %08X\n"), GetLastError()); goto error2; } write_log (_T("RAWINPUT: found %d devices\n"), num); if (num <= 0) goto error2; ridl = xcalloc (RAWINPUTDEVICELIST, num); gotnum = GetRawInputDeviceList (ridl, &num, sizeof (RAWINPUTDEVICELIST)); if (gotnum <= 0) { write_log (_T("RAWINPUT didn't find any devices\n")); goto error2; } if (rawinput_enabled_hid) { for (int rawcnt = 0; rawcnt < gotnum; rawcnt++) { int type = ridl[rawcnt].dwType; HANDLE h = ridl[rawcnt].hDevice; PRID_DEVICE_INFO rdi; if (type != RIM_TYPEHID) continue; rdi = (PRID_DEVICE_INFO)buf2; memset (rdi, 0, sizeof (RID_DEVICE_INFO)); rdi->cbSize = sizeof (RID_DEVICE_INFO); if (GetRawInputDeviceInfo (h, RIDI_DEVICEINFO, NULL, &vtmp) == -1) continue; if (vtmp >= bufsize) continue; if (GetRawInputDeviceInfo (h, RIDI_DEVICEINFO, buf2, &vtmp) == -1) continue; for (int i = 0; hidnorawinput[i].vid; i++) { if (hidnorawinput[i].vid == rdi->hid.dwVendorId && hidnorawinput[i].pid == rdi->hid.dwProductId) { write_log (_T("Found USB HID device that requires calibration (%04X/%04X), disabling HID RAWINPUT support\n"), rdi->hid.dwVendorId, rdi->hid.dwProductId); rawinput_enabled_hid = 0; } } } } rnum_raw = rnum_mouse = rnum_kb = rnum_hid = 0; raw_handles = 0; for (int rawcnt = 0; rawcnt < gotnum; rawcnt++) { int type = ridl[rawcnt].dwType; HANDLE h = ridl[rawcnt].hDevice; if (raw_handles < MAX_RAW_HANDLES) rawinputhandles[raw_handles++] = h; if (GetRawInputDeviceInfo (h, RIDI_DEVICENAME, NULL, &vtmp) == 1) continue; if (vtmp >= bufsize) continue; if (GetRawInputDeviceInfo (h, RIDI_DEVICENAME, buf1, &vtmp) == -1) continue; if (rdpdevice (buf1)) continue; if (type == RIM_TYPEMOUSE) rnum_mouse++; else if (type == RIM_TYPEKEYBOARD) rnum_kb++; else if (type == RIM_TYPEHID) rnum_hid++; } if (MAX_RAW_KEYBOARD > 0 && rnum_kb > MAX_RAW_KEYBOARD) rnum_kb = MAX_RAW_KEYBOARD; write_log (_T("HID device check:\n")); for (int rawcnt = 0; rawcnt < gotnum; rawcnt++) { HANDLE h = ridl[rawcnt].hDevice; int type = ridl[rawcnt].dwType; if (type == RIM_TYPEKEYBOARD || type == RIM_TYPEMOUSE || type == RIM_TYPEHID) { TCHAR prodname[128]; struct didata *did; PRID_DEVICE_INFO rdi; int v, i, j; if (rawinput_decided) { // must not enable rawinput later, even if rawinput capable device was plugged in if (type == RIM_TYPEKEYBOARD && !rawinput_enabled_keyboard) continue; if (type == RIM_TYPEMOUSE && !rawinput_enabled_mouse) continue; if (type == RIM_TYPEHID && !rawinput_enabled_hid) continue; } if (type == RIM_TYPEKEYBOARD) { if (num_keyboard >= rnum_kb) continue; did = di_keyboard; } else if (type == RIM_TYPEMOUSE) { did = di_mouse; } else if (type == RIM_TYPEHID) { if (!rawinput_enabled_hid) continue; did = di_joystick; } else continue; if (GetRawInputDeviceInfo (h, RIDI_DEVICENAME, NULL, &vtmp) == -1) { write_log (_T("%p RIDI_DEVICENAME failed\n"), h); continue; } if (vtmp >= bufsize) { write_log (_T("%p RIDI_DEVICENAME too big %d\n"), h, vtmp); continue; } if (GetRawInputDeviceInfo (h, RIDI_DEVICENAME, buf1, &vtmp) == -1) { write_log (_T("%p RIDI_DEVICENAME %d failed\n"), h, vtmp); continue; } rdi = (PRID_DEVICE_INFO)buf2; memset (rdi, 0, sizeof (RID_DEVICE_INFO)); rdi->cbSize = sizeof (RID_DEVICE_INFO); if (GetRawInputDeviceInfo (h, RIDI_DEVICEINFO, NULL, &vtmp) == -1) { write_log (_T("%p RIDI_DEVICEINFO failed\n"), h); continue; } if (vtmp >= bufsize) { write_log (_T("%p RIDI_DEVICEINFO too big %d\n"), h, vtmp); continue; } if (GetRawInputDeviceInfo (h, RIDI_DEVICEINFO, buf2, &vtmp) == -1) { write_log (_T("%p RIDI_DEVICEINFO %d failed\n"), h, vtmp); continue; } write_log (_T("%p %d %04X/%04X (%d/%d)\n"), h, type, rdi->hid.dwVendorId, rdi->hid.dwProductId, rdi->hid.usUsage, rdi->hid.usUsagePage); if (type == RIM_TYPEMOUSE) { if (rdpdevice (buf1)) continue; if (num_mouse >= MAX_INPUT_DEVICES - (no_windowsmouse ? 0 : 1)) {/* leave space for Windows mouse */ write_log (_T("Too many mice\n")); continue; } did += num_mouse; num_mouse++; rmouse++; v = rmouse; } else if (type == RIM_TYPEKEYBOARD) { if (rdpdevice (buf1)) continue; if (num_keyboard >= MAX_INPUT_DEVICES) { write_log (_T("Too many keyboards\n")); continue; } did += num_keyboard; num_keyboard++; rkb++; v = rkb; } else if (type == RIM_TYPEHID) { if (rdpdevice (buf1)) continue; if (rdi->hid.usUsagePage != 0x01) { write_log(_T("RAWHID: UsagePage not 1 (%04x)\n"), rdi->hid.usUsagePage); continue; } if (rdi->hid.usUsage != 4 && rdi->hid.usUsage != 5) { write_log (_T("RAWHID: Usage not 4 or 5 (%04X)\n"), rdi->hid.usUsage); continue; } for (i = 0; hidnorawinput[i].vid; i++) { if (rdi->hid.dwProductId == hidnorawinput[i].pid && rdi->hid.dwVendorId == hidnorawinput[i].vid) break; } if (hidnorawinput[i].vid) { write_log (_T("RAWHID: blacklisted\n")); continue; } if (num_joystick >= MAX_INPUT_DEVICES) { write_log (_T("RAWHID: too many devices\n")); continue; } did += num_joystick; num_joystick++; rhid++; v = rhid; } prodname[0] = 0; HANDLE hhid = NULL; hhid = CreateFile (buf1, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // mouse and keyboard don't allow READ or WRITE access if (hhid == INVALID_HANDLE_VALUE) { hhid = CreateFile(buf1, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); } if (hhid != INVALID_HANDLE_VALUE) { if (!HidD_GetProductString (hhid, prodname, sizeof prodname)) { prodname[0] = 0; } else { while (_tcslen (prodname) > 0 && prodname[_tcslen (prodname) - 1] == ' ') { prodname[_tcslen (prodname) - 1] = 0; } // Corrupted productstrings do exist so lets just ignore it if has non-ASCII characters for (int i = 0; i < _tcslen(prodname); i++) { if (prodname[i] >= 0x100 || prodname[i] < 32) { prodname[0] = 0; write_log(_T("HidD_GetProductString ignored!\n")); break; } } } if (prodname[0]) write_log(_T("(%s) '%s'\n"), tohex(prodname), prodname); } else { write_log (_T("HID CreateFile failed %d\n"), GetLastError ()); } if (type == RIM_TYPEMOUSE) { prodname[0] = 0; } rnum_raw++; cleardid (did); if (_tcsstr(buf1, _T("IG_"))) { did->xinput = 1; } getvidpid (buf1, &did->vid, &did->pid, &did->mi); if (prodname[0]) { _tcscpy (tmp, prodname); did->fullname = true; } else { TCHAR *st = type == RIM_TYPEHID ? (did->xinput ? _T("RAW HID+XINPUT") : _T("RAW HID")) : (type == RIM_TYPEMOUSE ? _T("RAW Mouse") : _T("RAW Keyboard")); if (did->vid > 0 && did->pid > 0) _stprintf (tmp, _T("%s (%04X/%04X)"), st, did->vid, did->pid); else _stprintf (tmp, _T("%s"), st); } did->name = my_strdup (tmp); did->rawinput = h; did->rawhidhandle = hhid; did->connection = DIDC_RAW; write_log (_T("%p %p [%04X/%04X] %s: "), h, hhid, did->vid, did->pid, type == RIM_TYPEHID ? _T("hid") : (type == RIM_TYPEMOUSE ? _T("mouse") : _T("keyboard"))); did->sortname = my_strdup (buf1); write_log (_T("'%s'\n"), buf1); did->configname = my_strdup (buf1); if (_tcslen(did->configname) >= MAX_JPORT_CONFIG) did->configname[MAX_JPORT_CONFIG - 1] = 0; if (type == RIM_TYPEMOUSE) { PRID_DEVICE_INFO_MOUSE rdim = &rdi->mouse; write_log (_T("id=%d buttons=%d hw=%d rate=%d\n"), rdim->dwId, rdim->dwNumberOfButtons, rdim->fHasHorizontalWheel, rdim->dwSampleRate); int buttons = rdim->dwNumberOfButtons; // limit to 20, can only have 32 buttons and it also includes [-][+] axis events. if (buttons > 20) { write_log(_T("too many buttons (%d > 20)\n"), buttons); buttons = 20; } did->buttons_real = did->buttons = (uae_s16)buttons; for (j = 0; j < did->buttons; j++) { did->buttonsort[j] = j; did->buttonmappings[j] = j; _stprintf (tmp, _T("Button %d"), j + 1); did->buttonname[j] = my_strdup (tmp); } did->axles = 3; did->axissort[0] = 0; did->axismappings[0] = 0; did->axisname[0] = my_strdup (_T("X Axis")); did->axissort[1] = 1; did->axismappings[1] = 1; did->axisname[1] = my_strdup (_T("Y Axis")); did->axissort[2] = 2; did->axismappings[2] = 2; did->axisname[2] = my_strdup (_T("Wheel")); addplusminus (did, 2); if (1 || rdim->fHasHorizontalWheel) { // why is this always false? did->axissort[3] = 3; did->axisname[3] = my_strdup (_T("HWheel")); did->axismappings[3] = 3; did->axles++; addplusminus (did, 3); } if (num_mouse == 1) did->priority = -1; else did->priority = -2; } else if (type == RIM_TYPEKEYBOARD) { PRID_DEVICE_INFO_KEYBOARD rdik = &rdi->keyboard; write_log (_T("type=%d sub=%d mode=%d fkeys=%d indicators=%d tkeys=%d\n"), rdik->dwType, rdik->dwSubType, rdik->dwKeyboardMode, rdik->dwNumberOfFunctionKeys, rdik->dwNumberOfIndicators, rdik->dwNumberOfKeysTotal); addrkblabels (did); if (num_keyboard == 1) did->priority = -1; else did->priority = -2; } else { bool ok = false; #if 0 if (did->xinput) { CloseHandle(did->rawhidhandle); did->rawhidhandle = NULL; rhid--; rnum_raw--; add_xinput_device(did); continue; } #endif if (hhid != INVALID_HANDLE_VALUE && HidD_GetPreparsedData (hhid, &did->hidpreparseddata)) { if (HidP_GetCaps (did->hidpreparseddata, &did->hidcaps) == HIDP_STATUS_SUCCESS) { PHIDP_BUTTON_CAPS bcaps; USHORT size = did->hidcaps.NumberInputButtonCaps; write_log(_T("RAWHID: %d/%d %d '%s' ('%s')\n"), rawcnt, gotnum, num_joystick - 1, did->name, did->configname); dumphidcaps (did); bcaps = xmalloc (HIDP_BUTTON_CAPS, size); if (HidP_GetButtonCaps (HidP_Input, bcaps, &size, did->hidpreparseddata) == HIDP_STATUS_SUCCESS) { dumphidbuttoncaps (bcaps, size); int buttoncnt = 0; // limit to 20, can only have 32 buttons and it also includes [-][+] axis events. for (i = 0; i < size && buttoncnt < 20; i++) { int first, last; if (bcaps[i].UsagePage >= 0xff00) continue; if (bcaps[i].IsRange) { first = bcaps[i].Range.UsageMin; last = bcaps[i].Range.UsageMax; } else { first = last = bcaps[i].NotRange.Usage; } for (j = first; j <= last && buttoncnt < 20; j++) { int k; for (k = 0; k < buttoncnt; k++) { if (did->buttonmappings[k] == j) break; } if (k == buttoncnt) { did->buttonsort[buttoncnt] = j * 2; did->buttonmappings[buttoncnt] = j; _stprintf (tmp, _T("Button %d"), j); did->buttonname[buttoncnt] = my_strdup (tmp); buttoncnt++; } } } if (buttoncnt > 0) { did->buttons = buttoncnt; ok = true; } } xfree (bcaps); PHIDP_VALUE_CAPS vcaps; size = did->hidcaps.NumberInputValueCaps; vcaps = xmalloc (HIDP_VALUE_CAPS, size); if (HidP_GetValueCaps (HidP_Input, vcaps, &size, did->hidpreparseddata) == HIDP_STATUS_SUCCESS) { #if 0 for (i = 0; i < size; i++) { int usage1; if (vcaps[i].IsRange) usage1 = vcaps[i].Range.UsageMin; else usage1 = vcaps[i].NotRange.Usage; for (j = i + 1; j < size; j++) { int usage2; if (vcaps[j].IsRange) usage2 = vcaps[j].Range.UsageMin; else usage2 = vcaps[j].NotRange.Usage; if (usage1 < usage2) { HIDP_VALUE_CAPS tcaps; memcpy(&tcaps, &vcaps[i], sizeof(HIDP_VALUE_CAPS)); memcpy(&vcaps[i], &vcaps[j], sizeof(HIDP_VALUE_CAPS)); memcpy(&vcaps[j], &tcaps, sizeof(HIDP_VALUE_CAPS)); } } } #endif dumphidvaluecaps (vcaps, size); int axiscnt = 0; for (i = 0; i < size && axiscnt < ID_AXIS_TOTAL; i++) { int first, last; if (vcaps[i].IsRange) { first = vcaps[i].Range.UsageMin; last = vcaps[i].Range.UsageMax; } else { first = last = vcaps[i].NotRange.Usage; } for (int acnt = first; acnt <= last && axiscnt < ID_AXIS_TOTAL; acnt++) { int ht; for (ht = 0; hidtable[ht].name; ht++) { if (hidtable[ht].usage == acnt && hidtable[ht].page == vcaps[i].UsagePage) { int k; for (k = 0; k < axiscnt; k++) { if (did->axismappings[k] == acnt) break; } if (k == axiscnt) { if (hidtable[ht].page == 0x01 && acnt == 0x39) { // POV if (axiscnt + 1 < ID_AXIS_TOTAL) { for (int l = 0; l < 2; l++) { TCHAR tmp[256]; _stprintf (tmp, _T("%s (%c)"), hidtable[ht].name, l == 0 ? 'X' : 'Y'); did->axisname[axiscnt] = my_strdup (tmp); did->axissort[axiscnt] = hidtable[ht].priority * 2 + l; did->axismappings[axiscnt] = acnt; memcpy (&did->hidvcaps[axiscnt], &vcaps[i], sizeof(HIDP_VALUE_CAPS)); did->axistype[axiscnt] = l + 1; axiscnt++; } } } else { did->axissort[axiscnt] = hidtable[ht].priority * 2; did->axisname[axiscnt] = my_strdup (hidtable[ht].name); did->axismappings[axiscnt] = acnt; memcpy (&did->hidvcaps[axiscnt], &vcaps[i], sizeof(HIDP_VALUE_CAPS)); fixhidvcaps (&rdi->hid, &did->hidvcaps[axiscnt]); #if NEGATIVEMINHACK did->hidvcaps[axiscnt].LogicalMin -= (did->hidvcaps[axiscnt].LogicalMax / 2); did->hidvcaps[axiscnt].LogicalMax -= (did->hidvcaps[axiscnt].LogicalMax / 2); #endif did->axistype[axiscnt] = hidtable[ht].type; axiscnt++; did->analogstick = true; } break; } } } if (hidtable[ht].name == NULL) write_log (_T("unsupported usage %d/%d\n"), vcaps[i].UsagePage, acnt); } } if (axiscnt > 0) { did->axles = axiscnt; ok = true; } } xfree (vcaps); dumphidend (); } } if (ok) { did->hidbuffer = xmalloc (CHAR, did->hidcaps.InputReportByteLength + 1); did->hidbufferprev = xmalloc (CHAR, did->hidcaps.InputReportByteLength + 1); did->maxusagelistlength = HidP_MaxUsageListLength (HidP_Input, 0, did->hidpreparseddata); did->usagelist = xmalloc (USAGE_AND_PAGE, did->maxusagelistlength); did->prevusagelist = xcalloc (USAGE_AND_PAGE, did->maxusagelistlength); fixbuttons (did); fixthings (did); rawhid_found = true; } else { if (did->hidpreparseddata) HidD_FreePreparsedData (did->hidpreparseddata); did->hidpreparseddata = NULL; num_joystick--; rhid--; rnum_raw--; } } } } if (rnum_kb && num_keyboard < MAX_INPUT_DEVICES - 1) { struct didata *did = di_keyboard + num_keyboard; num_keyboard++; rnum_kb++; did->name = my_strdup (_T("WinUAE keyboard")); did->rawinput = NULL; did->connection = DIDC_RAW; did->sortname = my_strdup (_T("NULLKEYBOARD")); did->priority = 2; did->configname = my_strdup (_T("NULLKEYBOARD")); addrkblabels (did); } rawinputfriendlynames (); xfree (ridl); xfree (bufp); if (rnum_raw > 0) rawinput_available = 1; for (int i = 0; i < num_mouse; i++) sortobjects (&di_mouse[i]); for (int i = 0; i < num_joystick; i++) sortobjects (&di_joystick[i]); rawinput_alloc(); return 1; error2: xfree (ridl); xfree (bufp); return 0; } static void initialize_windowsmouse (void) { struct didata *did = di_mouse; TCHAR tmp[100], *name; int i, j; did += num_mouse; for (i = 0; i < 2; i++) { if (num_mouse >= MAX_INPUT_DEVICES) return; cleardid (did); num_mouse++; name = (i == 0) ? _T("Windows mouse") : _T("Touchscreen light pen"); did->connection = DIDC_WIN; did->name = my_strdup (i ? _T("Touchscreen light pen") : _T("Windows mouse")); did->sortname = my_strdup (i ? _T("Lightpen1") : _T("Windowsmouse1")); did->configname = my_strdup (i ? _T("LIGHTPEN1") : _T("WINMOUSE1")); did->buttons = GetSystemMetrics (SM_CMOUSEBUTTONS); if (did->buttons < 3) did->buttons = 3; if (did->buttons > 5) did->buttons = 5; /* no non-direcinput support for >5 buttons */ if (i == 1) did->buttons = 1; did->buttons_real = did->buttons; for (j = 0; j < did->buttons; j++) { did->buttonsort[j] = j; _stprintf (tmp, _T("Button %d"), j + 1); did->buttonname[j] = my_strdup (tmp); } winmousewheelbuttonstart = did->buttons; if (i == 0) { did->axles = 4; did->axissort[0] = 0; did->axisname[0] = my_strdup (_T("X Axis")); did->axissort[1] = 1; did->axisname[1] = my_strdup (_T("Y Axis")); if (did->axles > 2) { did->axissort[2] = 2; did->axisname[2] = my_strdup (_T("Wheel")); addplusminus (did, 2); } if (did->axles > 3) { did->axissort[3] = 3; did->axisname[3] = my_strdup (_T("HWheel")); addplusminus (did, 3); } did->priority = 2; } else { did->priority = 1; } did->wininput = i + 1; did++; if (!is_tablet()) break; } } static uae_u8 rawkeystate[256]; static int rawprevkey; static void handle_rawinput_2 (RAWINPUT *raw, LPARAM lParam) { int i, num; struct didata *did; int istest = inputdevice_istest (); if (raw->header.dwType == RIM_TYPEMOUSE) { PRAWMOUSE rm = &raw->data.mouse; HANDLE h = raw->header.hDevice; for (num = 0; num < num_mouse; num++) { did = &di_mouse[num]; if (did->acquired) { if (did->rawinput == h) break; } } if (rawinput_log & 2) { write_log(_T("%p %04x %04x %04x %08x %3d %3d %08x M=%d F=%d\n"), raw->header.hDevice, rm->usFlags, rm->usButtonFlags, rm->usButtonData, rm->ulRawButtons, rm->lLastX, rm->lLastY, rm->ulExtraInformation, num < num_mouse ? num + 1 : -1, isfocus()); } #if OUTPUTDEBUG TCHAR xx[256]; _stprintf(xx, _T("%p %d %p %04x %04x %04x %08x %3d %3d %08x M=%d F=%d\n"), GetCurrentProcess(), timeframes, raw->header.hDevice, rm->usFlags, rm->usButtonFlags, rm->usButtonData, rm->ulRawButtons, rm->lLastX, rm->lLastY, rm->ulExtraInformation, num < num_mouse ? num + 1 : -1, isfocus()); OutputDebugString(xx); #endif USHORT usButtonFlags = rm->usButtonFlags; #ifdef RETROPLATFORM if (usButtonFlags && isfocus() != 0) { usButtonFlags = rp_rawbuttons(lParam, usButtonFlags); } #endif if (num == num_mouse) return; if (rp_ismouseevent()) return; if (isfocus () > 0 || istest) { static int lastx[MAX_INPUT_DEVICES], lasty[MAX_INPUT_DEVICES]; static int lastmbr[MAX_INPUT_DEVICES]; for (i = 0; i < (5 > did->buttons ? did->buttons : 5); i++) { if (usButtonFlags & (3 << (i * 2))) { int state = (usButtonFlags & (1 << (i * 2))) ? 1 : 0; if (!istest && i == 2 && (currprefs.input_mouse_untrap & MOUSEUNTRAP_MIDDLEBUTTON)) continue; setmousebuttonstate (num, i, state); } } if (did->buttons > 5) { for (i = 5; i < did->buttons; i++) { if ((lastmbr[num] & (1 << i)) != (rm->ulRawButtons & (1 << i))) setmousebuttonstate (num, i, (rm->ulRawButtons & (1 << i)) ? 1 : 0); } lastmbr[num] = rm->ulRawButtons; } for (i = 0; i < 2; i++) { int bnum = did->buttons_real + (i * 2); // RI_MOUSE_WHEEL << 1 = HWHEEL if (rm->usButtonFlags & (RI_MOUSE_WHEEL << i)) { int val = (short)rm->usButtonData; setmousestate (num, 2, val, 0); if (istest) setmousestate (num, 2, 0, 0); if (val < 0) setmousebuttonstate (num, bnum + 0, -1); else if (val > 0) setmousebuttonstate (num, bnum + 1, -1); } } if (!rm->ulButtons) { if (istest) { static time_t ot; time_t t = time (NULL); if (t != ot && t != ot + 1) { if (abs (rm->lLastX - lastx[num]) > 7) { setmousestate (num, 0, rm->lLastX, (rm->usFlags & (MOUSE_MOVE_ABSOLUTE | MOUSE_VIRTUAL_DESKTOP)) ? 1 : 0); lastx[num] = rm->lLastX; lasty[num] = rm->lLastY; ot = t; } if (abs (rm->lLastY - lasty[num]) > 7) { setmousestate (num, 1, rm->lLastY, (rm->usFlags & (MOUSE_MOVE_ABSOLUTE | MOUSE_VIRTUAL_DESKTOP)) ? 1 : 0); lastx[num] = rm->lLastX; lasty[num] = rm->lLastY; ot = t; } } } else { setmousestate (num, 0, rm->lLastX, (rm->usFlags & (MOUSE_MOVE_ABSOLUTE | MOUSE_VIRTUAL_DESKTOP)) ? 1 : 0); setmousestate (num, 1, rm->lLastY, (rm->usFlags & (MOUSE_MOVE_ABSOLUTE | MOUSE_VIRTUAL_DESKTOP)) ? 1 : 0); lastx[num] = rm->lLastX; lasty[num] = rm->lLastY; } } } if (isfocus () && !istest) { if (did->buttons >= 3 && (usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_DOWN)) { if (currprefs.input_mouse_untrap & MOUSEUNTRAP_MIDDLEBUTTON) { if ((isfullscreen() < 0 && currprefs.win32_minimize_inactive) || isfullscreen() > 0) minimizewindow(0); if (mouseactive) setmouseactive(0, 0); } } } } else if (raw->header.dwType == RIM_TYPEHID) { int j; PRAWHID hid = &raw->data.hid; HANDLE h = raw->header.hDevice; PCHAR rawdata; if ((rawinput_log & 4) || RAWINPUT_DEBUG) { static uae_u8 *oldbuf; static int oldbufsize; if (oldbufsize != hid->dwSizeHid) { xfree(oldbuf); oldbufsize = hid->dwSizeHid; oldbuf = xcalloc(uae_u8, oldbufsize); } uae_u8 *r = hid->bRawData; if (memcmp(r, oldbuf, oldbufsize)) { write_log (_T("%d %d "), hid->dwCount, hid->dwSizeHid); for (int i = 0; i < hid->dwSizeHid; i++) write_log (_T("%02X"), r[i]); write_log (_T(" H=%p\n"), h); memcpy(oldbuf, r, oldbufsize); } } for (num = 0; num < num_joystick; num++) { did = &di_joystick[num]; if (did->connection != DIDC_RAW) continue; if (did->acquired && did->rawinput == h) break; } #if RAWINPUT_DEBUG if (num >= num_joystick) { if (!rawinput_enabled_hid) return; write_log(_T("RAWHID unknown input handle %p\n"), h); for (num = 0; num < num_joystick; num++) { did = &di_joystick[num]; if (did->connection != DIDC_RAW) continue; if (!did->acquired && did->rawinput == h) { write_log(_T("RAWHID %d %p was unacquired!\n"), num, did->rawinput); return; } } } #endif #ifdef RETROPLATFORM if (rp_isactive ()) return; #endif if (!istest && !mouseactive && !(currprefs.win32_active_input & 4)) { return; } if (num < num_joystick) { rawdata = (PCHAR)hid->bRawData; for (int i = 0; i < hid->dwCount; i++) { DWORD usagelength = did->maxusagelistlength; if (HidP_GetUsagesEx (HidP_Input, 0, did->usagelist, &usagelength, did->hidpreparseddata, rawdata, hid->dwSizeHid) == HIDP_STATUS_SUCCESS) { int k; for (k = 0; k < usagelength; k++) { if (did->usagelist[k].UsagePage >= 0xff00) continue; // ignore vendor specific for (j = 0; j < did->maxusagelistlength; j++) { if (did->usagelist[k].UsagePage == did->prevusagelist[j].UsagePage && did->usagelist[k].Usage == did->prevusagelist[j].Usage) break; } if (j == did->maxusagelistlength || did->prevusagelist[j].Usage == 0) { if (rawinput_log & 4) write_log (_T("%d/%d ON\n"), did->usagelist[k].UsagePage, did->usagelist[k].Usage); for (int l = 0; l < did->buttons; l++) { if (did->buttonmappings[l] == did->usagelist[k].Usage) setjoybuttonstate (num, l, 1); } } else { did->prevusagelist[j].Usage = 0; } } for (j = 0; j < did->maxusagelistlength; j++) { if (did->prevusagelist[j].UsagePage >= 0xff00) continue; // ignore vendor specific if (did->prevusagelist[j].Usage) { if (rawinput_log & 4) write_log (_T("%d/%d OFF\n"), did->prevusagelist[j].UsagePage, did->prevusagelist[j].Usage); for (int l = 0; l < did->buttons; l++) { if (did->buttonmappings[l] == did->prevusagelist[j].Usage) setjoybuttonstate (num, l, 0); } } } memcpy (did->prevusagelist, did->usagelist, usagelength * sizeof(USAGE_AND_PAGE)); memset (did->prevusagelist + usagelength, 0, (did->maxusagelistlength - usagelength) * sizeof(USAGE_AND_PAGE)); for (int axisnum = 0; axisnum < did->axles; axisnum++) { ULONG val; int usage = did->axismappings[axisnum]; NTSTATUS status; status = HidP_GetUsageValue (HidP_Input, did->hidvcaps[axisnum].UsagePage, 0, usage, &val, did->hidpreparseddata, rawdata, hid->dwSizeHid); if (status == HIDP_STATUS_SUCCESS) { int data = 0; int digitalrange = 0; HIDP_VALUE_CAPS *vcaps = &did->hidvcaps[axisnum]; int type = did->axistype[axisnum]; int logicalrange = (vcaps->LogicalMax - vcaps->LogicalMin) / 2; uae_u32 mask = hidmask (vcaps->BitSize); int buttonaxistype; if (type == AXISTYPE_POV_X || type == AXISTYPE_POV_Y) { int min = vcaps->LogicalMin; if (vcaps->LogicalMax - min == 7) { if ((val == min + 0 || val == min + 1 || val == min + 7) && type == AXISTYPE_POV_Y) data = -127; if ((val == min + 2 || val == min + 3 || val == min + 1) && type == AXISTYPE_POV_X) data = 127; if ((val == min + 4 || val == min + 5 || val == min + 3) && type == AXISTYPE_POV_Y) data = 127; if ((val == min + 6 || val == min + 7 || val == min + 5) && type == AXISTYPE_POV_X) data = -127; } else { if (val == min + 0 && type == AXISTYPE_POV_Y) data = -127; if (val == min + 1 && type == AXISTYPE_POV_X) data = 127; if (val == min + 2 && type == AXISTYPE_POV_Y) data = 127; if (val == min + 3 && type == AXISTYPE_POV_X) data = -127; } logicalrange = 127; digitalrange = logicalrange / 2; buttonaxistype = type == AXISTYPE_POV_X ? 1 : 2; } else { int v; #if NEGATIVEMINHACK v = extractbits(val, vcaps->BitSize, 0); v -= (vcaps->LogicalMax - vcaps->LogicalMin) / 2; #else v = extractbits(val, vcaps->BitSize, vcaps->LogicalMin < 0); #endif if (v < vcaps->LogicalMin) v = vcaps->LogicalMin; else if (v > vcaps->LogicalMax) v = vcaps->LogicalMax; data = v - logicalrange + (0 - vcaps->LogicalMin); if (rawinput_log & 4) write_log(_T("DEV %d AXIS %d: %d %d (%d - %d) %d %d\n"), num, axisnum, digitalrange, logicalrange, vcaps->LogicalMin, vcaps->LogicalMax, v, data); digitalrange = logicalrange * 2 / 3; if (istest) { if (data < -digitalrange) data = -logicalrange; else if (data > digitalrange) data = logicalrange; else data = 0; } buttonaxistype = -1; } if (data != axisold[num][axisnum] && logicalrange) { //write_log (_T("%d %d: %d->%d %d\n"), num, axisnum, axisold[num][axisnum], data, logicalrange); axisold[num][axisnum] = data; for (j = 0; j < did->buttons; j++) { if (did->buttonaxisparent[j] >= 0 && did->buttonmappings[j] == usage && (did->buttonaxistype[j] == buttonaxistype || buttonaxistype < 0)) { int bstate = -1; int bstate2 = 0; int axistype = did->axistype[j]; if (did->buttonaxisparentdir[j] == 0 && data < -digitalrange) { bstate = j; bstate2 = 1; } else if (did->buttonaxisparentdir[j] != 0 && data > digitalrange) { bstate = j; bstate2 = 1; } else if (data >= -digitalrange && data <= digitalrange) { bstate = j; bstate2 = 0; } if (bstate >= 0 && buttonold[num][bstate] != bstate2) { if (rawinput_log & 4) write_log (_T("[+-] DEV %d AXIS %d: %d %d %d %d (%s)\n"), num, axisnum, digitalrange, data, bstate, bstate2, did->buttonname[bstate]); buttonold[num][bstate] = bstate2; setjoybuttonstate (num, bstate, bstate2); } } } setjoystickstate (num, axisnum, data, logicalrange); } } } } rawdata += hid->dwSizeHid; } } } else if (raw->header.dwType == RIM_TYPEKEYBOARD) { PRAWKEYBOARD rk = &raw->data.keyboard; HANDLE h = raw->header.hDevice; int scancode = rk->MakeCode & 0x7f; int pressed = (rk->Flags & RI_KEY_BREAK) ? 0 : 1; if (rawinput_log & 1) write_log (_T("HANDLE=%x CODE=%x Flags=%x VK=%x MSG=%x EXTRA=%x SC=%x\n"), raw->header.hDevice, rk->MakeCode, rk->Flags, rk->VKey, rk->Message, rk->ExtraInformation, scancode); #ifdef RETROPLATFORM if (rp_isactive ()) return; #endif if (key_swap_hack) { if (scancode == DIK_F11) { scancode = DIK_EQUALS; } else if (scancode == DIK_EQUALS) { scancode = DIK_F11; } } // eat E1 extended keys if (rk->Flags & (RI_KEY_E1)) return; if (scancode == 0) { scancode = MapVirtualKey (rk->VKey, MAPVK_VK_TO_VSC); if (rawinput_log & 1) write_log (_T("VK->CODE: %x\n"), scancode); } if (rk->VKey == 0xff || ((rk->Flags & RI_KEY_E0) && !(winekeyboard && rk->VKey == VK_NUMLOCK))) scancode |= 0x80; if (winekeyboard && rk->VKey == VK_PAUSE) scancode |= 0x80; if (rk->MakeCode == KEYBOARD_OVERRUN_MAKE_CODE) return; if (scancode == 0xaa || scancode == 0) return; if (currprefs.right_control_is_right_win_key && scancode == DIK_RCONTROL) { scancode = DIK_RWIN; } if (!istest) { if (scancode == DIK_SYSRQ) clipboard_disable (!!pressed); if (h == NULL) { // swallow led key fake messages if (currprefs.keyboard_leds[KBLED_NUMLOCKB] > 0 && scancode == DIK_NUMLOCK) return; if (currprefs.keyboard_leds[KBLED_CAPSLOCKB] > 0 && scancode == DIK_CAPITAL) return; if (currprefs.keyboard_leds[KBLED_SCROLLLOCKB] > 0 && scancode == DIK_SCROLL) return; } else { static bool ch; if (pressed) { if (currprefs.keyboard_leds[KBLED_NUMLOCKB] > 0 && scancode == DIK_NUMLOCK) { oldleds ^= KBLED_NUMLOCKM; ch = true; } if (currprefs.keyboard_leds[KBLED_CAPSLOCKB] > 0 && scancode == DIK_CAPITAL) { oldleds ^= KBLED_CAPSLOCKM; ch = true; } if (currprefs.keyboard_leds[KBLED_SCROLLLOCKB] > 0 && scancode == DIK_SCROLL) { oldleds ^= KBLED_SCROLLLOCKM; ch = true; } } else if (ch && isfocus ()) { ch = false; set_leds (newleds); } } } for (num = 0; num < num_keyboard; num++) { did = &di_keyboard[num]; if (did->connection != DIDC_RAW) continue; if (did->acquired) { if (did->rawinput == h) break; } } if (num == num_keyboard) { // find winuae keyboard for (num = 0; num < num_keyboard; num++) { did = &di_keyboard[num]; if (did->connection == DIDC_RAW && did->acquired && did->rawinput == NULL) break; } if (num == num_keyboard) { if (!istest && scancode == DIK_F12 && pressed && isfocus ()) inputdevice_add_inputcode (AKS_ENTERGUI, 1, NULL); return; } } // More complex press/release check because we want to support // keys that never return releases, only presses but also need // handle normal keys that can repeat. #if 0 if (!pressed) return; #endif if (pressed) { // previously pressed key and current press is same key? Repeat. Ignore it. if (scancode == rawprevkey) return; rawprevkey = scancode; if (rawkeystate[scancode] == 2) { // Got press for key that is already pressed. // Must be ignored. It is repeat. rawkeystate[scancode] = 1; return; } rawkeystate[scancode] = 1; } else { rawprevkey = -1; // release without press: ignore if (rawkeystate [scancode] == 0) return; rawkeystate[scancode] = 0; // Got release, if following press is key that // is currently pressed: ignore it, it is repeat. // Mark all currently pressed keys. for (int i = 0; i < sizeof (rawkeystate); i++) { if (rawkeystate[i] == 1) rawkeystate[i] = 2; } } if (istest) { if (pressed && (scancode == DIK_F12)) return; if (scancode == DIK_F12) { inputdevice_testrecord (IDTYPE_KEYBOARD, num, IDEV_WIDGET_BUTTON, 0x101, 1, -1); inputdevice_testrecord (IDTYPE_KEYBOARD, num, IDEV_WIDGET_BUTTON, 0x101, 0, -1); } else { inputdevice_testrecord (IDTYPE_KEYBOARD, num, IDEV_WIDGET_BUTTON, scancode, pressed, -1); } } else { scancode = keyhack (scancode, pressed, num); #if DEBUG_SCANCODE write_log (_T("%02X %d %d\n"), scancode, pressed, isfocus ()); #endif if (scancode < 0) return; if (!isfocus ()) return; if (isfocus () < 2 && currprefs.input_tablet >= TABLET_MOUSEHACK && (currprefs.input_mouse_untrap & MOUSEUNTRAP_MAGIC)) return; if (!mouseactive && !(currprefs.win32_active_input & 1)) { if ((currprefs.win32_guikey <= 0 && scancode == DIK_F12) || (scancode == currprefs.win32_guikey)) { inputdevice_add_inputcode(AKS_ENTERGUI, 1, NULL); } return; } if (pressed) { di_keycodes[num][scancode] = 1; } else { if ((di_keycodes[num][scancode] & 1) && pause_emulation) { di_keycodes[num][scancode] = 2; } else { di_keycodes[num][scancode] = 0; } } if (stopoutput == 0) { my_kbd_handler (num, scancode, pressed, false); } } } } bool is_hid_rawinput(void) { if (no_rawinput & 4) return false; if (!rawinput_enabled_hid && !rawinput_enabled_hid_reset) return false; return true; } static bool match_rawinput(struct didata *didp, const TCHAR *name, HANDLE h) { for (int i = 0; i < MAX_INPUT_DEVICES; i++) { struct didata *did = &didp[i]; if (did->connection != DIDC_RAW) continue; if (!_tcscmp(name, did->configname)) { #if RAWINPUT_DEBUG write_log(_T("- matched: %p -> %p (%s)\n"), did->rawinput, h, name); #endif for (int j = 0; j < raw_handles; j++) { if (rawinputhandles[j] == did->rawinput) { rawinputhandles[j] = h; } } did->rawinput = h; return true; } } return false; } bool handle_rawinput_change(LPARAM lParam, WPARAM wParam) { HANDLE h = (HANDLE)lParam; UINT vtmp; uae_u8 buf[10000]; bool ret = true; #if RAWINPUT_DEBUG PRID_DEVICE_INFO rdi; write_log(_T("WM_INPUT_DEVICE_CHANGE %p %08x\n"), lParam, wParam); #endif for (int i = 0; i < raw_handles; i++) { if (rawinputhandles[i] == h) { #if RAWINPUT_DEBUG write_log(_T("- Already existing\n")); #endif ret = false; } } if (ret) { #if RAWINPUT_DEBUG write_log(_T("- Not found, re-enumerating if no match..\n")); #endif } // existing removed if (wParam == GIDC_REMOVAL && !ret) { #if RAWINPUT_DEBUG write_log(_T("- Existing device removed, re-enumerating..\n")); #endif return true; } if (wParam != GIDC_ARRIVAL) return false; if (GetRawInputDeviceInfo(h, RIDI_DEVICENAME, NULL, &vtmp) == -1) return false; if (vtmp >= sizeof buf) return false; if (GetRawInputDeviceInfo(h, RIDI_DEVICENAME, buf, &vtmp) == -1) return false; TCHAR *dn = (TCHAR*)buf; // name matches? Replace handle, do not re-enumerate if (match_rawinput(di_mouse, dn, h)) return false; if (match_rawinput(di_keyboard, dn, h)) return false; if (match_rawinput(di_joystick, dn, h)) return false; // new device #if RAWINPUT_DEBUG rdi = (PRID_DEVICE_INFO)buf; memset(rdi, 0, sizeof(RID_DEVICE_INFO)); rdi->cbSize = sizeof(RID_DEVICE_INFO); if (GetRawInputDeviceInfo(h, RIDI_DEVICEINFO, NULL, &vtmp) == -1) return false; if (vtmp >= sizeof buf) return false; if (GetRawInputDeviceInfo(h, RIDI_DEVICEINFO, buf, &vtmp) == -1) return false; write_log(_T("Type = %d\n"), rdi->dwType); if (rdi->dwType == RIM_TYPEHID) { RID_DEVICE_INFO_HID *hid = &rdi->hid; write_log(_T("%04x %04x %04x %04x %04x\n"), hid->dwVendorId, hid->dwProductId, hid->dwVersionNumber, hid->usUsage, hid->usUsagePage); } #endif return ret; } void handle_rawinput(LPARAM lParam) { UINT dwSize = 0; BYTE lpb[1000]; RAWINPUT *raw; if (!rawinput_available) return; if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)) >= 0) { if (dwSize <= sizeof(lpb)) { if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) == dwSize) { raw = (RAWINPUT*)lpb; if (!isguiactive() || (inputdevice_istest() && isguiactive())) { handle_rawinput_2 (raw, lParam); } DefRawInputProc(&raw, 1, sizeof(RAWINPUTHEADER)); } else { write_log(_T("GetRawInputData(%d) failed, %d\n"), dwSize, GetLastError ()); } } else { write_log(_T("GetRawInputData() too large buffer %d\n"), dwSize); } } else { write_log(_T("GetRawInputData(-1) failed, %d\n"), GetLastError ()); } } static void unacquire (LPDIRECTINPUTDEVICE8 lpdi, TCHAR *txt) { HRESULT hr; if (lpdi) { hr = IDirectInputDevice8_Unacquire (lpdi); if (FAILED (hr) && hr != DI_NOEFFECT) write_log (_T("unacquire %s failed, %s\n"), txt, DXError (hr)); } } static int acquire (LPDIRECTINPUTDEVICE8 lpdi, TCHAR *txt) { HRESULT hr = DI_OK; if (lpdi) { hr = IDirectInputDevice8_Acquire (lpdi); if (FAILED (hr) && hr != 0x80070005) { write_log (_T("acquire %s failed, %s\n"), txt, DXError (hr)); } } return SUCCEEDED (hr) ? 1 : 0; } static int setcoop (struct didata *did, DWORD mode, TCHAR *txt) { struct AmigaMonitor *mon = &AMonitors[0]; HRESULT hr = DI_OK; HWND hwnd; int test = inputdevice_istest (); if (!test) hwnd = mon->hMainWnd; else hwnd = hGUIWnd; if (did->lpdi) { did->coop = 0; if (!did->coop && hwnd) { hr = IDirectInputDevice8_SetCooperativeLevel (did->lpdi, hwnd, mode); if (FAILED (hr) && hr != E_NOTIMPL) { write_log (_T("setcooperativelevel %s failed, %s\n"), txt, DXError (hr)); } else { did->coop = 1; //write_log (_T("cooperativelevel %s set\n"), txt); } } } return SUCCEEDED (hr) ? 1 : 0; } static void sortdd2 (struct didata *dd, int num, int type) { for (int i = 0; i < num; i++) { struct didata *did1 = &dd[i]; did1->type = type; for (int j = i + 1; j < num; j++) { struct didata *did2 = &dd[j]; did2->type = type; if (did1->priority < did2->priority || (did1->priority == did2->priority && _tcscmp (did1->sortname, did2->sortname) > 0)) { struct didata ddtmp; memcpy (&ddtmp, did1, sizeof ddtmp); memcpy (did1, did2, sizeof ddtmp); memcpy (did2, &ddtmp, sizeof ddtmp); } } } } static void sortdd (struct didata *dd, int num, int type) { sortdd2 (dd, num, type); /* rename duplicate names */ for (int i = 0; i < num; i++) { struct didata *did1 = &dd[i]; for (int j = i + 1; j < num; j++) { struct didata *did2 = &dd[j]; if (!_tcscmp (did1->name, did2->name)) { int cnt = 1; TCHAR tmp[MAX_DPATH], tmp2[MAX_DPATH]; _tcscpy (tmp2, did1->name); for (j = i; j < num; j++) { did2 = &dd[j]; if (!_tcscmp (tmp2, did2->name)) { _stprintf (tmp, _T("%s [%d]"), did2->name, cnt); xfree (did2->name); did2->name = my_strdup (tmp); _stprintf (tmp, _T("%s [%d]"), did2->sortname, cnt); xfree (did2->sortname); did2->sortname = my_strdup (tmp); cnt++; } } break; } } } sortdd2 (dd, num, type); } static int isg (const GUID *g, const GUID *g2, short *dwofs, int v) { if (!memcmp (g, g2, sizeof (GUID))) { *dwofs = v; return 1; } return 0; } static int makesort_joy (const GUID *g, short *dwofs) { if (isg (g, &GUID_XAxis, dwofs, DIJOFS_X)) return -99; if (isg (g, &GUID_YAxis, dwofs, DIJOFS_Y)) return -98; if (isg (g, &GUID_ZAxis, dwofs, DIJOFS_Z)) return -97; if (isg (g, &GUID_RxAxis, dwofs, DIJOFS_RX)) return -89; if (isg (g, &GUID_RyAxis, dwofs, DIJOFS_RY)) return -88; if (isg (g, &GUID_RzAxis, dwofs, DIJOFS_RZ)) return -87; if (isg (g, &GUID_Slider, dwofs, DIJOFS_SLIDER(0))) return -79; if (isg (g, &GUID_Slider, dwofs, DIJOFS_SLIDER(1))) return -78; if (isg (g, &GUID_POV, dwofs, DIJOFS_POV(0))) return -69; if (isg (g, &GUID_POV, dwofs, DIJOFS_POV(1))) return -68; if (isg (g, &GUID_POV, dwofs, DIJOFS_POV(2))) return -67; if (isg (g, &GUID_POV, dwofs, DIJOFS_POV(3))) return -66; return *dwofs; } static int makesort_mouse (const GUID *g, short *dwofs) { if (isg (g, &GUID_XAxis, dwofs, DIMOFS_X)) return -99; if (isg (g, &GUID_YAxis, dwofs, DIMOFS_Y)) return -98; if (isg (g, &GUID_ZAxis, dwofs, DIMOFS_Z)) return -97; return *dwofs; } static BOOL CALLBACK EnumObjectsCallback (const DIDEVICEOBJECTINSTANCE* pdidoi, VOID *pContext) { struct didata *did = (struct didata*)pContext; int i; TCHAR tmp[100]; #if 0 if (pdidoi->dwOfs != DIDFT_GETINSTANCE (pdidoi->dwType)) write_log (_T("%x-%s: %x <> %x\n"), pdidoi->dwType & 0xff, pdidoi->tszName, pdidoi->dwOfs, DIDFT_GETINSTANCE (pdidoi->dwType)); #endif if (pdidoi->dwType & DIDFT_AXIS) { int sort = 0; if (did->axles >= ID_AXIS_TOTAL) return DIENUM_CONTINUE; did->axismappings[did->axles] = DIDFT_GETINSTANCE (pdidoi->dwType); did->axisname[did->axles] = my_strdup (pdidoi->tszName); if (pdidoi->wUsagePage == 1 && (pdidoi->wUsage == 0x30 || pdidoi->wUsage == 0x31)) did->analogstick = true; if (did->type == DID_JOYSTICK) sort = makesort_joy (&pdidoi->guidType, &did->axismappings[did->axles]); else if (did->type == DID_MOUSE) sort = makesort_mouse (&pdidoi->guidType, &did->axismappings[did->axles]); if (sort < 0) { for (i = 0; i < did->axles; i++) { if (did->axissort[i] == sort) { write_log (_T("ignored duplicate '%s'\n"), pdidoi->tszName); return DIENUM_CONTINUE; } } } did->axissort[did->axles] = sort; did->axles++; } if (pdidoi->dwType & DIDFT_POV) { int numpov = 0; if (did->axles + 1 >= ID_AXIS_TOTAL) return DIENUM_CONTINUE; for (i = 0; i < did->axles; i++) { if (did->axistype[i]) { numpov++; i++; } } if (did->type == DID_JOYSTICK) did->axissort[did->axles] = makesort_joy (&pdidoi->guidType, &did->axismappings[did->axles]); else if (did->type == DID_MOUSE) did->axissort[did->axles] = makesort_mouse (&pdidoi->guidType, &did->axismappings[did->axles]); for (i = 0; i < 2; i++) { did->axismappings[did->axles + i] = (uae_s16)DIJOFS_POV(numpov); _stprintf (tmp, _T("%s (%c)"), pdidoi->tszName, i ? 'Y' : 'X'); did->axisname[did->axles + i] = my_strdup (tmp); did->axissort[did->axles + i] = did->axissort[did->axles]; did->axistype[did->axles + i] = i + 1; } did->axles += 2; } if (pdidoi->dwType & DIDFT_BUTTON) { if (did->buttons >= ID_BUTTON_TOTAL && did->type != DID_KEYBOARD) return DIENUM_CONTINUE; TCHAR *bname = did->buttonname[did->buttons] = my_strdup (pdidoi->tszName); if (did->type == DID_JOYSTICK) { //did->buttonmappings[did->buttons] = DIJOFS_BUTTON(DIDFT_GETINSTANCE (pdidoi->dwType)); did->buttonmappings[did->buttons] = DIJOFS_BUTTON(did->buttons); did->buttonsort[did->buttons] = makesort_joy (&pdidoi->guidType, &did->buttonmappings[did->buttons]); } else if (did->type == DID_MOUSE) { //did->buttonmappings[did->buttons] = FIELD_OFFSET(DIMOUSESTATE2, rgbButtons) + DIDFT_GETINSTANCE (pdidoi->dwType); did->buttonmappings[did->buttons] = FIELD_OFFSET(DIMOUSESTATE2, rgbButtons) + did->buttons; did->buttonsort[did->buttons] = makesort_mouse (&pdidoi->guidType, &did->buttonmappings[did->buttons]); } else if (did->type == DID_KEYBOARD) { //did->buttonmappings[did->buttons] = pdidoi->dwOfs; did->buttonmappings[did->buttons] = DIDFT_GETINSTANCE (pdidoi->dwType); } did->buttons++; } return DIENUM_CONTINUE; } static void trimws (TCHAR *s) { /* Delete trailing whitespace. */ int len = uaetcslen(s); while (len > 0 && _tcscspn(s + len - 1, _T("\t \r\n")) == 0) s[--len] = '\0'; } static BOOL di_enumcallback2 (LPCDIDEVICEINSTANCE lpddi, int joy) { struct didata *did; int len, type; TCHAR *typetxt; TCHAR tmp[100]; if (rawinput_enabled_hid && (lpddi->dwDevType & DIDEVTYPE_HID)) { return 1; } type = lpddi->dwDevType & 0xff; if (type == DI8DEVTYPE_MOUSE || type == DI8DEVTYPE_SCREENPOINTER) { did = di_mouse; typetxt = _T("Mouse"); } else if ((type == DI8DEVTYPE_GAMEPAD || type == DI8DEVTYPE_JOYSTICK || type == DI8DEVTYPE_SUPPLEMENTAL || type == DI8DEVTYPE_FLIGHT || type == DI8DEVTYPE_DRIVING || type == DI8DEVTYPE_1STPERSON) || joy) { did = di_joystick; typetxt = _T("Game controller"); } else if (type == DI8DEVTYPE_KEYBOARD) { did = di_keyboard; typetxt = _T("Keyboard"); } else { did = NULL; typetxt = _T("Unknown"); } #if DI_DEBUG write_log (_T("I=%s "), outGUID (&lpddi->guidInstance)); write_log (_T("P=%s\n"), outGUID (&lpddi->guidProduct)); write_log (_T("'%s' '%s' %08X [%s]\n"), lpddi->tszProductName, lpddi->tszInstanceName, lpddi->dwDevType, typetxt); #endif if (did == di_mouse) { if (num_mouse >= MAX_INPUT_DEVICES) return DIENUM_CONTINUE; did += num_mouse; num_mouse++; } else if (did == di_joystick) { if (num_joystick >= MAX_INPUT_DEVICES) return DIENUM_CONTINUE; did += num_joystick; num_joystick++; } else if (did == di_keyboard) { if (num_keyboard >= MAX_INPUT_DEVICES) return DIENUM_CONTINUE; did += num_keyboard; num_keyboard++; } else return DIENUM_CONTINUE; cleardid (did); if (lpddi->tszInstanceName) { len = uaetcslen(lpddi->tszInstanceName) + 5 + 1; did->name = xmalloc (TCHAR, len); _tcscpy (did->name, lpddi->tszInstanceName); } else { did->name = xmalloc (TCHAR, 100); _tcscpy (did->name, _T("[no name]")); } trimws (did->name); _stprintf (tmp, _T("%08X-%04X-%04X-%02X%02X%02X%02X%02X%02X%02X%02X %08X-%04X-%04X-%02X%02X%02X%02X%02X%02X%02X%02X"), lpddi->guidProduct.Data1, lpddi->guidProduct.Data2, lpddi->guidProduct.Data3, lpddi->guidProduct.Data4[0], lpddi->guidProduct.Data4[1], lpddi->guidProduct.Data4[2], lpddi->guidProduct.Data4[3], lpddi->guidProduct.Data4[4], lpddi->guidProduct.Data4[5], lpddi->guidProduct.Data4[6], lpddi->guidProduct.Data4[7], lpddi->guidInstance.Data1, lpddi->guidInstance.Data2, lpddi->guidInstance.Data3, lpddi->guidInstance.Data4[0], lpddi->guidInstance.Data4[1], lpddi->guidInstance.Data4[2], lpddi->guidInstance.Data4[3], lpddi->guidInstance.Data4[4], lpddi->guidInstance.Data4[5], lpddi->guidInstance.Data4[6], lpddi->guidInstance.Data4[7]); did->configname = my_strdup (tmp); trimws (did->configname); did->iguid = lpddi->guidInstance; did->pguid = lpddi->guidProduct; did->sortname = my_strdup (did->name); did->connection = DIDC_DX; if (!memcmp (&did->iguid, &GUID_SysKeyboard, sizeof (GUID)) || !memcmp (&did->iguid, &GUID_SysMouse, sizeof (GUID))) { did->priority = 2; did->superdevice = 1; } return DIENUM_CONTINUE; } static BOOL CALLBACK di_enumcallback (LPCDIDEVICEINSTANCE lpddi, LPVOID dd) { return di_enumcallback2 (lpddi, 0); } static BOOL CALLBACK di_enumcallbackj (LPCDIDEVICEINSTANCE lpddi, LPVOID dd) { return di_enumcallback2 (lpddi, 1); } static void di_dev_free (struct didata *did) { if (did->lpdi) IDirectInputDevice8_Release (did->lpdi); if (did->parjoy != INVALID_HANDLE_VALUE) CloseHandle (did->parjoy); xfree (did->name); xfree (did->sortname); xfree (did->configname); if (did->hidpreparseddata) HidD_FreePreparsedData (did->hidpreparseddata); if (did->rawhidhandle != INVALID_HANDLE_VALUE) CloseHandle(did->rawhidhandle); xfree (did->hidbuffer); xfree (did->hidbufferprev); xfree (did->usagelist); xfree (did->prevusagelist); cleardid(did); } #if 0 #define SAFE_RELEASE(x) if(x) x->Release(); // believe it or not, this is MS example code! BOOL IsXInputDevice(const GUID* pGuidProductFromDirectInput) { IWbemLocator* pIWbemLocator = NULL; IEnumWbemClassObject* pEnumDevices = NULL; IWbemClassObject* pDevices[20] = { 0 }; IWbemServices* pIWbemServices = NULL; BSTR bstrNamespace = NULL; BSTR bstrDeviceID = NULL; BSTR bstrClassName = NULL; DWORD uReturned = 0; bool bIsXinputDevice = false; UINT iDevice = 0; VARIANT var; HRESULT hr; // CoInit if needed hr = CoInitialize(NULL); bool bCleanupCOM = SUCCEEDED(hr); // Create WMI hr = CoCreateInstance(__uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*)&pIWbemLocator); if (FAILED(hr) || pIWbemLocator == NULL) goto LCleanup; bstrNamespace = SysAllocString(L"\\\\.\\root\\cimv2"); if (bstrNamespace == NULL) goto LCleanup; bstrClassName = SysAllocString(L"Win32_PNPEntity"); if (bstrClassName == NULL) goto LCleanup; bstrDeviceID = SysAllocString(L"DeviceID"); if (bstrDeviceID == NULL) goto LCleanup; // Connect to WMI hr = pIWbemLocator->ConnectServer(bstrNamespace, NULL, NULL, 0L, 0L, NULL, NULL, &pIWbemServices); if (FAILED(hr) || pIWbemServices == NULL) goto LCleanup; // Switch security level to IMPERSONATE. CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); hr = pIWbemServices->CreateInstanceEnum(bstrClassName, 0, NULL, &pEnumDevices); if (FAILED(hr) || pEnumDevices == NULL) goto LCleanup; // Loop over all devices for (;; ) { // Get 20 at a time hr = pEnumDevices->Next(10000, 20, pDevices, &uReturned); if (FAILED(hr)) goto LCleanup; if (uReturned == 0) break; for (iDevice = 0; iDevice<uReturned; iDevice++) { // For each device, get its device ID hr = pDevices[iDevice]->Get(bstrDeviceID, 0L, &var, NULL, NULL); if (SUCCEEDED(hr) && var.vt == VT_BSTR && var.bstrVal != NULL) { // Check if the device ID contains "IG_". If it does, then it's an XInput device // This information can not be found from DirectInput if (wcsstr(var.bstrVal, L"IG_")) { // If it does, then get the VID/PID from var.bstrVal DWORD dwPid = 0, dwVid = 0; WCHAR* strVid = wcsstr(var.bstrVal, L"VID_"); if (strVid && swscanf(strVid, L"VID_%4X", &dwVid) != 1) dwVid = 0; WCHAR* strPid = wcsstr(var.bstrVal, L"PID_"); if (strPid && swscanf(strPid, L"PID_%4X", &dwPid) != 1) dwPid = 0; // Compare the VID/PID to the DInput device DWORD dwVidPid = MAKELONG(dwVid, dwPid); if (pGuidProductFromDirectInput && dwVidPid == pGuidProductFromDirectInput->Data1) { bIsXinputDevice = true; goto LCleanup; } } } SAFE_RELEASE(pDevices[iDevice]); } } LCleanup: if (bstrNamespace) SysFreeString(bstrNamespace); if (bstrDeviceID) SysFreeString(bstrDeviceID); if (bstrClassName) SysFreeString(bstrClassName); for (iDevice = 0; iDevice<20; iDevice++) SAFE_RELEASE(pDevices[iDevice]); SAFE_RELEASE(pEnumDevices); SAFE_RELEASE(pIWbemLocator); SAFE_RELEASE(pIWbemServices); if (bCleanupCOM) CoUninitialize(); return bIsXinputDevice; } #endif static int di_do_init (void) { HRESULT hr; int i; num_mouse = num_joystick = num_keyboard = 0; for (i = 0; i < MAX_INPUT_DEVICES; i++) { di_dev_free (&di_joystick[i]); di_dev_free (&di_mouse[i]); di_dev_free (&di_keyboard[i]); } if (rawinput_enabled_hid_reset) { rawinput_enabled_hid = rawinput_enabled_hid_reset; rawinput_enabled_hid_reset = 0; } #if 0 IsXInputDevice(NULL); #endif write_log (_T("RawInput enumeration..\n")); if (!initialize_rawinput ()) rawinput_enabled_hid = 0; if (!rawinput_decided) { if (!(no_rawinput & 1)) rawinput_enabled_keyboard = true; if (!(no_rawinput & 2)) rawinput_enabled_mouse = true; rawinput_decided = true; } if (!rawhid_found) { // didn't find anything but was enabled? Try again next time. rawinput_enabled_hid_reset = rawinput_enabled_hid; rawinput_enabled_hid = 0; } if (!no_directinput || !rawinput_enabled_keyboard || !rawinput_enabled_mouse) { hr = DirectInput8Create (hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID *)&g_lpdi, NULL); if (FAILED (hr)) { write_log (_T("DirectInput8Create failed, %s\n"), DXError (hr)); } else { if (dinput_enum_all) { write_log (_T("DirectInput enumeration..\n")); g_lpdi->EnumDevices (DI8DEVCLASS_ALL, di_enumcallback, 0, DIEDFL_ATTACHEDONLY); } else { if (!rawinput_enabled_keyboard) { write_log (_T("DirectInput enumeration.. Keyboards..\n")); g_lpdi->EnumDevices (DI8DEVCLASS_KEYBOARD, di_enumcallback, 0, DIEDFL_ATTACHEDONLY); } if (!rawinput_enabled_mouse) { write_log (_T("DirectInput enumeration.. Pointing devices..\n")); g_lpdi->EnumDevices (DI8DEVCLASS_POINTER, di_enumcallback, 0, DIEDFL_ATTACHEDONLY); } if (!no_directinput) { write_log (_T("DirectInput enumeration.. Game controllers..\n")); g_lpdi->EnumDevices (DI8DEVCLASS_GAMECTRL, di_enumcallbackj, 0, DIEDFL_ATTACHEDONLY); } } } } if (!no_windowsmouse) { write_log (_T("Windowsmouse initialization..\n")); initialize_windowsmouse (); } write_log (_T("Catweasel joymouse initialization..\n")); initialize_catweasel (); // write_log (_T("Parallel joystick port initialization..\n")); // initialize_parjoyport (); write_log (_T("wintab tablet initialization..\n")); initialize_tablet (); write_log (_T("end\n")); sortdd (di_joystick, num_joystick, DID_JOYSTICK); sortdd (di_mouse, num_mouse, DID_MOUSE); sortdd (di_keyboard, num_keyboard, DID_KEYBOARD); for (int i = 0; i < num_joystick; i++) { write_log(_T("M %02d: '%s' (%s)\n"), i, di_mouse[i].name, di_mouse[i].configname); } for (int i = 0; i < num_joystick; i++) { write_log(_T("J %02d: '%s' (%s)\n"), i, di_joystick[i].name, di_joystick[i].configname); } for (int i = 0; i < num_keyboard; i++) { write_log(_T("K %02d: '%s' (%s)\n"), i, di_keyboard[i].name, di_keyboard[i].configname); } return 1; } static int di_init (void) { if (dd_inited++ > 0) return 1; if (!di_do_init ()) return 0; return 1; } static void di_free (void) { int i; if (dd_inited == 0) return; dd_inited--; if (dd_inited > 0) return; if (g_lpdi) IDirectInput8_Release (g_lpdi); g_lpdi = 0; for (i = 0; i < MAX_INPUT_DEVICES; i++) { di_dev_free (&di_joystick[i]); di_dev_free (&di_mouse[i]); di_dev_free (&di_keyboard[i]); } } static int get_mouse_num (void) { return num_mouse; } static TCHAR *get_mouse_friendlyname (int mouse) { return di_mouse[mouse].name; } static TCHAR *get_mouse_uniquename (int mouse) { return di_mouse[mouse].configname; } static int get_mouse_widget_num (int mouse) { return di_mouse[mouse].axles + di_mouse[mouse].buttons; } static int get_mouse_widget_first (int mouse, int type) { switch (type) { case IDEV_WIDGET_BUTTON: return di_mouse[mouse].axles; case IDEV_WIDGET_AXIS: return 0; case IDEV_WIDGET_BUTTONAXIS: return di_mouse[mouse].axles + di_mouse[mouse].buttons_real; } return -1; } static int get_mouse_widget_type (int mouse, int num, TCHAR *name, uae_u32 *code) { struct didata *did = &di_mouse[mouse]; int axles = did->axles; int buttons = did->buttons; int realbuttons = did->buttons_real; if (num >= axles + realbuttons && num < axles + buttons) { if (name) _tcscpy (name, did->buttonname[num - axles]); return IDEV_WIDGET_BUTTONAXIS; } else if (num >= axles && num < axles + realbuttons) { if (name) _tcscpy (name, did->buttonname[num - axles]); return IDEV_WIDGET_BUTTON; } else if (num < axles) { if (name) _tcscpy (name, did->axisname[num]); return IDEV_WIDGET_AXIS; } return IDEV_WIDGET_NONE; } static int init_mouse (void) { int i; LPDIRECTINPUTDEVICE8 lpdi; HRESULT hr; struct didata *did; if (mouse_inited) return 1; di_init (); mouse_inited = 1; for (i = 0; i < num_mouse; i++) { did = &di_mouse[i]; if (did->connection == DIDC_DX) { hr = g_lpdi->CreateDevice (did->iguid, &lpdi, NULL); if (SUCCEEDED (hr)) { hr = IDirectInputDevice8_SetDataFormat (lpdi, &c_dfDIMouse2); IDirectInputDevice8_EnumObjects (lpdi, EnumObjectsCallback, (void*)did, DIDFT_ALL); fixbuttons (did); fixthings_mouse (did); sortobjects (did); did->lpdi = lpdi; } else { write_log (_T("mouse %d CreateDevice failed, %s\n"), i, DXError (hr)); } } } return 1; } static void close_mouse (void) { int i; if (!mouse_inited) return; mouse_inited = 0; for (i = 0; i < num_mouse; i++) di_dev_free (&di_mouse[i]); supermouse = normalmouse = rawmouse = winmouse = 0; di_free (); } static int acquire_mouse (int num, int flags) { DIPROPDWORD dipdw; HRESULT hr; if (num < 0) { return 1; } struct didata *did = &di_mouse[num]; if (did->connection == DIDC_NONE) return 0; LPDIRECTINPUTDEVICE8 lpdi = did->lpdi; unacquire (lpdi, _T("mouse")); did->acquireattempts = MAX_ACQUIRE_ATTEMPTS; if (did->connection == DIDC_DX && lpdi) { setcoop (&di_mouse[num], flags ? (DISCL_FOREGROUND | DISCL_EXCLUSIVE) : (DISCL_BACKGROUND | DISCL_NONEXCLUSIVE), _T("mouse")); dipdw.diph.dwSize = sizeof (DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof (DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = DI_BUFFER; hr = IDirectInputDevice8_SetProperty (lpdi, DIPROP_BUFFERSIZE, &dipdw.diph); if (FAILED (hr)) write_log (_T("mouse setpropertry failed, %s\n"), DXError (hr)); did->acquired = acquire (lpdi, _T("mouse")) ? 1 : -1; } else { did->acquired = 1; } if (did->acquired > 0) { if (did->rawinput) { rawmouse++; } else if (did->superdevice) { supermouse++; } else if (did->wininput == 1) { winmouse++; winmousenumber = num; } else if (did->wininput == 2) { lightpen++; lightpennumber = num; } else { normalmouse++; } } return did->acquired > 0 ? 1 : 0; } static void unacquire_mouse (int num) { if (num < 0) { return; } struct didata *did = &di_mouse[num]; if (did->connection == DIDC_NONE) return; unacquire (did->lpdi, _T("mouse")); if (did->acquired > 0) { if (did->rawinput) { rawmouse--; } else if (did->superdevice) { supermouse--; } else if (did->wininput == 1) { winmouse--; } else if (did->wininput == 2) { lightpen--; } else { normalmouse--; } did->acquired = 0; } } static void read_mouse (void) { DIDEVICEOBJECTDATA didod[DI_BUFFER]; DWORD elements; HRESULT hr; int i, j, k; int fs = isfullscreen () > 0 ? 1 : 0; int istest = inputdevice_istest (); if (IGNOREEVERYTHING) return; for (i = 0; i < MAX_INPUT_DEVICES; i++) { struct didata *did = &di_mouse[i]; LPDIRECTINPUTDEVICE8 lpdi = did->lpdi; if (!did->acquired) continue; if (did->connection == DIDC_CAT) { if (getmousestate (i)) { int cx, cy, cbuttons; if (catweasel_read_mouse (did->catweasel, &cx, &cy, &cbuttons)) { if (cx) setmousestate (i, 0, cx, 0); if (cy) setmousestate (i, 1, cy, 0); setmousebuttonstate (i, 0, cbuttons & 8); setmousebuttonstate (i, 1, cbuttons & 4); setmousebuttonstate (i, 2, cbuttons & 2); } } continue; } if (!lpdi || did->connection != DIDC_DX) continue; if (did->acquireattempts <= 0) continue; elements = DI_BUFFER; hr = IDirectInputDevice8_GetDeviceData (lpdi, sizeof (DIDEVICEOBJECTDATA), didod, &elements, 0); if (SUCCEEDED (hr) || hr == DI_BUFFEROVERFLOW) { if (supermouse && !did->superdevice) continue; for (j = 0; j < elements; j++) { int dimofs = didod[j].dwOfs; int data = didod[j].dwData; int state = (data & 0x80) ? 1 : 0; if (rawinput_log & 8) write_log (_T("MOUSE: %d OFF=%d DATA=%d STATE=%d\n"), i, dimofs, data, state); if (istest || isfocus () > 0) { for (k = 0; k < did->axles; k++) { if (did->axismappings[k] == dimofs) { if (istest) { static time_t ot; time_t t = time (NULL); if (t != ot && t != ot + 1) { if (data > 7 || data < -7) setmousestate (i, k, data, 0); } } else { setmousestate (i, k, data, 0); } } } for (k = 0; k < did->buttons; k++) { if (did->buttonmappings[k] == dimofs) { if (did->buttonaxisparent[k] >= 0) { int dir = did->buttonaxisparentdir[k]; int bstate = 0; if (dir) bstate = data > 0 ? 1 : 0; else bstate = data < 0 ? 1 : 0; if (bstate) setmousebuttonstate (i, k, -1); } else { #ifdef SINGLEFILE if (k == 0) uae_quit (); #endif if (((currprefs.input_mouse_untrap & MOUSEUNTRAP_MIDDLEBUTTON) && k != 2) || !(currprefs.input_mouse_untrap & MOUSEUNTRAP_MIDDLEBUTTON) || istest) setmousebuttonstate (i, k, state); } } } } if (!istest && isfocus () && (currprefs.input_mouse_untrap & MOUSEUNTRAP_MIDDLEBUTTON) && dimofs == DIMOFS_BUTTON2 && state) { if ((isfullscreen() < 0 && currprefs.win32_minimize_inactive) || isfullscreen() > 0) minimizewindow(0); if (mouseactive) setmouseactive(0, 0); } } } else if (hr == DIERR_INPUTLOST) { if (!acquire (lpdi, _T("mouse"))) did->acquireattempts--; } else if (did->acquired && hr == DIERR_NOTACQUIRED) { if (!acquire (lpdi, _T("mouse"))) did->acquireattempts--; } IDirectInputDevice8_Poll (lpdi); } } static int get_mouse_flags (int num) { if (!rawinput_enabled_mouse && !num) return 1; if (di_mouse[num].rawinput || !rawinput_enabled_mouse) return 0; if (di_mouse[num].catweasel) return 0; return 1; } struct inputdevice_functions inputdevicefunc_mouse = { init_mouse, close_mouse, acquire_mouse, unacquire_mouse, read_mouse, get_mouse_num, get_mouse_friendlyname, get_mouse_uniquename, get_mouse_widget_num, get_mouse_widget_type, get_mouse_widget_first, get_mouse_flags }; static int get_kb_num (void) { return num_keyboard; } static TCHAR *get_kb_friendlyname (int kb) { return di_keyboard[kb].name; } static TCHAR *get_kb_uniquename (int kb) { return di_keyboard[kb].configname; } static int get_kb_widget_num (int kb) { return di_keyboard[kb].buttons; } static int get_kb_widget_first (int kb, int type) { return 0; } static int get_kb_widget_type (int kb, int num, TCHAR *name, uae_u32 *code) { if (name) { if (di_keyboard[kb].buttonname[num]) _tcscpy (name, di_keyboard[kb].buttonname[num]); else name[0] = 0; } if (code) { *code = di_keyboard[kb].buttonmappings[num]; } return IDEV_WIDGET_KEY; } static int init_kb (void) { int i; LPDIRECTINPUTDEVICE8 lpdi; DIPROPDWORD dipdw; HRESULT hr; if (keyboard_inited) return 1; di_init (); originalleds = -1; keyboard_inited = 1; for (i = 0; i < num_keyboard; i++) { struct didata *did = &di_keyboard[i]; if (did->connection == DIDC_DX) { hr = g_lpdi->CreateDevice (did->iguid, &lpdi, NULL); if (SUCCEEDED (hr)) { hr = lpdi->SetDataFormat (&c_dfDIKeyboard); if (FAILED (hr)) write_log (_T("keyboard setdataformat failed, %s\n"), DXError (hr)); memset (&dipdw, 0, sizeof (dipdw)); dipdw.diph.dwSize = sizeof (DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof (DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = DI_KBBUFFER; hr = lpdi->SetProperty (DIPROP_BUFFERSIZE, &dipdw.diph); if (FAILED (hr)) write_log (_T("keyboard setpropertry failed, %s\n"), DXError (hr)); lpdi->EnumObjects (EnumObjectsCallback, did, DIDFT_ALL); sortobjects (did); did->lpdi = lpdi; } else write_log (_T("keyboard CreateDevice failed, %s\n"), DXError (hr)); } } keyboard_german = 0; if ((LOWORD(GetKeyboardLayout (0)) & 0x3ff) == 7) keyboard_german = 1; return 1; } static void close_kb (void) { int i; if (keyboard_inited == 0) return; keyboard_inited = 0; for (i = 0; i < num_keyboard; i++) di_dev_free (&di_keyboard[i]); superkb = normalkb = rawkb = 0; di_free (); } static uae_u32 kb_do_refresh; int ispressed (int key) { if (key < 0 || key > 255) return 0; int i; for (i = 0; i < MAX_INPUT_DEVICES; i++) { if (di_keycodes[i][key] & 1) return 1; } return 0; } void release_keys(void) { for (int j = 0; j < MAX_INPUT_DEVICES; j++) { for (int i = 0; i < MAX_KEYCODES; i++) { if (di_keycodes[j][i]) { #if DEBUG_SCANCODE write_log(_T("release %d:%02x:%02x\n"), j, di_keycodes[j][i], i); #endif di_keycodes[j][i] = 0; my_kbd_handler(j, i, 0, true); } } } memset (rawkeystate, 0, sizeof rawkeystate); rawprevkey = -1; } static void flushmsgpump (void) { MSG msg; while (PeekMessage (&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage (&msg); DispatchMessage (&msg); } } static int acquire_kb (int num, int flags) { if (num < 0) { flushmsgpump(); if (currprefs.keyboard_leds_in_use) { //write_log (_T("***********************acquire_kb_led\n")); if (!currprefs.win32_kbledmode) { if (DefineDosDevice (DDD_RAW_TARGET_PATH, _T("Kbd"), _T("\\Device\\KeyboardClass0"))) { kbhandle = CreateFile (_T("\\\\.\\Kbd"), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (kbhandle == INVALID_HANDLE_VALUE) { write_log (_T("kbled: CreateFile failed, error %d\n"), GetLastError()); currprefs.win32_kbledmode = 1; } } else { currprefs.win32_kbledmode = 1; write_log (_T("kbled: DefineDosDevice failed, error %d\n"), GetLastError()); } } oldleds = get_leds (); if (originalleds == -1) { originalleds = oldleds; //write_log (_T("stored %08x -> %08x\n"), originalleds, newleds); } set_leds (newleds); } return 1; } struct didata *did = &di_keyboard[num]; if (did->connection == DIDC_NONE) return 0; LPDIRECTINPUTDEVICE8 lpdi = did->lpdi; unacquire (lpdi, _T("keyboard")); did->acquireattempts = MAX_ACQUIRE_ATTEMPTS; //lock_kb (); setcoop (did, DISCL_NOWINKEY | DISCL_FOREGROUND | DISCL_EXCLUSIVE, _T("keyboard")); kb_do_refresh = ~0; did->acquired = -1; if (acquire (lpdi, _T("keyboard"))) { if (did->rawinput) rawkb++; else if (did->superdevice) superkb++; else normalkb++; did->acquired = 1; } return did->acquired > 0 ? 1 : 0; } static void unacquire_kb (int num) { if (num < 0) { if (currprefs.keyboard_leds_in_use) { //write_log (_T("*********************** unacquire_kb_led\n")); if (originalleds != -1) { //write_log (_T("restored %08x -> %08x\n"), oldleds, originalleds); set_leds (originalleds); originalleds = -1; flushmsgpump (); } if (kbhandle != INVALID_HANDLE_VALUE) { CloseHandle (kbhandle); DefineDosDevice (DDD_REMOVE_DEFINITION, _T("Kbd"), NULL); kbhandle = INVALID_HANDLE_VALUE; } } return; } struct didata *did = &di_keyboard[num]; if (did->connection == DIDC_NONE) return; LPDIRECTINPUTDEVICE8 lpdi = did->lpdi; unacquire (lpdi, _T("keyboard")); if (did->acquired > 0) { if (did->rawinput) rawkb--; else if (did->superdevice) superkb--; else normalkb--; did->acquired = 0; } } static int refresh_kb (LPDIRECTINPUTDEVICE8 lpdi, int num) { HRESULT hr; int i; uae_u8 kc[256]; hr = IDirectInputDevice8_GetDeviceState (lpdi, sizeof (kc), kc); if (SUCCEEDED (hr)) { for (i = 0; i < sizeof (kc); i++) { if (i == 0x80) /* USB KB led causes this, better ignore it */ continue; if (kc[i] & 0x80) kc[i] = 1; else kc[i] = 0; if (kc[i] != (di_keycodes[num][i] & 1)) { write_log (_T("%d: %02X -> %d\n"), num, i, kc[i]); di_keycodes[num][i] = kc[i]; my_kbd_handler (num, i, kc[i], true); } } } else if (hr == DIERR_INPUTLOST) { acquire_kb (num, 0); IDirectInputDevice8_Poll (lpdi); return 0; } IDirectInputDevice8_Poll (lpdi); return 1; } static void read_kb (void) { DIDEVICEOBJECTDATA didod[DI_KBBUFFER]; DWORD elements; HRESULT hr; LPDIRECTINPUTDEVICE8 lpdi; int i, j; int istest = inputdevice_istest (); if (IGNOREEVERYTHING) return; if (originalleds != -1) update_leds (); for (i = 0; i < MAX_INPUT_DEVICES; i++) { struct didata *did = &di_keyboard[i]; if (!did->acquired) continue; if (istest == 0 && isfocus () == 0) { if (did->acquired > 0) unacquire_kb (i); continue; } lpdi = did->lpdi; if (!lpdi) continue; if (kb_do_refresh & (1 << i)) { if (!refresh_kb (lpdi, i)) continue; kb_do_refresh &= ~(1 << i); } if (did->acquireattempts <= 0) continue; elements = DI_KBBUFFER; hr = IDirectInputDevice8_GetDeviceData (lpdi, sizeof (DIDEVICEOBJECTDATA), didod, &elements, 0); if ((SUCCEEDED (hr) || hr == DI_BUFFEROVERFLOW) && (isfocus () || istest)) { for (j = 0; j < elements; j++) { int scancode = didod[j].dwOfs; int pressed = (didod[j].dwData & 0x80) ? 1 : 0; //write_log (_T("%d: %02X %d\n"), j, scancode, pressed); if (currprefs.right_control_is_right_win_key && scancode == DIK_RCONTROL) scancode = DIK_RWIN; if (!istest) scancode = keyhack (scancode, pressed, i); if (scancode < 0) continue; if (pressed) { di_keycodes[i][scancode] = 1; } else { if ((di_keycodes[i][scancode] & 1) && pause_emulation) { di_keycodes[i][scancode] = 2; } else { di_keycodes[i][scancode] = 0; } } if (istest) { if (pressed && (scancode == DIK_F12)) return; if (scancode == DIK_F12) { inputdevice_testrecord (IDTYPE_KEYBOARD, i, IDEV_WIDGET_BUTTON, 0x101, 1, -1); inputdevice_testrecord (IDTYPE_KEYBOARD, i, IDEV_WIDGET_BUTTON, 0x101, 0, -1); } else { inputdevice_testrecord (IDTYPE_KEYBOARD, i, IDEV_WIDGET_BUTTON, scancode, pressed, -1); } } else { if (stopoutput == 0) my_kbd_handler (i, scancode, pressed, false); } } } else if (hr == DIERR_INPUTLOST) { if (!acquire_kb (i, 0)) did->acquireattempts--; kb_do_refresh |= 1 << i; } else if (did->acquired && hr == DIERR_NOTACQUIRED) { if (!acquire_kb (i, 0)) did->acquireattempts--; } IDirectInputDevice8_Poll (lpdi); } #ifdef CATWEASEL if (isfocus() || istest) { uae_u8 kc; if (stopoutput == 0 && catweasel_read_keyboard (&kc)) inputdevice_do_keyboard (kc & 0x7f, kc & 0x80); } #endif } void wait_keyrelease (void) { stopoutput++; #if 0 int i, j, maxcount = 10, found; while (maxcount-- > 0) { read_kb (); found = 0; for (j = 0; j < MAX_INPUT_DEVICES; j++) { for (i = 0; i < MAX_KEYCODES; i++) { if (di_keycodes[j][i]) found = 1; } } if (!found) break; sleep_millis (10); } #endif release_keys (); #if 0 for (;;) { int ok = 0, nok = 0; for (i = 0; i < MAX_INPUT_DEVICES; i++) { struct didata *did = &di_mouse[i]; DIMOUSESTATE dis; LPDIRECTINPUTDEVICE8 lpdi = did->lpdi; HRESULT hr; int j; if (!lpdi) continue; nok++; hr = IDirectInputDevice8_GetDeviceState (lpdi, sizeof (dis), &dis); if (SUCCEEDED (hr)) { for (j = 0; j < 4; j++) { if (dis.rgbButtons[j] & 0x80) break; } if (j == 4) ok++; } else { ok++; } } if (ok == nok) break; sleep_millis (10); } #endif stopoutput--; } static int get_kb_flags (int num) { return 0; } struct inputdevice_functions inputdevicefunc_keyboard = { init_kb, close_kb, acquire_kb, unacquire_kb, read_kb, get_kb_num, get_kb_friendlyname, get_kb_uniquename, get_kb_widget_num, get_kb_widget_type, get_kb_widget_first, get_kb_flags }; static int get_joystick_num (void) { return num_joystick; } static int get_joystick_widget_num (int joy) { return di_joystick[joy].axles + di_joystick[joy].buttons; } static int get_joystick_widget_type (int joy, int num, TCHAR *name, uae_u32 *code) { struct didata *did = &di_joystick[joy]; if (num >= did->axles + did->buttons_real && num < did->axles + did->buttons) { if (name) _tcscpy (name, did->buttonname[num - did->axles]); return IDEV_WIDGET_BUTTONAXIS; } else if (num >= did->axles && num < did->axles + did->buttons_real) { if (name) _tcscpy (name, did->buttonname[num - did->axles]); return IDEV_WIDGET_BUTTON; } else if (num < di_joystick[joy].axles) { if (name) _tcscpy (name, did->axisname[num]); return IDEV_WIDGET_AXIS; } return IDEV_WIDGET_NONE; } static int get_joystick_widget_first (int joy, int type) { switch (type) { case IDEV_WIDGET_BUTTON: return di_joystick[joy].axles; case IDEV_WIDGET_AXIS: return 0; case IDEV_WIDGET_BUTTONAXIS: return di_joystick[joy].axles + di_joystick[joy].buttons_real; } return -1; } static TCHAR *get_joystick_friendlyname (int joy) { return di_joystick[joy].name; } static TCHAR *get_joystick_uniquename (int joy) { return di_joystick[joy].configname; } static void read_joystick (void) { DIDEVICEOBJECTDATA didod[DI_BUFFER]; LPDIRECTINPUTDEVICE8 lpdi; DWORD elements; HRESULT hr; int i, j, k; int istest = inputdevice_istest (); if (IGNOREEVERYTHING) return; #ifdef RETROPLATFORM if (rp_isactive ()) return; #endif if (!istest && !mouseactive && !(currprefs.win32_active_input & 4)) { return; } for (i = 0; i < MAX_INPUT_DEVICES; i++) { struct didata *did = &di_joystick[i]; if (!did->acquired) continue; if (did->connection == DIDC_CAT) { if (getjoystickstate (i) && (isfocus () || istest)) { /* only read CW state if it is really needed */ uae_u8 cdir, cbuttons; if (catweasel_read_joystick (&cdir, &cbuttons)) { cdir >>= did->catweasel * 4; cbuttons >>= did->catweasel * 4; setjoystickstate (i, 0, !(cdir & 1) ? 1 : !(cdir & 2) ? -1 : 0, 0); setjoystickstate (i, 1, !(cdir & 4) ? 1 : !(cdir & 8) ? -1 : 0, 0); setjoybuttonstate (i, 0, cbuttons & 8); setjoybuttonstate (i, 1, cbuttons & 4); setjoybuttonstate (i, 2, cbuttons & 2); } } continue; } else if (did->connection == DIDC_PARJOY) { DWORD ret; PAR_QUERY_INFORMATION inf; ret = 0; if (DeviceIoControl (did->parjoy, IOCTL_PAR_QUERY_INFORMATION, NULL, 0, &inf, sizeof inf, &ret, NULL)) { write_log (_T("PARJOY: IOCTL_PAR_QUERY_INFORMATION = %u\n"), GetLastError ()); } else { if (inf.Status != did->oldparjoystatus.Status) { write_log (_T("PARJOY: %08x\n"), inf.Status); did->oldparjoystatus.Status = inf.Status; } } continue; #if 0 } else if (did->connection == DIDC_RAW) { bool changedreport = true; while ((isfocus () || istest) && changedreport) { DWORD readbytes; changedreport = false; if (!did->hidread) { DWORD ret; DWORD readlen = did->hidcaps.InputReportByteLength; did->hidbuffer[0] = 0; ret = ReadFile (did->hidhandle, did->hidbuffer, readlen, NULL, &did->hidol); if (ret || (ret == 0 && GetLastError () == ERROR_IO_PENDING)) did->hidread = true; } if (did->hidread && GetOverlappedResult (did->hidhandle, &did->hidol, &readbytes, FALSE)) { did->hidread = false; changedreport = memcmp (did->hidbuffer, did->hidbufferprev, readbytes) != 0; memcpy (did->hidbufferprev, did->hidbuffer, readbytes); DWORD usagelength = did->maxusagelistlength; if (changedreport) write_log (_T("%02x%02x%02x%02x%02x%02x%02x\n"), (uae_u8)did->hidbuffer[0], (uae_u8)did->hidbuffer[1], (uae_u8)did->hidbuffer[2], (uae_u8)did->hidbuffer[3], (uae_u8)did->hidbuffer[4], (uae_u8)did->hidbuffer[5], (uae_u8)did->hidbuffer[6]); if (HidP_GetUsagesEx (HidP_Input, 0, did->usagelist, &usagelength, did->hidpreparseddata, did->hidbuffer, readbytes) == HIDP_STATUS_SUCCESS) { for (k = 0; k < usagelength; k++) { for (j = 0; j < did->maxusagelistlength; j++) { if (did->usagelist[k].UsagePage == did->prevusagelist[j].UsagePage && did->usagelist[k].Usage == did->prevusagelist[j].Usage) break; } if (j == did->maxusagelistlength || did->prevusagelist[j].Usage == 0) { write_log (_T("%d/%d ON\n"), did->usagelist[k].UsagePage, did->usagelist[k].Usage); } else { did->prevusagelist[j].Usage = 0; } } for (j = 0; j < did->maxusagelistlength; j++) { if (did->prevusagelist[j].Usage) { write_log (_T("%d/%d OFF\n"), did->prevusagelist[j].UsagePage, did->prevusagelist[j].Usage); } } memcpy (did->prevusagelist, did->usagelist, usagelength * sizeof(USAGE_AND_PAGE)); memset (did->prevusagelist + usagelength, 0, (did->maxusagelistlength - usagelength) * sizeof(USAGE_AND_PAGE)); } } } #endif } lpdi = did->lpdi; if (!lpdi || did->connection != DIDC_DX) continue; if (did->acquireattempts <= 0) continue; elements = DI_BUFFER; hr = IDirectInputDevice8_GetDeviceData (lpdi, sizeof (DIDEVICEOBJECTDATA), didod, &elements, 0); if ((SUCCEEDED (hr) || hr == DI_BUFFEROVERFLOW) && (isfocus () || istest || (currprefs.win32_inactive_input & 4))) { for (j = 0; j < elements; j++) { int dimofs = didod[j].dwOfs; int data = didod[j].dwData; int data2 = data; int state = (data & 0x80) ? 1 : 0; data -= 32768; for (k = 0; k < did->buttons; k++) { if (did->buttonaxisparent[k] >= 0 && did->buttonmappings[k] == dimofs) { int bstate = -1; int axis = did->buttonaxisparent[k]; int dir = did->buttonaxisparentdir[k]; if (did->axistype[axis] == 1) { if (!dir) bstate = (data2 >= 20250 && data2 <= 33750) ? 1 : 0; else bstate = (data2 >= 2250 && data2 <= 15750) ? 1 : 0; } else if (did->axistype[axis] == 2) { if (!dir) bstate = ((data2 >= 29250 && data2 <= 33750) || (data2 >= 0 && data2 <= 6750)) ? 1 : 0; else bstate = (data2 >= 11250 && data2 <= 24750) ? 1 : 0; } else if (did->axistype[axis] == 0) { if (dir) bstate = data > 20000 ? 1 : 0; else bstate = data < -20000 ? 1 : 0; } if (bstate >= 0 && axisold[i][k] != bstate) { setjoybuttonstate (i, k, bstate); axisold[i][k] = bstate; if (rawinput_log & 8) write_log (_T("AB:NUM=%d OFF=%d AXIS=%d DIR=%d NAME=%s VAL=%d STATE=%d BS=%d\n"), k, dimofs, axis, dir, did->buttonname[k], data, state, bstate); } } else if (did->buttonaxisparent[k] < 0 && did->buttonmappings[k] == dimofs) { if (rawinput_log & 8) write_log (_T("B:NUM=%d OFF=%d NAME=%s VAL=%d STATE=%d\n"), k, dimofs, did->buttonname[k], data, state); setjoybuttonstate (i, k, state); } } for (k = 0; k < did->axles; k++) { if (did->axismappings[k] == dimofs) { if (did->axistype[k] == 1) { setjoystickstate (i, k, (data2 >= 20250 && data2 <= 33750) ? -1 : (data2 >= 2250 && data2 <= 15750) ? 1 : 0, 1); } else if (did->axistype[k] == 2) { setjoystickstate (i, k, ((data2 >= 29250 && data2 <= 33750) || (data2 >= 0 && data2 <= 6750)) ? -1 : (data2 >= 11250 && data2 <= 24750) ? 1 : 0, 1); if (rawinput_log & 8) write_log (_T("P:NUM=%d OFF=%d NAME=%s VAL=%d\n"), k, dimofs, did->axisname[k], data2); } else if (did->axistype[k] == 0) { if (rawinput_log & 8) { if (data < -20000 || data > 20000) write_log (_T("A:NUM=%d OFF=%d NAME=%s VAL=%d\n"), k, dimofs, did->axisname[k], data); } if (istest) { if (data < -20000) data = -20000; else if (data > 20000) data = 20000; else data = 0; } if (axisold[i][k] != data) { setjoystickstate (i, k, data, 32767); axisold[i][k] = data; } } } } } } else if (hr == DIERR_INPUTLOST) { if (!acquire (lpdi, _T("joystick"))) did->acquireattempts--; } else if (did->acquired && hr == DIERR_NOTACQUIRED) { if (!acquire (lpdi, _T("joystick"))) did->acquireattempts--; } IDirectInputDevice8_Poll (lpdi); } } static int init_joystick (void) { int i; LPDIRECTINPUTDEVICE8 lpdi; HRESULT hr; struct didata *did; if (joystick_inited) return 1; di_init (); joystick_inited = 1; for (i = 0; i < num_joystick; i++) { did = &di_joystick[i]; if (did->connection == DIDC_DX) { hr = g_lpdi->CreateDevice (did->iguid, &lpdi, NULL); if (SUCCEEDED (hr)) { hr = lpdi->SetDataFormat (&c_dfDIJoystick); if (SUCCEEDED (hr)) { did->lpdi = lpdi; lpdi->EnumObjects (EnumObjectsCallback, (void*)did, DIDFT_ALL); fixbuttons (did); fixthings (did); sortobjects (did); } } else { write_log (_T("joystick createdevice failed, %s\n"), DXError (hr)); } } } return 1; } static void close_joystick (void) { int i; if (!joystick_inited) return; joystick_inited = 0; for (i = 0; i < num_joystick; i++) di_dev_free (&di_joystick[i]); di_free (); } void dinput_window (void) { int i; for (i = 0; i < num_joystick; i++) di_joystick[i].coop = 0; for (i = 0; i < num_mouse; i++) di_mouse[i].coop = 0; for (i = 0; i < num_keyboard; i++) di_keyboard[i].coop = 0; } static int acquire_joystick (int num, int flags) { if (num < 0) { return 1; } struct didata *did = &di_joystick[num]; if (did->connection == DIDC_NONE) return 0; LPDIRECTINPUTDEVICE8 lpdi = did->lpdi; unacquire (lpdi, _T("joystick")); did->acquireattempts = MAX_ACQUIRE_ATTEMPTS; if (did->connection == DIDC_DX && lpdi) { DIPROPDWORD dipdw; HRESULT hr; setcoop (did, flags ? (DISCL_FOREGROUND | DISCL_EXCLUSIVE) : (DISCL_BACKGROUND | DISCL_NONEXCLUSIVE), _T("joystick")); memset (&dipdw, 0, sizeof (dipdw)); dipdw.diph.dwSize = sizeof (DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof (DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = DI_BUFFER; hr = IDirectInputDevice8_SetProperty (lpdi, DIPROP_BUFFERSIZE, &dipdw.diph); if (FAILED (hr)) write_log (_T("joystick setproperty failed, %s\n"), DXError (hr)); did->acquired = acquire (lpdi, _T("joystick")) ? 1 : -1; } else if (did->connection == DIDC_RAW) { did->acquired = 1; } else { did->acquired = 1; } return did->acquired > 0 ? 1 : 0; } static void unacquire_joystick (int num) { if (num < 0) { return; } struct didata *did = &di_joystick[num]; if (did->connection == DIDC_NONE) return; unacquire (did->lpdi, _T("joystick")); did->acquired = 0; } static int get_joystick_flags (int num) { return 0; } struct inputdevice_functions inputdevicefunc_joystick = { init_joystick, close_joystick, acquire_joystick, unacquire_joystick, read_joystick, get_joystick_num, get_joystick_friendlyname, get_joystick_uniquename, get_joystick_widget_num, get_joystick_widget_type, get_joystick_widget_first, get_joystick_flags }; int dinput_wmkey (uae_u32 key) { if (normalkb || superkb || rawkb) return 0; if (((key >> 16) & 0xff) == 0x58) return 1; return 0; } int input_get_default_keyboard (int i) { if (rawinput_enabled_keyboard) { if (i < 0) return 0; if (i >= num_keyboard) return 0; struct didata *did = &di_keyboard[i]; if (did->connection == DIDC_RAW && !did->rawinput) return 1; } else { if (i < 0) return 0; if (i == 0) return 1; } return 0; } static int nextsub(struct uae_input_device *uid, int i, int slot, int sub) { if (currprefs.input_advancedmultiinput) { while (uid[i].eventid[slot][sub] > 0) { sub++; if (sub >= MAX_INPUT_SUB_EVENT) { return -1; } } } return sub; } static void setid (struct uae_input_device *uid, int i, int slot, int sub, int port, int evt, bool gp) { sub = nextsub(uid, i, slot, sub); if (sub < 0) { return; } if (gp && sub == 0) { inputdevice_sparecopy (&uid[i], slot, sub); } uid[i].eventid[slot][sub] = evt; uid[i].port[slot][sub] = port + 1; } static void setid (struct uae_input_device *uid, int i, int slot, int sub, int port, int evt, int af, bool gp) { sub = nextsub(uid, i, slot, sub); if (sub < 0) { return; } setid (uid, i, slot, sub, port, evt, gp); uid[i].flags[slot][sub] &= ~ID_FLAG_AUTOFIRE_MASK; if (af >= JPORT_AF_NORMAL) uid[i].flags[slot][sub] |= ID_FLAG_AUTOFIRE; if (af == JPORT_AF_TOGGLE) uid[i].flags[slot][sub] |= ID_FLAG_TOGGLE; if (af == JPORT_AF_ALWAYS) uid[i].flags[slot][sub] |= ID_FLAG_INVERTTOGGLE; if (af == JPORT_AF_TOGGLENOAF) uid[i].flags[slot][sub] |= ID_FLAG_INVERT; } int input_get_default_mouse (struct uae_input_device *uid, int i, int port, int af, bool gp, bool wheel, bool joymouseswap) { struct didata *did = NULL; if (!joymouseswap) { if (i >= num_mouse) return 0; did = &di_mouse[i]; } else { if (i >= num_joystick) return 0; did = &di_joystick[i]; } setid (uid, i, ID_AXIS_OFFSET + 0, 0, port, port ? INPUTEVENT_MOUSE2_HORIZ : INPUTEVENT_MOUSE1_HORIZ, gp); setid (uid, i, ID_AXIS_OFFSET + 1, 0, port, port ? INPUTEVENT_MOUSE2_VERT : INPUTEVENT_MOUSE1_VERT, gp); if (wheel) setid (uid, i, ID_AXIS_OFFSET + 2, 0, port, port ? 0 : INPUTEVENT_MOUSE1_WHEEL, gp); setid (uid, i, ID_BUTTON_OFFSET + 0, 0, port, port ? INPUTEVENT_JOY2_FIRE_BUTTON : INPUTEVENT_JOY1_FIRE_BUTTON, af, gp); setid (uid, i, ID_BUTTON_OFFSET + 1, 0, port, port ? INPUTEVENT_JOY2_2ND_BUTTON : INPUTEVENT_JOY1_2ND_BUTTON, gp); setid (uid, i, ID_BUTTON_OFFSET + 2, 0, port, port ? INPUTEVENT_JOY2_3RD_BUTTON : INPUTEVENT_JOY1_3RD_BUTTON, gp); if (wheel && port == 0) { /* map back and forward to ALT+LCUR and ALT+RCUR */ if (isrealbutton (did, 3)) { setid (uid, i, ID_BUTTON_OFFSET + 3, 0, port, INPUTEVENT_KEY_ALT_LEFT, gp); setid (uid, i, ID_BUTTON_OFFSET + 3, 1, port, INPUTEVENT_KEY_CURSOR_LEFT, gp); if (isrealbutton (did, 4)) { setid (uid, i, ID_BUTTON_OFFSET + 4, 0, port, INPUTEVENT_KEY_ALT_LEFT, gp); setid (uid, i, ID_BUTTON_OFFSET + 4, 1, port, INPUTEVENT_KEY_CURSOR_RIGHT, gp); } } } if (i == 0) return 1; return 0; } int input_get_default_lightpen (struct uae_input_device *uid, int i, int port, int af, bool gp, bool joymouseswap, int submode) { struct didata *did = NULL; if (!joymouseswap) { if (i >= num_mouse) return 0; did = &di_mouse[i]; } else { if (i >= num_joystick) return 0; did = &di_joystick[i]; } setid (uid, i, ID_AXIS_OFFSET + 0, 0, port, INPUTEVENT_LIGHTPEN_HORIZ, gp); setid (uid, i, ID_AXIS_OFFSET + 1, 0, port, INPUTEVENT_LIGHTPEN_VERT, gp); int button = port ? INPUTEVENT_JOY2_3RD_BUTTON : INPUTEVENT_JOY1_3RD_BUTTON; switch (submode) { case 1: button = port ? INPUTEVENT_JOY2_LEFT : INPUTEVENT_JOY1_LEFT; break; } setid (uid, i, ID_BUTTON_OFFSET + 0, 0, port, button, gp); if (i == 0) return 1; return 0; } int input_get_default_joystick (struct uae_input_device *uid, int i, int port, int af, int mode, bool gp, bool joymouseswap) { int j; struct didata *did = NULL; int h, v; if (joymouseswap) { if (i >= num_mouse) return 0; did = &di_mouse[i]; } else { if (i >= num_joystick) return 0; did = &di_joystick[i]; } if (mode == JSEM_MODE_MOUSE_CDTV) { h = INPUTEVENT_MOUSE_CDTV_HORIZ; v = INPUTEVENT_MOUSE_CDTV_VERT; } else if (port >= 2) { h = port == 3 ? INPUTEVENT_PAR_JOY2_HORIZ : INPUTEVENT_PAR_JOY1_HORIZ; v = port == 3 ? INPUTEVENT_PAR_JOY2_VERT : INPUTEVENT_PAR_JOY1_VERT; } else { h = port ? INPUTEVENT_JOY2_HORIZ : INPUTEVENT_JOY1_HORIZ;; v = port ? INPUTEVENT_JOY2_VERT : INPUTEVENT_JOY1_VERT; } setid (uid, i, ID_AXIS_OFFSET + 0, 0, port, h, gp); setid (uid, i, ID_AXIS_OFFSET + 1, 0, port, v, gp); if (port >= 2) { setid (uid, i, ID_BUTTON_OFFSET + 0, 0, port, port == 3 ? INPUTEVENT_PAR_JOY2_FIRE_BUTTON : INPUTEVENT_PAR_JOY1_FIRE_BUTTON, af, gp); } else { setid (uid, i, ID_BUTTON_OFFSET + 0, 0, port, port ? INPUTEVENT_JOY2_FIRE_BUTTON : INPUTEVENT_JOY1_FIRE_BUTTON, af, gp); if (isrealbutton (did, 1)) setid (uid, i, ID_BUTTON_OFFSET + 1, 0, port, port ? INPUTEVENT_JOY2_2ND_BUTTON : INPUTEVENT_JOY1_2ND_BUTTON, gp); if (mode != JSEM_MODE_JOYSTICK) { if (isrealbutton (did, 2)) setid (uid, i, ID_BUTTON_OFFSET + 2, 0, port, port ? INPUTEVENT_JOY2_3RD_BUTTON : INPUTEVENT_JOY1_3RD_BUTTON, gp); } } for (j = 2; j < MAX_MAPPINGS - 1; j++) { int type = did->axistype[j]; if (type == AXISTYPE_POV_X) { setid (uid, i, ID_AXIS_OFFSET + j + 0, 0, port, h, gp); setid (uid, i, ID_AXIS_OFFSET + j + 1, 0, port, v, gp); j++; } } if (mode == JSEM_MODE_JOYSTICK_CD32) { setid (uid, i, ID_BUTTON_OFFSET + 0, 0, port, port ? INPUTEVENT_JOY2_CD32_RED : INPUTEVENT_JOY1_CD32_RED, af, gp); if (isrealbutton (did, 1)) { setid (uid, i, ID_BUTTON_OFFSET + 1, 0, port, port ? INPUTEVENT_JOY2_CD32_BLUE : INPUTEVENT_JOY1_CD32_BLUE, gp); } if (isrealbutton (did, 2)) setid (uid, i, ID_BUTTON_OFFSET + 2, 0, port, port ? INPUTEVENT_JOY2_CD32_GREEN : INPUTEVENT_JOY1_CD32_GREEN, gp); if (isrealbutton (did, 3)) setid (uid, i, ID_BUTTON_OFFSET + 3, 0, port, port ? INPUTEVENT_JOY2_CD32_YELLOW : INPUTEVENT_JOY1_CD32_YELLOW, gp); if (isrealbutton (did, 4)) setid (uid, i, ID_BUTTON_OFFSET + 4, 0, port, port ? INPUTEVENT_JOY2_CD32_RWD : INPUTEVENT_JOY1_CD32_RWD, gp); if (isrealbutton (did, 5)) setid (uid, i, ID_BUTTON_OFFSET + 5, 0, port, port ? INPUTEVENT_JOY2_CD32_FFW : INPUTEVENT_JOY1_CD32_FFW, gp); if (isrealbutton (did, 6)) setid (uid, i, ID_BUTTON_OFFSET + 6, 0, port, port ? INPUTEVENT_JOY2_CD32_PLAY : INPUTEVENT_JOY1_CD32_PLAY, gp); } if (i == 0) return 1; return 0; } int input_get_default_joystick_analog (struct uae_input_device *uid, int i, int port, int af, bool gp, bool joymouseswap) { int j; struct didata *did; if (joymouseswap) { if (i >= num_mouse) return 0; did = &di_mouse[i]; } else { if (i >= num_joystick) return 0; did = &di_joystick[i]; } setid (uid, i, ID_AXIS_OFFSET + 0, 0, port, port ? INPUTEVENT_JOY2_HORIZ_POT : INPUTEVENT_JOY1_HORIZ_POT, gp); setid (uid, i, ID_AXIS_OFFSET + 1, 0, port, port ? INPUTEVENT_JOY2_VERT_POT : INPUTEVENT_JOY1_VERT_POT, gp); setid (uid, i, ID_BUTTON_OFFSET + 0, 0, port, port ? INPUTEVENT_JOY2_LEFT : INPUTEVENT_JOY1_LEFT, af, gp); if (isrealbutton (did, 1)) setid (uid, i, ID_BUTTON_OFFSET + 1, 0, port, port ? INPUTEVENT_JOY2_RIGHT : INPUTEVENT_JOY1_RIGHT, gp); if (isrealbutton (did, 2)) setid (uid, i, ID_BUTTON_OFFSET + 2, 0, port, port ? INPUTEVENT_JOY2_UP : INPUTEVENT_JOY1_UP, gp); if (isrealbutton (did, 3)) setid (uid, i, ID_BUTTON_OFFSET + 3, 0, port, port ? INPUTEVENT_JOY2_DOWN : INPUTEVENT_JOY1_DOWN, gp); for (j = 2; j < MAX_MAPPINGS - 1; j++) { int type = did->axistype[j]; if (type == AXISTYPE_POV_X) { setid (uid, i, ID_AXIS_OFFSET + j + 0, 0, port, port ? INPUTEVENT_JOY2_HORIZ_POT : INPUTEVENT_JOY1_HORIZ_POT, gp); setid (uid, i, ID_AXIS_OFFSET + j + 1, 0, port, port ? INPUTEVENT_JOY2_VERT_POT : INPUTEVENT_JOY1_VERT_POT, gp); j++; } } if (i == 0) return 1; return 0; } #ifdef RETROPLATFORM #include "cloanto/RetroPlatformIPC.h" int rp_input_enum (struct RPInputDeviceDescription *desc, int index) { memset (desc, 0, sizeof (struct RPInputDeviceDescription)); if (index < num_joystick) { struct didata *did = &di_joystick[index]; _tcscpy (desc->szHostInputName, did->name); _tcscpy (desc->szHostInputID, did->configname); desc->dwHostInputType = RP_HOSTINPUT_JOYSTICK; desc->dwInputDeviceFeatures = RP_FEATURE_INPUTDEVICE_JOYSTICK; if (did->buttons > 2) desc->dwInputDeviceFeatures |= RP_FEATURE_INPUTDEVICE_GAMEPAD; if (did->buttons >= 7) desc->dwInputDeviceFeatures |= RP_FEATURE_INPUTDEVICE_JOYPAD; desc->dwHostInputProductID = did->pid; desc->dwHostInputVendorID = did->vid; if (did->analogstick) desc->dwInputDeviceFeatures |= RP_FEATURE_INPUTDEVICE_ANALOGSTICK; return index + 1; } else if (index < num_joystick + num_mouse) { struct didata *did = &di_mouse[index - num_joystick]; _tcscpy (desc->szHostInputName, did->name); _tcscpy (desc->szHostInputID, did->configname); desc->dwHostInputType = RP_HOSTINPUT_MOUSE; desc->dwInputDeviceFeatures = RP_FEATURE_INPUTDEVICE_MOUSE; desc->dwInputDeviceFeatures |= RP_FEATURE_INPUTDEVICE_LIGHTPEN; desc->dwHostInputProductID = did->pid; desc->dwHostInputVendorID = did->vid; if (did->wininput) desc->dwFlags |= RP_HOSTINPUTFLAGS_MOUSE_SMART; return index + 1; } return -1; } #endif
#include "book.h" /** * @brief Book::getAvailable * gets the list of * @return */ std::vector<bool> Book::getAvailable() const { return available; } void Book::setAvailable(const std::vector<bool> &value) { available = value; } std::vector<time_t> Book::getRentedOn() const { return rentedOn; } void Book::setRentedOn(const std::vector<time_t> &value) { rentedOn = value; } std::vector<std::vector<std::string> > Book::getAuthors() const { return authors; } void Book::setAuthors(const std::vector<std::vector<std::string> > &value) { authors = value; } /** * @brief compares the first author name to the firest author name of another * list * @param author name 1 * @param author name 2 * @return */ bool Book::nameCompare(const std::vector<std::string> &a, const std::vector<std::string> &b) { if (a.empty()) return false; if (b.empty()) return true; return a.front() > b.front(); } /** * @brief prints in a file all book titles of books that were rented on the * chosen day * @param the date to save all books rented on */ void Book::onDate(struct tm* chosenDate) { const struct tm chdate = *chosenDate; std::ofstream file("books.txt"); for (int i = 0; i < getSize(); ++i) { auto bookdateraw = getRentedOn().at(i); auto bookDate = std::localtime(&bookdateraw); if (bookDate->tm_mon == chdate.tm_mon && bookDate->tm_year == chdate.tm_year && bookDate->tm_mday == chdate.tm_mday) { file << getTitles()[i] << std::endl; } } } /** * @brief prints in a file all information about books with more than one author */ void Book::moreThanOneAuthor() { std::ofstream file("authors.txt"); for (int i = 0; i < getSize(); ++i) { if (getAuthors().at(i).size() > 1) { file << "{ "; for (auto &a : authors.at(i)) { file << a << " "; } file << ", " << ctime(&getRentedOn().at(i)) << ", " << ((getAvailable().at(i)) ? "available }" : "unavailable }"); } } } /** * @brief constructor for book */ Book::Book() { Library(); } /** * @brief adds book to the book class * @param title of the book * @param authors of the book * @param available if the book is available * @param date the day it was rented on */ void Book::addBook(const char* title, const std::vector<std::string> authors, bool available, time_t date) { // allocate memory for the title name getTitles()[getSize()] = new char[255]; strcpy(getTitles()[getSize()], title); this->authors.push_back(authors); this->available.push_back(available); this->rentedOn.push_back(date); this->incrementSize(); } /** * @brief Overloads the operator << to print books from Book class * @param os outputstream to pass file stream * @param b book class * @return */ std::ostream& operator<<(std::ostream& os, const Book& b) { // print all book information auto authors = b.getAuthors(); for (int i = 0; i < b.getSize(); ++i) { os << "{ "; for (auto &a : authors.at(i)) { os << a << " "; } os << ", " << ctime(&b.getRentedOn().at(i)) << ", " << ((b.getAvailable().at(i)) ? "available }" : "unavailable }"); } return os; }
class Solution { public: int numTrees(int n) { vector<int> M(n+1,0); M[0] = 1; for(int i = 1; i <= n; i++) { int temp = 0; for(int j = 1; j <= i; j++) { temp += M[j-1]*M[i-j]; } M[i] = temp; } return M[n]; } };
#include <iostream> using namespace std; int main() { double iP; double total; double tax; cout << "enter the amount of items purchased"; cin >> iP; tax = iP * 0.07; total = iP + tax; cout << "Your items purchased + taxs = " << total << "$" << endl; return 0; }
#ifndef TEXTTESTER_H_ #define TEXTTESTER_H_ #include <string> #include <vector> class TextTester { public: TextTester(); ~TextTester(); void testResize(); void testReadText(); void testAppendText(); void testDeleteWordAll(); private: std::string* generateText_(std::vector<std::string>& text_vector, unsigned int& length, unsigned int& capacity); void generateWord_(std::string& word, unsigned int length); bool checkText_(std::string* text, std::vector<std::string>& text_vector, unsigned int length); void errorOut_(const std::string& errMsg, unsigned int errBit); void passOut_(const std::string& passMsg); char error_; std::string funcname_; static const unsigned int SMALL_LENGHT = 100; static const unsigned int SMALL_CAPACITY = 100; static const unsigned int WORD_LENGTH = 20; static const std::string DEL_WORD; }; #endif /* TEXTTESTER_H_ */
// - SCRNREF.CPP - // // Implementation of class "CScreenReference". // // Author: Zhang Lei // Date: 2000. 4. 26 // #include "stdafx.h" #include "ScrnRef.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ////////////////////////////////////////////////////////////////////////////// // Implementation of class "CScreenReference". CScreenReference::CScreenReference(USHORT uWidth, USHORT uHeight, float fRatio, CPoint2d& ptCenter) { m_uWidth = uWidth; m_uHeight = uHeight; m_fRatio = fRatio; m_ptCenter = ptCenter; } CScreenReference::CScreenReference() { m_uWidth = 0; m_uHeight = 0; m_fRatio = 1.0; m_ptCenter.x = 0; m_ptCenter.y = 0; } // // Set the pointer that will map to the center of the view port. // void CScreenReference::SetCenterPoint(CPoint2d& pt) { m_ptCenter = pt; } // // 设置视口的左上角点所对应的物理点位置 void CScreenReference::SetLeftTopPoint(CPoint2d& pt) { m_ptCenter.x = pt.x + m_uWidth/m_fRatio/2; m_ptCenter.y = pt.y - m_uHeight/m_fRatio/2; } // // Set the display ratio. // void CScreenReference::SetRatio(float fRatio) { m_fRatio = fRatio; } // // Set the size of the view port. // void CScreenReference::SetViewPort(USHORT uWidth, USHORT uHeight) { m_uWidth = uWidth; m_uHeight = uHeight; } #ifdef _MSC_VER // // Get the world coordinates of the specified window point. // CPoint2d CScreenReference::GetWorldPoint(CPoint& pnt) { CPoint2d pt; CPoint2d ptLeftTop = GetLeftTopPoint(); pt.x = (float)( pnt.x/m_fRatio + ptLeftTop.x); pt.y = (float)(-pnt.y/m_fRatio + ptLeftTop.y); return pt; } // Get the window coordinates of the specified world point CPoint CScreenReference::GetWindowPoint(CPoint2d& pt) { CPoint pnt; CPoint2d ptLeftTop = GetLeftTopPoint(); pnt.x = (int)((pt.x - ptLeftTop.x) * m_fRatio); pnt.y = (int)((ptLeftTop.y - pt.y) * m_fRatio); return pnt; } #endif ///////////////////////////////////////////////////////////////////////////// // Helper functions CPoint2d CScreenReference::GetLeftTopPoint() { CPoint2d pt; pt.x = m_ptCenter.x - m_uWidth/(2*m_fRatio); pt.y = m_ptCenter.y + m_uHeight/(2*m_fRatio); return pt; }
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int a[n+1]; for(int i=1; i<=n; i++) cin>>a[i]; a[0] = -10001; for(int i=2; i<=n; i++) { int v = a[i], j = i-1; while(j>=0 && v<a[j]) { a[j+1] = a[j]; j--; } a[j+1] = v; for(int i=1; i<=n; i++) cout<<a[i]<<" "; cout<<endl; } }
#include "SafetyConnection.h" namespace database { SafetyConnection::SafetyConnection() { source_ind_ = -1; PoolConnections* instance = PoolConnections::GetInstance(); instance->SetParams("config.txt"); source_ind_ = instance->GetConnection(conn_); } SafetyConnection::~SafetyConnection() { ReturnConnection(); } void SafetyConnection::Lock() { conn_mutex_.lock(); } void SafetyConnection::Unlock() { conn_mutex_.unlock(); } Connection& SafetyConnection::GetConnection() { return conn_; } bool SafetyConnection::IsConnected() { return source_ind_ != -1 && conn_.IsOpen(); } void SafetyConnection::ReturnConnection() { if (source_ind_ == -1) { return; } PoolConnections *instance = PoolConnections::GetInstance(); instance->ReturnConnection(conn_, source_ind_); } } // namespace database
#include "AVLtree.h" bool isContain(const QString &str1,const QString &str2){ for(int i=0;i<str2.length();i++){ if(str1[i]!=str2[i]){return false;} } return true; } AVLTree::AVLTree() { root=NULL; } AVLNode *AVLTree::Search(QString x, AVLNode *ptr){ if (ptr == NULL){ return NULL; } AVLNode *temp = ptr; while (temp){ if (temp->data.key == x){ return temp; } if (temp->data.key > x){ temp = temp->left; } else{ temp = temp->right; } } return NULL; } vector<WordNode> AVLTree::BlurrySearch(QString x, AVLNode *ptr) const{ // if(isContain("abc","a")){qDebug()<<"contain";} //qDebug()<<x; //qDebug()<<1; vector<WordNode> Vec; if (ptr == NULL){ return Vec; } AVLNode *temp = ptr;//qDebug()<<2; while (temp){/*qDebug()<<i<<temp->data.key;i++;*/ if (isContain(temp->data.key,x)){//qDebug()<<3;//qDebug()<<"contain"; //Vec.push_back(temp->data); break; } if (temp->data.key > x){//qDebug()<<4; temp = temp->left; } else{//qDebug()<<5; temp=temp->right; } }std::stack<AVLNode*> S; do {//qDebug()<<6; while (temp!=NULL) { S.push(temp); temp = temp->left; } if (!S.empty()) { temp = S.top(); S.pop();if(isContain(temp->data.key,x)){Vec.push_back(temp->data);} temp = temp->right; } } while (temp != NULL || !S.empty()); // temp=temp->right; // while (temp!=NULL) { // if(temp->data.key.contains(x)){ // Vec.push_back(temp->data); // } // temp=temp->right; // //qDebug()<<i;i++; // } return Vec; } bool AVLTree::Export(AVLNode *ptr, QTextStream &out){ if (ptr == NULL){ return false; } AVLNode *temp = ptr; std::stack<AVLNode*> S; do {//qDebug()<<6; while (temp!=NULL) { S.push(temp); temp = temp->left; } if (!S.empty()) { temp = S.top(); S.pop();out<<temp->data.key<<'\n'<<temp->data.description<<'\n'; temp = temp->right; } } while (temp != NULL || !S.empty()); return true; } int AVLTree::Height(AVLNode *ptr)const{ if (!ptr){ return 0; } int n=Height(ptr->left); int m=Height(ptr->right); return n<m ? m+1 : n+1; } //以下必须对应教材的图,而教材图缺了一些中间步骤,要补足才易于理解 //右子树比左子树高: 做左单旋转后新根在ptr void AVLTree::RotateL(AVLNode *& ptr){ AVLNode *subL = ptr; //保留原来的根结点 ptr = subL->right; //原根的右子女将成为新根 subL->right = ptr->left; //ptr成为新根前卸掉左子女,成为原根的右子女 ptr->left = subL; //左单旋,ptr成为新根,原根成为新根的右子女 ptr->bf = subL->bf = 0; //改写平衡度 } //左子树比右子树高, 旋转后新根在ptr void AVLTree::RotateR(AVLNode *& ptr){ AVLNode *subR = ptr; ptr = subR->left; //原根的左子女成为新根 subR->left = ptr->right; //新根原右子女成为原根的左子女 ptr->right = subR; //原根成为新根的右子女 ptr->bf = subR->bf = 0; //改写平衡度 } void AVLTree::RotateLR(AVLNode *& ptr){ AVLNode *subR = ptr; AVLNode *subL = subR->left; ptr = subL->right; //先左旋 subL->right = ptr->left; //ptr成为新根前卸掉左子女,成为原根的右子女 ptr->left = subL; //左单旋,ptr成为新根,原根成为新根的右子女 if (ptr->bf <= 0){ //旋转前插入新结点后ptr左子树变高 subL->bf = 0; } else{ //插入新结点后ptr右子树变高 subL->bf = -1; } subR->left = ptr->right; ptr->right = subR; if (ptr->bf == -1){ //旋转前插入新结点后ptr左子树变高 subR->bf = 1; } else{ //插入新结点后ptr右子树变高 subR->bf = 0; } ptr->bf = 0; } void AVLTree::RotateRL(AVLNode *& ptr){ AVLNode *subL = ptr; AVLNode *subR = subL->right; ptr = subR->left; subR->left = ptr->right; ptr->right = subR; if (ptr->bf >= 0){ subR->bf = 0; } else{ subR->bf = 1; } subL->right = ptr->left; ptr->left = subL; if (ptr->bf == 1){ subL->bf = -1; } else{ subL->bf = 0; } ptr->bf = 0; } //在以ptr为根的AVL树中插入新元素e1, //如果插入成功,函数返回true,否则返回false。 bool AVLTree::Insert(AVLNode *& ptr, WordNode &e1){ AVLNode *pr = NULL, *p = ptr, *q; int d; std::stack<AVLNode*> st; while (p != NULL){ //寻找插入位置 if (e1 == p->data) return false;//找到等于e1的结点,不插入 pr = p; st.push(pr); //否则用栈记忆查找路径 if (e1 < p->data) p = p->left; else p = p->right; } p = new AVLNode(e1); //创建新结点,data=e1,bf=0 //assert(p); if (pr == NULL){ //空树,新结点成为根结点 ptr = p; return true; } if (e1 < pr->data){ //新结点插入 pr->left = p; } else{ pr->right = p; } //重新平衡化 while (st.empty() == false){ pr=st.top();st.pop(); //从栈中退出父结点 if (p == pr->left){ //调整父结点的平衡因子 pr->bf--; } else{ pr->bf++; } if (pr->bf == 0){ //第1种情况,|bf|=0,平衡退出 break; } if (pr->bf == 1 || pr->bf == -1){//第2种情况,|bf|=1 p = pr; } else{ //第3种情况,|bf|=2 d = (pr->bf < 0) ? -1 : 1; //区别单双旋转标志 if (p->bf == d){ //两结点平衡因子同号,单旋转 if (d == -1) { RotateR(pr); //右单旋转 } else{ RotateL(pr); //左单旋转 } } else{ //两结点平衡因子反号,双旋转 if (d == -1){ RotateLR(pr); //先左后右双旋转,”<”型 } else{ RotateRL(pr); //先右后左双旋转,”>”型 } } break; //不再向上调整 }//第三种情况结束 } // 对于第二种情况需要继续从结点向根的方向回溯调整 if (st.empty() == true){ //调整到树的根结点 ptr = pr; } else{ //中间重新链接 q=st.top();//st.getTop(q); if (q->data > pr->data){ q->left = pr; } else{ q->right = pr; } } return true; } //在以ptr为根的AVL树中删除关键码为x的结点。 //如果删除成功,函数返回true,同时通过参数e1返回被删结点元素; //如果删除失败则函数返回false。 bool AVLTree::Remove(AVLNode *& ptr, QString x, WordNode &e1){ AVLNode *pr = NULL, *p = ptr, *q, *ppr; int d, dd = 0; std::stack<AVLNode*> st; while (p != NULL){ //寻找删除位置 if (x == p->data.key){ //找到等于x的结点,停止搜索 break; } pr = p; st.push(pr); //否则用栈记忆查找路径 if (x < p->data.key){ p = p->left; } else{ p = p->right; } } if (p == NULL){ //未找到被删结点,删除失败 return false; } e1 = p->data; if (p->left && p->right){ //被删结点有两个子女 pr = p; st.push(pr); q = p->left; //在p左子树找p的直接前驱 while (q->right){ pr = q; st.push(pr); q = q->right; } p->data = q->data; //用q的值填补p p = q; //被删结点转化为q } //以下包括由双子女转换后的和原来就非双子女的。 //同时以下也包括单子女和无子女 if (p->left){ //被删结点p最多只有一个子女q q = p->left; } else{ q = p->right; //无子女时,q为NULL } if (pr == NULL){ //被删结点为根结点,其父结点为空 ptr = q; } else{ //被删结点不是根结点 if (pr->left == p){ //链接 pr->left = q; } else{ pr->right = q; } while (st.empty() == false){ //重新平衡化 pr=st.top();st.pop(); //从栈中退出父结点 if(q==NULL){ //调整父结点的平衡因子。无子女 pr->bf=0; } else{ //单子女 if (pr->right == q){ pr->bf--; //删在右边 } else{ pr->bf++; //删在左边 } } if (st.empty() == false){ ppr=st.top();//st.getTop(ppr); //从栈中取出祖父结点 dd = (ppr->left == pr) ?-1 : 1; //旋转后与上层链接方向 } else{ //栈空,旋转后不与上层链接 dd = 0; } if (pr->bf == 1 || pr->bf == -1){ //图7.20,|bf|=1 break; } if (pr->bf != 0){ //|bf|=2 if (pr->bf < 0) {d = -1; q = pr->left;} else{ //用q指示较高的子树 d = 1; q = pr->right; } if (q->bf == 0){ //图7.22 if (d == -1){ RotateR(pr); //再参见图7.15 pr->bf = 1; pr->right->bf = -1; //#改 } else{ RotateL(pr); pr->bf = -1; pr->left->bf = 1; //#改 } //旋转后新根与上层链接 if (dd == -1){ ppr->left = pr; } else if (dd == 1){ ppr->right = pr; } break; } if (q->bf == d){ //两结点平衡因子同号,图7.23 if (d == -1){ //右单旋转 RotateR(pr); } else{ //左单旋转 RotateL(pr); } } else{ //两结点平衡因子反号,图7.24 if (d == -1){ //先左后右双旋转,”<”型 RotateLR(pr); } else{ //先右后左双旋转,”>”型 RotateRL(pr); } } //旋转后新根与上层链接 if (dd == -1){ ppr->left = pr; } else if (dd == 1){ ppr->right = pr; } } q = pr; //图7.21,|bf|=0 } if (st.empty() == true){ //调整到树的根结点 ptr = pr; } } delete p; return true; } //void AVLTree::Traverse(AVLNode *ptr, ostream &out)const{ // if (ptr != NULL){ //树非空 // Traverse(ptr->left, out); //中序遍历左子树 // out << ptr->data.key << ' '; //输出根的数据 // Traverse(ptr->right, out); //中序遍历右子树 // } //} // //void AVLTree::PrintTree(AVLNode *ptr, ostream &out)const{ // if (!ptr){ // return; // } // out << ptr->data.key; // if (ptr->left == NULL && ptr->right == NULL){ // return; // } // out << "("; // PrintTree(ptr->left, out); // out << ','; // PrintTree(ptr->right, out); // out << ")"; //} //void AVLTree::PrintData(AVLNode *ptr, ostream &out)const{ // if (ptr){ // PrintData(ptr->left, out); // out << ptr->data <<'\t'<< ptr->bf << endl; // PrintData(ptr->right, out); // } //}
#ifndef SRADIO_CPP #define SRADIO_CPP #include <windows.h> #include "SApp.h" #include "SWindow.h" #include "SButton.h" #include "SRadio.h" SRadio::SRadio(SWindow * pWin, UINT uStyle, UINT uId, UINT uExStyle): SButton(pWin, uStyle | BS_RADIOBUTTON, uId, uExStyle) { } SRadio::~SRadio() { } BOOL SRadio::IsChecked() { return (SendMessage(hwnd, BM_GETCHECK, 0, 0) == BST_CHECKED) ? TRUE : FALSE; } DWORD SRadio::SetChecked(BOOL isCheck) { WPARAM bState = (isCheck) ? BST_CHECKED : BST_UNCHECKED; SendMessage(hwnd, BM_SETCHECK, bState, 0); return 0; } #endif
#include<iostream> #include<cmath> using namespace std; int main() { int n; cout<<"Enter a number: "; cin>>n; bool flag = 0; for(int i = 2; i <= sqrt(n); i++) { if(n % i == 0) { flag = 1; cout<<"Not prime"; break; } } if(flag == 0) { cout<<"Prime number!"; } return 0; }
#pragma once #include "ofMain.h" #include "ofxCv.h" #include "FaceOsc.h" #include "ofxXmlSettings.h" #include "ofxOsc.h" #include "ofxBox2d.h" class ofApp : public ofBaseApp, public FaceOsc { public: void setup(); void update(); void draw(); void keyPressed(int key); bool bUseCamera, bPaused; int camWidth, camHeight; int movieWidth, movieHeight; int sourceWidth, sourceHeight; ofVideoGrabber cam; ofxFaceTracker tracker; ofMatrix4x4 rotationMatrix; ofMesh customMesh; ofVec4f pastMouth[100]; vector<ofVec3f> faceCircle; bool bDrawMesh; ofImage facebuffer[30]; int faceCounter; ofPoint facePosition; float faceSize; int cMode; enum MODE{VER,HOR,BLO}; };
#pragma once #include <map> #include <string> #include "Tags.h" class TradosUnit { public: TradosUnit(); virtual ~TradosUnit(); std::map<std::wstring, std::wstring>& pairs(void) { return m_pairs; } const std::map<std::wstring, std::wstring>& pairs(void) const { return m_pairs; } const std::wstring& creationdate(void) const { return m_creationdate; } void creationdate(const std::wstring& _creationdate) { this->m_creationdate = _creationdate; } void creationdate(wchar_t* _creationdate) { this->m_creationdate.assign(_creationdate); } const std::wstring& creationid(void) const { return m_creationid; } void creationid(const std::wstring& _creationid) { this->m_creationid = _creationid; } void creationid(wchar_t* _creationid) { this->m_creationid.assign(_creationid); } const long long id(void) const { return llId; } const void id(long long id) { llId = id; } private: std::map<std::wstring, std::wstring> m_pairs; long long llId; std::wstring m_creationdate; std::wstring m_creationid; }; std::wostream& operator<<(std::wostream& s, const TradosUnit& tu);
#pragma once #include "cui.h" class cButton : public cUI { private: _SYNTHESIZE_INHER( bool, m_IsVirusPatten, VirusPatten ); _SYNTHESIZE_REF_INHER( float, m_fPattenTime, PattenTime ); _SYNTHESIZE_REF_INHER( D3DXVECTOR3, m_vStart, StartPos ); _SYNTHESIZE_REF_INHER( D3DXVECTOR3, m_vEnd, EndPos ); public: virtual void Init(); virtual void Update(); virtual void Render(); virtual void Release(); private: void VirusPatten(); public: cButton(void); ~cButton(void); };
#include <gtest/gtest.h> #include "CppLinq.h" #include "TestUtils.h" TEST(Contains, ThreeInts) { std::vector<int> src = { 1, 2, 3 }; auto rng = CppLinq::From(src); EXPECT_TRUE(rng.Contains(1)); EXPECT_TRUE(rng.Contains(2)); EXPECT_TRUE(rng.Contains(3)); EXPECT_FALSE(rng.Contains(0)); EXPECT_FALSE(rng.Contains(4)); }
#include "wizFolderView.h" #include <QtGui> #include "widgets/wizScrollBar.h" #include "wizdef.h" #include "share/wizsettings.h" #include "share/wizuihelper.h" #include "wiznotestyle.h" CWizFolderView::CWizFolderView(CWizExplorerApp& app, QWidget *parent) : QTreeWidget(parent) , m_app(app) , m_dbMgr(app.databaseManager()) { header()->hide(); setAnimated(true); setAttribute(Qt::WA_MacShowFocusRect, false); setStyle(::WizGetStyle(m_app.userSettings().skin())); // use custom scrollbar setVerticalScrollMode(QAbstractItemView::ScrollPerItem); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_vScroll = new CWizScrollBar(this); m_vScroll->syncWith(verticalScrollBar()); initFolders(); } void CWizFolderView::resizeEvent(QResizeEvent* event) { // reset scrollbar m_vScroll->resize(m_vScroll->sizeHint().width(), event->size().height()); m_vScroll->move(event->size().width() - m_vScroll->sizeHint().width(), 0); QTreeWidget::resizeEvent(event); } void CWizFolderView::initFolders() { CWizCategoryViewAllFoldersItem* pAllFoldersItem = new CWizCategoryViewAllFoldersItem(m_app, tr("Note Folders"), m_dbMgr.db().kbGUID()); addTopLevelItem(pAllFoldersItem); CWizStdStringArray arrayAllLocation; m_dbMgr.db().GetAllLocations(arrayAllLocation); initFolders(pAllFoldersItem, "", arrayAllLocation); if (arrayAllLocation.empty()) { const QString strNotes("/My Notes/"); m_dbMgr.db().AddExtraFolder(strNotes); m_dbMgr.db().SetObjectVersion("folder", 0); arrayAllLocation.push_back(strNotes); } //init extra folders CWizStdStringArray arrayExtLocation; m_dbMgr.db().GetExtraFolder(arrayExtLocation); CWizStdStringArray::const_iterator it; for (it = arrayExtLocation.begin(); it != arrayExtLocation.end(); it++) { QString strLocation = *it; if (strLocation.isEmpty()) continue; if (m_dbMgr.db().IsInDeletedItems(strLocation)) continue; addFolder(strLocation, true); } pAllFoldersItem->setExpanded(true); pAllFoldersItem->sortChildren(0, Qt::AscendingOrder); } void CWizFolderView::initFolders(QTreeWidgetItem* pParent, const QString& strParentLocation, const CWizStdStringArray& arrayAllLocation) { CWizStdStringArray arrayLocation; CWizDatabase::GetChildLocations(arrayAllLocation, strParentLocation, arrayLocation); CWizStdStringArray::const_iterator it; for (it = arrayLocation.begin(); it != arrayLocation.end(); it++) { QString strLocation = *it; if (m_dbMgr.db().IsInDeletedItems(strLocation)) continue; CWizCategoryViewFolderItem* pFolderItem = new CWizCategoryViewFolderItem(m_app, strLocation, m_dbMgr.db().kbGUID()); pParent->addChild(pFolderItem); initFolders(pFolderItem, strLocation, arrayAllLocation); } } CWizCategoryViewFolderItem* CWizFolderView::addFolder(const QString& strLocation, bool sort) { return findFolder(strLocation, true, sort); } CWizCategoryViewFolderItem* CWizFolderView::findFolder(const QString& strLocation, bool create, bool sort) { CWizCategoryViewAllFoldersItem* pAllFolders = findAllFolders(); if (!pAllFolders) return NULL; if (m_dbMgr.db().IsInDeletedItems(strLocation)) { return findTrash(m_dbMgr.db().kbGUID()); } QString strCurrentLocation = "/"; QTreeWidgetItem* parent = pAllFolders; CString strTempLocation = strLocation; strTempLocation.Trim('/'); QStringList sl = strTempLocation.split("/"); QStringList::const_iterator it; for (it = sl.begin(); it != sl.end(); it++) { QString strLocationName = *it; Q_ASSERT(!strLocationName.isEmpty()); strCurrentLocation = strCurrentLocation + strLocationName + "/"; bool found = false; int nCount = parent->childCount(); for (int i = 0; i < nCount; i++) { CWizCategoryViewFolderItem* pFolder = dynamic_cast<CWizCategoryViewFolderItem*>(parent->child(i)); if (pFolder && pFolder->name() == strLocationName) { found = true; parent = pFolder; continue; } } if (found) continue; if (!create) return NULL; CWizCategoryViewFolderItem* pFolderItem = new CWizCategoryViewFolderItem(m_app, strCurrentLocation, m_dbMgr.db().kbGUID()); parent->addChild(pFolderItem); parent->setExpanded(true); if (sort) { parent->sortChildren(0, Qt::AscendingOrder); } parent = pFolderItem; } return dynamic_cast<CWizCategoryViewFolderItem *>(parent); } CWizCategoryViewAllFoldersItem* CWizFolderView::findAllFolders() { int nCount = topLevelItemCount(); for (int i = 0; i < nCount; i++) { if (CWizCategoryViewAllFoldersItem* pItem = dynamic_cast<CWizCategoryViewAllFoldersItem*>(topLevelItem(i))) { return pItem; } } Q_ASSERT(false); return NULL; } CWizCategoryViewTrashItem* CWizFolderView::findTrash(const QString& strKbGUID) { Q_UNUSED(strKbGUID); int nCount = topLevelItemCount(); for (int i = 0; i < nCount; i++) { if (CWizCategoryViewTrashItem* pItem = dynamic_cast<CWizCategoryViewTrashItem*>(topLevelItem(i))) { return pItem; } } return NULL; }
#include<stdio.h> #include<string.h> void fun(char s[]) { int len=strlen(s); int letter=0,num=0,space=0,other=0; for (int i=0; i<len; i++) { if ((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')) letter++; else if (s[i]>='0'&&s[i]<='9') num++; else if (s[i]==' '||s[i]=='\t') space++; else other++; } printf("Letter=%d, Number=%d, Space=%d, Ohter=%d\n", letter, num, space, other); } int main() { char s[81]; gets(s); fun(s); return 0; }
string Solution::largestNumber(const vector<int> &A) { vector<int> v; int n=A.size(); int count=0; for(int i=0;i<n;i++) { if(A[i]==0)count++; v.push_back(A[i]); } if(count==n) { return "0"; } sort(v.begin(),v.end(),[](int &a,int &b) { string t1=to_string(a); string t2=to_string(b); int i=0,j=0; while(1) { if(j>i && j==0)return true; if(i>j && i==0)return true; if(t1[i]==t2[j]) { i++;j++; } else if(t1[i]>t2[j]) { return true; } else { return false; } if(i==t1.size() && j==t2.size()) { return true; } if(i==t1.size()) { i=0; } if(j==t2.size()) { j=0; } } }); string s=""; for(int i=0;i<n;i++) { s.append(to_string(v[i])); } return s; }
#ifndef __GEOMETRY2D_H__ #define __GEOMETRY2D_H__ #include <Python.h> #include <boost/python.hpp> #include <boost/python/numeric.hpp> #include <boost/python/tuple.hpp> #include <boost/numpy.hpp> #include <boost/filesystem.hpp> #include <boost/math/distributions.hpp> const boost::math::normal_distribution<> standard_normal; namespace py = boost::python; namespace np = boost::numpy; #include <armadillo> using namespace arma; #include <assert.h> #include "planar-utils.h" const double epsilon = 1e-5; class Line; class Halfspace; class Segment; class Beam; /** * Vector direction + origin */ class Line { public: Line(const vec& direction, const vec& origin) : d(direction), o(origin) { }; Line(const Segment& seg); bool intersection(const Line& other, vec& intersection); bool intersection(const Segment& seg, vec& intersection); double distance_to(const vec& x); private: vec d, o; }; /** * Normal direction + origin */ class Halfspace { public: Halfspace(const vec& normal, const vec& origin) : n(normal), o(origin) { }; bool contains(const vec& x); bool contains_part(const Segment& seg, Segment& seg_part); private: vec n, o; }; class Segment { public: vec p0, p1; Segment(const vec& point0, const vec& point1) : p0(point0), p1(point1) { }; bool intersection(const Segment& other, vec& intersection); bool within_bounding_rect(const vec& p) const; vec closest_point_to(const vec& x); double distance_to(const vec& x); double length() { return norm(p1 - p0, 2); } }; /** * Triangle in which space inside the points * is in the FOV */ class Beam { public: vec base, a, b; // base, a, b Counter-Clockwise Beam(const vec& base_pt, const vec& a_pt, const vec& b_pt); std::vector<Beam> truncate(const Segment& s); double signed_distance(const vec& x); bool is_inside(const vec& p); double top_length() { return top_segment().length(); } private: Segment right_segment() { return Segment(base, a); } Segment top_segment() { return Segment(a, b); } Segment left_segment() { return Segment(base, b); } double area(); }; namespace geometry2d { double signed_distance(const vec& p, std::vector<Beam>& beams); std::vector<Segment> beams_border(const std::vector<Beam>& beams); void truncate_belief(const std::vector<Beam>& beams, const vec& cur_mean, const mat& cur_cov, vec& out_mean, mat& out_cov); void my_truncate_belief(const std::vector<Beam>& beams, const vec& cur_mean, const mat& cur_cov, vec& out_mean, mat& out_cov); void truncate_gaussian(const vec& c, double d, const vec& cur_mean, const mat& cur_cov, vec& out_mean, mat& out_cov); void my_truncate_gaussian(const vec& c, double d, const vec& cur_mean, const mat& cur_cov, vec& delta_mean_total, mat& delta_cov_total); void truncate_univariate_gaussian(const double x, const double cur_mean, const double cur_var, double& out_mean, double& out_var); void my_truncate_univariate_gaussian(const double x, const double cur_mean, const double cur_var, double& out_mean, double& out_var); void plot_beams(std::vector<Beam>& beams); } #endif
/** * @author Levi Armstrong * @date January 1, 2016 * * @copyright Copyright (c) 2016, Southwest Research Institute * * @license Software License Agreement (Apache License)\n * \n * 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\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * 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 "ros_utils.h" #include "ros_project_constants.h" #include <utils/fileutils.h> #include <utils/environment.h> #include <QDir> #include <QDebug> #include <QFile> #include <QTextStream> #include <QDirIterator> namespace ROSProjectManager { namespace Internal { ROSUtils::ROSUtils() { } bool ROSUtils::generateCodeBlocksProjectFile(QProcess *process, const Utils::FileName &sourceDir, const Utils::FileName &buildDir) { QString cmd = QLatin1String("cmake ") + sourceDir.toString() + QLatin1String(" -G \"CodeBlocks - Unix Makefiles\""); process->setWorkingDirectory(buildDir.toString()); process->start(QLatin1String("bash"), QStringList() << QLatin1String("-c") << cmd); process->waitForFinished(); if (process->exitStatus() != QProcess::CrashExit) { return true; } else { qDebug() << "Faild to generate Code Blocks Project File."; return false; } } bool ROSUtils::sourceROS(QProcess *process, const QString &rosDistribution) { bool results = sourceWorkspaceHelper(process, Utils::FileName::fromString(QLatin1String(ROSProjectManager::Constants::ROS_INSTALL_DIRECTORY)).appendPath(rosDistribution).appendPath(QLatin1String("setup.bash")).toString()); if (!results) { qDebug() << "Faild to source ROS Distribution: " << rosDistribution; } return results; } bool ROSUtils::sourceWorkspace(QProcess *process, const Utils::FileName &workspaceDir, const QString &rosDistribution) { bool results = false; Utils::FileName ws(workspaceDir); Utils::FileName devDir(workspaceDir); devDir.appendPath(QLatin1String("devel")); if (sourceROS(process, rosDistribution)) { results = true; if (!hasBuildDirectory(workspaceDir) || !hasDevelDirectory(workspaceDir)) { results = initializeWorkspace(process, workspaceDir, rosDistribution); } if (results) { if (sourceWorkspaceHelper(process, devDir.appendPath(QLatin1String("setup.bash")).toString())) { results = true; } else { results = false; qDebug() << "Failed to source workspace: " << workspaceDir.toString(); } } } return results; } bool ROSUtils::isWorkspaceInitialized(const Utils::FileName &workspaceDir) { Utils::FileName topCMake(workspaceDir); topCMake.appendPath(QLatin1String("src")).appendPath(QLatin1String("CMakeLists.txt")); if (!topCMake.exists()) { return false; } else { return true; } } bool ROSUtils::initializeWorkspace(QProcess *process, const Utils::FileName &workspaceDir, const QString &rosDistribution) { Utils::FileName srcDir(workspaceDir); srcDir.appendPath(QLatin1String("src")); bool results = false; if (sourceROS(process, rosDistribution)) { if (!isWorkspaceInitialized(workspaceDir)) { if (!srcDir.exists()) { QDir(workspaceDir.toString()).mkdir(QLatin1String("src")); } process->setWorkingDirectory(srcDir.toString()); process->start(QLatin1String("bash"), QStringList() << QLatin1String("-c") << QLatin1String("catkin_init_workspace")); process->waitForFinished(); if (process->exitStatus() != QProcess::CrashExit) { results = true; } else { results = false; qDebug() << "Failed ot initialize workspace: " << workspaceDir.toString(); } } else { results = true; } if (buildWorkspace(process, workspaceDir)) { results = true; } else { results = false; } } return results; } bool ROSUtils::hasBuildDirectory(const Utils::FileName &workspaceDir) { Utils::FileName buildDir(workspaceDir); buildDir.appendPath(QLatin1String("build")); return buildDir.exists(); } bool ROSUtils::hasDevelDirectory(const Utils::FileName &workspaceDir) { Utils::FileName develDir(workspaceDir); develDir.appendPath(QLatin1String("devel")); return develDir.exists(); } bool ROSUtils::buildWorkspace(QProcess *process, const Utils::FileName &workspaceDir) { bool results = false; process->setWorkingDirectory(workspaceDir.toString()); // May need to change PWD Enviroment variable here process->start(QLatin1String("bash"), QStringList() << QLatin1String("-c") << QLatin1String("catkin_make")); process->waitForFinished(); if (process->exitStatus() != QProcess::CrashExit) { results = true; } else { qDebug() << "Failed ot build workspace: " << workspaceDir.toString(); } return results; } QStringList ROSUtils::installedDistributions() { QDir ros_opt(QLatin1String(ROSProjectManager::Constants::ROS_INSTALL_DIRECTORY)); ros_opt.setFilter(QDir::NoDotAndDotDot | QDir::Dirs); return ros_opt.entryList(); } bool ROSUtils::sourceWorkspaceHelper(QProcess *process, const QString &path) { bool results = false; QStringList env_list; process->start(QLatin1String("bash")); process->waitForStarted(); QString cmd = QLatin1String("source ") + path + QLatin1String(" && env > /tmp/rosqtenv.txt"); process->write(cmd.toLatin1()); process->closeWriteChannel(); process->waitForFinished(); if (process->exitStatus() != QProcess::CrashExit) { QFile env_file(QLatin1String("/tmp/rosqtenv.txt")); if (env_file.open(QIODevice::ReadOnly)) { QTextStream env_stream(&env_file); while (!env_stream.atEnd()) { env_list << env_stream.readLine(); } env_file.close(); Utils::Environment env(env_list); process->setProcessEnvironment(env.toProcessEnvironment()); results = true; } } return results; } bool ROSUtils::gererateQtCreatorWorkspaceFile(QXmlStreamWriter &xmlFile, const QStringList &watchDirectories, const QStringList &includePaths) { xmlFile.setAutoFormatting(true); xmlFile.writeStartDocument(); xmlFile.writeStartElement(QLatin1String("Workspace")); xmlFile.writeStartElement(QLatin1String("WatchDirectories")); foreach (QString str, watchDirectories) { xmlFile.writeTextElement(QLatin1String("Directory"), str); } xmlFile.writeEndElement(); xmlFile.writeStartElement(QLatin1String("IncludePaths")); foreach (const QString &str, includePaths) { xmlFile.writeTextElement(QLatin1String("Directory"), str); } xmlFile.writeEndElement(); xmlFile.writeEndElement(); xmlFile.writeEndDocument(); return xmlFile.hasError(); } QHash<QString, QStringList> ROSUtils::getWorkspaceFiles(const Utils::FileName &workspaceDir) { QHash<QString, QStringList> workspaceFiles; Utils::FileName srcPath = workspaceDir; srcPath.appendPath(QLatin1String("src")); const QDir srcDir(srcPath.toString()); QString wsDir; QDirIterator itSrc(srcDir.absolutePath(), QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (itSrc.hasNext()) { wsDir = itSrc.next(); QFileInfoList dirFiles = QDir(wsDir).entryInfoList(QDir::Files | QDir::NoDotAndDotDot); if(dirFiles.count() == 0) { workspaceFiles[wsDir].append(QLatin1Literal("EMPTY_FOLDER")); } else { foreach (QFileInfo file, dirFiles) { workspaceFiles[wsDir].append(file.absoluteFilePath()); } } } return workspaceFiles; } QHash<QString, ROSUtils::FolderContent> ROSUtils::getFolderContent(const Utils::FileName &folderPath, QStringList &fileList) { QHash<QString, ROSUtils::FolderContent> workspaceFiles; ROSUtils::FolderContent content; QString folder = folderPath.toString(); // Get Directory data content.directories = QDir(folder).entryList(QDir::NoDotAndDotDot | QDir::Dirs); content.files = QDir(folder).entryList(QDir::NoDotAndDotDot | QDir::Files); workspaceFiles[folder] = content; foreach (QString file, content.files) { fileList.append(QDir(folder).absoluteFilePath(file)); } // Get SubDirectory Information const QDir srcDir(folder); QDirIterator itSrc(srcDir.absolutePath(), QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (itSrc.hasNext()) { folder = itSrc.next(); content.directories = QDir(folder).entryList(QDir::NoDotAndDotDot | QDir::Dirs); content.files = QDir(folder).entryList(QDir::NoDotAndDotDot | QDir::Files); workspaceFiles[folder] = content; foreach (QString file, content.files) { fileList.append(QDir(folder).absoluteFilePath(file)); } } return workspaceFiles; } QStringList ROSUtils::getWorkspaceIncludes(const Utils::FileName &workspaceDir, const QString &rosDistribution) { // Parse CodeBlocks Project File // Need to search for all of the tags <Add directory="include path" /> QStringList includePaths; QXmlStreamReader cbpXml; Utils::FileName cbpPath = workspaceDir; cbpPath.appendPath(QLatin1String("build")).appendPath(QLatin1String("Project.cbp")); QFile cbpFile(cbpPath.toString()); if (!cbpFile.open(QFile::ReadOnly | QFile::Text)) { qDebug() << "Error opening CodeBlocks Project File"; return includePaths; } cbpXml.setDevice(&cbpFile); cbpXml.readNext(); while(!cbpXml.atEnd()) { if(cbpXml.isStartElement()) { if(cbpXml.name() == QLatin1String("Add")) { foreach(const QXmlStreamAttribute &attr, cbpXml.attributes()) { if(attr.name().toString() == QLatin1String("directory")) { QString attribute_value = attr.value().toString(); if(!includePaths.contains(attribute_value)) { includePaths.append(attribute_value); } } } } } cbpXml.readNext(); } // Next search the source directory for any missed include folders Utils::FileName srcPath = workspaceDir; const QDir srcDir(srcPath.toString()); srcPath.appendPath(QLatin1String("src")); QString includePath; QDirIterator itSrc(srcDir.absolutePath(),QStringList() << QLatin1String("include"), QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (itSrc.hasNext()) { includePath = itSrc.next(); if(!includePaths.contains(includePath)) { includePaths.append(includePath); } } // Next search the devel directory for any missed include folders Utils::FileName develPath = workspaceDir; const QDir develDir(develPath.toString()); develPath.appendPath(QLatin1String("devel")); QDirIterator itDevel(develDir.absolutePath(),QStringList() << QLatin1String("include"), QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (itDevel.hasNext()) { includePath = itDevel.next(); if(!includePaths.contains(includePath)) { includePaths.append(includePath); } } return includePaths; } QMap<QString, QString> ROSUtils::getROSPackages(const QStringList &env) { QProcess process; QMap<QString, QString> package_map; QStringList tmp; process.setEnvironment(env); process.start(QLatin1String("bash")); process.waitForStarted(); QString cmd = QLatin1String("rospack list > /tmp/rosqtpackages.txt"); process.write(cmd.toLatin1()); process.closeWriteChannel(); process.waitForFinished(); if (process.exitStatus() != QProcess::CrashExit) { QFile package_file(QLatin1String("/tmp/rosqtpackages.txt")); if (package_file.open(QIODevice::ReadOnly)) { QTextStream package_stream(&package_file); while (!package_stream.atEnd()) { tmp = package_stream.readLine().split(QLatin1String(" ")); package_map.insert(tmp[0],tmp[1]); } package_file.close(); return package_map; } } return QMap<QString, QString>(); } QStringList ROSUtils::getROSPackageLaunchFiles(const QString &packagePath, bool OnlyNames) { QStringList launchFiles; if(!packagePath.isEmpty()) { const QDir srcDir(packagePath); QDirIterator it(srcDir.absolutePath(),QStringList() << QLatin1String("*.launch"), QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (it.hasNext()) { QFileInfo launchFile(it.next()); if(OnlyNames) { launchFiles.append(launchFile.fileName()); } else { launchFiles.append(launchFile.absoluteFilePath()); } } } return launchFiles; } QStringList ROSUtils::getROSPackageExecutables(const QString &packageName, const QStringList &env) { QProcess process; QStringList package_executables; QString package_executables_location; process.setEnvironment(env); process.start(QLatin1String("bash")); process.waitForStarted(); QString cmd = QLatin1String("catkin_find --without-underlays --libexec ") + packageName + QLatin1String(" > /tmp/rosqtexecutables.txt"); process.write(cmd.toLatin1()); process.closeWriteChannel(); process.waitForFinished(); if (process.exitStatus() != QProcess::CrashExit) { QFile executable_file(QLatin1String("/tmp/rosqtexecutables.txt")); if (executable_file.open(QIODevice::ReadOnly)) { QTextStream executable_stream(&executable_file); if (!executable_stream.atEnd()) { package_executables_location = executable_stream.readLine(); } executable_file.close(); if(!package_executables_location.isEmpty()) { const QDir srcDir(package_executables_location); QDirIterator it(srcDir.absolutePath(), QDir::Files | QDir::Executable | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (it.hasNext()) { QFileInfo executableFile(it.next()); package_executables.append(executableFile.fileName()); } return package_executables; } } } return QStringList(); } } //namespace Internal } //namespace ROSProjectManager
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include "core/CompileConfig.h" #if OUZEL_SUPPORTS_DIRECT3D11 #include "ShaderResourceD3D11.h" #include "RendererD3D11.h" #include "core/Engine.h" #include "utils/Log.h" namespace ouzel { namespace graphics { ShaderResourceD3D11::ShaderResourceD3D11() { } ShaderResourceD3D11::~ShaderResourceD3D11() { if (pixelShader) { pixelShader->Release(); } if (vertexShader) { vertexShader->Release(); } if (inputLayout) { inputLayout->Release(); } if (pixelShaderConstantBuffer) { pixelShaderConstantBuffer->Release(); } if (vertexShaderConstantBuffer) { vertexShaderConstantBuffer->Release(); } } bool ShaderResourceD3D11::uploadBuffer(ID3D11Buffer* buffer, const void* data, uint32_t size) { RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer()); D3D11_MAPPED_SUBRESOURCE mappedSubresource; HRESULT hr = rendererD3D11->getContext()->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedSubresource); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to lock Direct3D 11 buffer, error: " << hr; return false; } std::copy(static_cast<const uint8_t*>(data), static_cast<const uint8_t*>(data) + size, static_cast<uint8_t*>(mappedSubresource.pData)); rendererD3D11->getContext()->Unmap(buffer, 0); return true; } static DXGI_FORMAT getVertexFormat(DataType dataType, bool normalized) { switch (dataType) { case DataType::BYTE: return normalized ? DXGI_FORMAT_R8_SNORM : DXGI_FORMAT_R8_SINT; case DataType::BYTE_VECTOR2: return normalized ? DXGI_FORMAT_R8G8_SNORM : DXGI_FORMAT_R8G8_SINT; case DataType::BYTE_VECTOR3: return DXGI_FORMAT_UNKNOWN; case DataType::BYTE_VECTOR4: return normalized ? DXGI_FORMAT_R8G8B8A8_SNORM : DXGI_FORMAT_R8G8B8A8_SINT; case DataType::UNSIGNED_BYTE: return normalized ? DXGI_FORMAT_R8_UNORM : DXGI_FORMAT_R8_UINT; case DataType::UNSIGNED_BYTE_VECTOR2: return normalized ? DXGI_FORMAT_R8G8_UNORM : DXGI_FORMAT_R8G8_UINT; case DataType::UNSIGNED_BYTE_VECTOR3: return DXGI_FORMAT_UNKNOWN; case DataType::UNSIGNED_BYTE_VECTOR4: return normalized ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_R8G8B8A8_UINT; case DataType::SHORT: return normalized ? DXGI_FORMAT_R16_SNORM : DXGI_FORMAT_R16_SINT; case DataType::SHORT_VECTOR2: return normalized ? DXGI_FORMAT_R16G16_SNORM : DXGI_FORMAT_R16G16_SINT; case DataType::SHORT_VECTOR3: return DXGI_FORMAT_UNKNOWN; case DataType::SHORT_VECTOR4: return normalized ? DXGI_FORMAT_R16G16B16A16_SNORM : DXGI_FORMAT_R16G16B16A16_SINT; case DataType::UNSIGNED_SHORT: return normalized ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R16_UINT; case DataType::UNSIGNED_SHORT_VECTOR2: return normalized ? DXGI_FORMAT_R16G16_UNORM : DXGI_FORMAT_R16G16_UINT; case DataType::UNSIGNED_SHORT_VECTOR3: return DXGI_FORMAT_UNKNOWN; case DataType::UNSIGNED_SHORT_VECTOR4: return normalized ? DXGI_FORMAT_R16G16B16A16_UNORM : DXGI_FORMAT_R16G16B16A16_UINT; case DataType::INTEGER: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32_SINT; case DataType::INTEGER_VECTOR2: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32_SINT; case DataType::INTEGER_VECTOR3: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32B32_SINT; case DataType::INTEGER_VECTOR4: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32B32A32_SINT; case DataType::UNSIGNED_INTEGER: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32_UINT; case DataType::UNSIGNED_INTEGER_VECTOR2: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32_UINT; case DataType::UNSIGNED_INTEGER_VECTOR3: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32B32_UINT; case DataType::UNSIGNED_INTEGER_VECTOR4: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32B32A32_UINT; case DataType::FLOAT: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32_FLOAT; case DataType::FLOAT_VECTOR2: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32_FLOAT; case DataType::FLOAT_VECTOR3: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32B32_FLOAT; case DataType::FLOAT_VECTOR4: return normalized ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32G32B32A32_FLOAT; default: return DXGI_FORMAT_UNKNOWN; } } bool ShaderResourceD3D11::upload() { std::lock_guard<std::mutex> lock(uploadMutex); if (dirty) { RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer()); if (pixelShader) { pixelShader->Release(); pixelShader = nullptr; } if (vertexShader) { vertexShader->Release(); vertexShader = nullptr; } if (inputLayout) { inputLayout->Release(); inputLayout = nullptr; } if (pixelShaderConstantBuffer) { pixelShaderConstantBuffer->Release(); pixelShaderConstantBuffer = nullptr; } if (vertexShaderConstantBuffer) { vertexShaderConstantBuffer->Release(); vertexShaderConstantBuffer = nullptr; } HRESULT hr = rendererD3D11->getDevice()->CreatePixelShader(pixelShaderData.data(), pixelShaderData.size(), NULL, &pixelShader); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create a Direct3D 11 pixel shader, error: " << hr; return false; } hr = rendererD3D11->getDevice()->CreateVertexShader(vertexShaderData.data(), vertexShaderData.size(), NULL, &vertexShader); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create a Direct3D 11 vertex shader, error: " << hr; return false; } std::vector<D3D11_INPUT_ELEMENT_DESC> vertexInputElements; UINT offset = 0; for (const VertexAttribute& vertexAttribute : vertexAttributes) { DXGI_FORMAT vertexFormat = getVertexFormat(vertexAttribute.dataType, vertexAttribute.normalized); if (vertexFormat == DXGI_FORMAT_UNKNOWN) { Log(Log::Level::ERR) << "Invalid vertex format"; return false; } const char* usage; switch (vertexAttribute.usage) { case VertexAttribute::Usage::BINORMAL: usage = "BINORMAL"; break; case VertexAttribute::Usage::BLEND_INDICES: usage = "BLENDINDICES"; break; case VertexAttribute::Usage::BLEND_WEIGHT: usage = "BLENDWEIGHT"; break; case VertexAttribute::Usage::COLOR: usage = "COLOR"; break; case VertexAttribute::Usage::NORMAL: usage = "NORMAL"; break; case VertexAttribute::Usage::POSITION: usage = "POSITION"; break; case VertexAttribute::Usage::POSITION_TRANSFORMED: usage = "POSITIONT"; break; case VertexAttribute::Usage::POINT_SIZE: usage = "PSIZE"; break; case VertexAttribute::Usage::TANGENT: usage = "TANGENT"; break; case VertexAttribute::Usage::TEXTURE_COORDINATES: usage = "TEXCOORD"; break; default: Log(Log::Level::ERR) << "Invalid vertex attribute usage"; return false; } vertexInputElements.push_back({ usage, vertexAttribute.index, vertexFormat, 0, offset, D3D11_INPUT_PER_VERTEX_DATA, 0 }); offset += getDataTypeSize(vertexAttribute.dataType); } hr = rendererD3D11->getDevice()->CreateInputLayout( vertexInputElements.data(), static_cast<UINT>(vertexInputElements.size()), vertexShaderData.data(), vertexShaderData.size(), &inputLayout); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 input layout for vertex shader, error: " << hr; return false; } if (!pixelShaderConstantInfo.empty()) { pixelShaderConstantLocations.clear(); pixelShaderConstantLocations.reserve(pixelShaderConstantInfo.size()); pixelShaderConstantSize = 0; for (const Shader::ConstantInfo& info : pixelShaderConstantInfo) { pixelShaderConstantLocations.push_back({pixelShaderConstantSize, info.size}); pixelShaderConstantSize += info.size; } } D3D11_BUFFER_DESC pixelShaderConstantBufferDesc; pixelShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(pixelShaderConstantSize); pixelShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; pixelShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; pixelShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; pixelShaderConstantBufferDesc.MiscFlags = 0; pixelShaderConstantBufferDesc.StructureByteStride = 0; hr = rendererD3D11->getDevice()->CreateBuffer(&pixelShaderConstantBufferDesc, nullptr, &pixelShaderConstantBuffer); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 constant buffer, error: " << hr; return false; } if (!vertexShaderConstantInfo.empty()) { vertexShaderConstantLocations.clear(); vertexShaderConstantLocations.reserve(vertexShaderConstantInfo.size()); vertexShaderConstantSize = 0; for (const Shader::ConstantInfo& info : vertexShaderConstantInfo) { vertexShaderConstantLocations.push_back({vertexShaderConstantSize, info.size}); vertexShaderConstantSize += info.size; } } D3D11_BUFFER_DESC vertexShaderConstantBufferDesc; vertexShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(vertexShaderConstantSize); vertexShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; vertexShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; vertexShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexShaderConstantBufferDesc.MiscFlags = 0; vertexShaderConstantBufferDesc.StructureByteStride = 0; hr = rendererD3D11->getDevice()->CreateBuffer(&vertexShaderConstantBufferDesc, nullptr, &vertexShaderConstantBuffer); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 constant buffer, error: " << hr; return false; } dirty = 0; } return true; } } // namespace graphics } // namespace ouzel #endif
#ifndef _PLAYER_KEYBOARD_CONTROL_COMPONENT_H_ #define _PLAYER_KEYBOARD_CONTROL_COMPONENT_H_ #include "TransformComponent.h" #include "InputComponent.h" #include "GameObject.h" //Input handling component for the player. This is unique to the player object and does not exist anywhere else. class PlayerKeyboardControlComponent : public InputComponent { private: bool m_Enabled_ = true; TransformComponent * m_ParentTransform_; public: PlayerKeyboardControlComponent(GameObject * pParent); virtual void Update(double dt); virtual void LateUpdate(double dt); virtual void Destroy(); virtual void Start(); //Check if the component is enabled to read inputs. bool isEnabled() { return m_Enabled_; } //Toggle if the component is enabled or not. void toggleEnabled(bool pToggle) { m_Enabled_ = pToggle; } }; #endif
#ifndef GLOBALS_H #define GLOBALS_H #include <functional> #include <string> typedef std::basic_string<uint8_t> Bytes; #define VERSION "0.1" #define SlowBaudRate 19200 /* Global options. */ extern bool Verbose; extern const char* SerialPort; /* Utilities. */ extern void error(const char* message, ...); extern void verbose(const char* message, ...); extern void warning(const char* message, ...); extern std::string aprintf(const char* fmt, ...); extern void resettimer(); extern double gettime(); extern void pad_with_nops(Bytes& stub); extern void writebe16(uint8_t* dest, uint16_t value); extern void writebe32(uint8_t* dest, uint32_t value); extern uint16_t readbe16(const uint8_t* ptr); extern uint32_t readbe32(const uint8_t* ptr); extern void hexdump(uint32_t address, const uint8_t* data, size_t size); /* Serial port management. */ extern void logon(); extern void dodgyterm(); extern void sendbyte(uint8_t c); extern void send(const std::string& s); extern uint8_t recvbyte(); extern bool recvpending(); /* B-record protocol. */ extern void brecord_execute(uint32_t addr); extern void brecord_write(uint32_t addr, uint8_t count, const uint8_t* data); extern void brecord_write_bytes(uint32_t addr, uint8_t count, uint8_t value); /* Operations */ extern Bytes buffer_read(uint32_t start, uint32_t length); extern void cmd_cs(char** argv); extern void cmd_dump(char** argv); extern void cmd_execute(char** argv); extern void cmd_fill(char** argv); extern void cmd_getsp(char** argv); extern void cmd_ping(char** argv); extern void cmd_read(char** argv); extern void cmd_setreg(char** argv); extern void cmd_showreg(char** argv); extern void cmd_write(char** argv); #endif
#pragma once #include "State.h" #include "Font.h" enum { MM_SINGLE, MM_HIGH, MM_OPTIONS, MM_QUIT, }; class NewGame; class MainMenu final : public State { public: MainMenu(NewGame *game); ~MainMenu() final; void Enter() final; void Update(float dt) final; void Draw() final; void Exit() final; private: void setHot(int n); NewGame *m_game = nullptr; std::unique_ptr<Font> m_title; std::unique_ptr<Font> m_opt; std::unique_ptr<Font> m_opt2; std::vector<std::string> m_options; int m_hot; };
#include "pch.h" #include "data_structure.h" #define M_PI 3.14159265358979323846 /* pi */ bool kinect_data::full_frame() { for (int i = 0; i < number_of_joints; i++) { if (needed_joints[i].joint_name == -1) { return false; } } return true; } void kinect_data::print_data() { //if (full_frame()) //{ std::cout << "kinect data: " << std::endl; for (int i = 0; i < number_of_joints; i++) { std::cout << "\t " << needed_joints[i].joint_name << ": " << joint_Enum_ToStr(needed_joint[i], "ita") << " x->" << needed_joints[i].position[0] << " y->" << needed_joints[i].position[1] << " z->" << needed_joints[i].position[2] << std::endl; } std::cout << "\t time: " << frame_time << std::endl << std::endl; //} } float kinect_data::jointAngleX(float *P1, float *P2) { float alfa = (180 / M_PI)*atan((((P2[1] - P1[1]))) / ((P2[2] - P1[2]))); if (((P2[2] - P1[2])) > 0) { return alfa; //risultato in gradi } else { return alfa + 180.0f; //risultato in gradi } } float kinect_data::jointAngleY(float *P1, float *P2) { float beta = (180 / M_PI)*atan(((P2[0] - P1[0])) / (-(P2[2] - P1[2]))); if ((-(P2[2] - P1[2])) > 0) { return beta; //risultato in gradi } else { return beta /*+ 180.0f*/; //risultato in gradi } } float kinect_data::jointAngleZ(float *P1, float *P2) { float alfa = (180 / M_PI)*atan((((P2[1] - P1[1]))) / (-(P2[2] - P1[2]))); if ((-(P2[2] - P1[2])) > 0) { return alfa; //risultato in gradi } else { return alfa + 180.0f; //risultato in gradi } } void kinect_data::updateAngles() { for (int i = 0; i < number_of_joints; i++) { if (needed_joints[i].to_joint != -1) { //calcolo gli angoloi solo per i nodi con un nodo figlio if (i == 6) { //schiena needed_joints[i].angle[0] = ref_Ang_x[i] + jointAngleX(needed_joints[i].position, needed_joints[to_ref_joint[needed_joints[i].to_joint]].position); needed_joints[i].angle[1] = ref_Ang_y[i]; needed_joints[i].angle[2] = ref_Ang_z[i] + jointAngleY(needed_joints[i].position, needed_joints[to_ref_joint[needed_joints[i].to_joint]].position); } else { //braccia needed_joints[i].angle[0] = 0; needed_joints[i].angle[1] = mul_fctor_y[i] * (ref_Ang_y[i] + jointAngleY(needed_joints[i].position, needed_joints[to_ref_joint[needed_joints[i].to_joint]].position)); needed_joints[i].angle[2] = mul_fctor_z[i] * (ref_Ang_z[i] + jointAngleZ(needed_joints[i].position, needed_joints[to_ref_joint[needed_joints[i].to_joint]].position)); } } else { //cout << "giunto " << needed_joint[i] << " non possiede un giunto successivo" << endl; } } } std::string kinect_data::joint_Enum_ToStr(int n, std::string language) { std::string name_ita("unknown"); std::string name_eng("unknown"); switch (n) { case 0: name_eng = "Spine Base"; name_ita = "Base della colonna vertebrale"; break; case 1: name_eng = "Spine Mid"; name_ita = "centro colonna vertebrtale"; break; case 2: name_eng = "Neck"; name_ita = "collo"; break; case 3: name_eng = "Head"; name_ita = "testa"; break; case 4: name_eng = "Shoulder Left"; name_ita = "Spalla sinistra"; break; case 5: name_eng = "Elbow Left"; name_ita = "Gomito sinistro"; break; case 6: name_eng = "Wrist Left"; name_ita = "Polso sinistro"; break; case 7: name_eng = "Hand Left"; name_ita = "mano sinistra"; break; case 8: name_eng = "Shoulder Right"; name_ita = "Mano destra"; break; case 9: name_eng = "Elbow Right"; name_ita = "gomito destro"; break; case 10: name_eng = "Wrist Right"; name_ita = "Polso destro"; break; case 11: name_eng = "Hand Right"; name_ita = "Mano destra"; break; case 12: name_eng = "Hip Left"; name_ita = "Anca sinistra"; break; case 13: name_eng = "Knee Left"; name_ita = "ginocchio sinistro"; break; case 14: name_eng = "Ankle Left"; name_ita = "caviglia sinistra"; break; case 15: name_eng = "Foot Left"; name_ita = "piede sinistro"; break; case 16: name_eng = "Hip Right"; name_ita = "Anca destra"; break; case 17: name_eng = "Knee Right"; name_ita = "ginocchio destro"; break; case 18: name_eng = "Ankle Right"; name_ita = "caviglia destra"; break; case 19: name_eng = "Foot Right"; name_ita = "Piede destro"; break; case 20: name_eng = "Spine Shoulder"; name_ita = "Spina dorsale"; break; case 21: name_eng = "Hand Tip Left"; name_ita = "Punta della mano sinistra"; break; case 22: name_eng = "Thumb Left"; name_ita = "pollice sinistro"; break; case 23: name_eng = "Hand Tip Right"; name_ita = "Punta mano destra"; break; case 24: name_eng = "Thumb Right"; name_ita = "pollice destro"; break; } if (language == "eng") { return name_eng; } else if (language == "ita") { return name_ita; } } void arduino_data::print_data() { std::cout << "arduino data: " << std::endl << "\t acc_xyz: " << acc_xyz[0] << "\t" << acc_xyz[1] << "\t" << acc_xyz[2] << std::endl << "\t gy_xyz: " << gy_xyz[0] << "\t" << gy_xyz[1] << "\t" << gy_xyz[2] << std::endl << "\t magn_xyz: " << magn_xyz[0] << "\t" << magn_xyz[1] << "\t" << magn_xyz[2] << std::endl << "\t temp: " << temp << std::endl << "\t time: " << frame_time << std::endl << std::endl; } template<typename type_in, std::size_t N, typename type_out, std::size_t M> void dataset_data< type_in, N, type_out, M>::print_data() { std::cout << std::endl << "input" << std::endl; for (auto i : in) { std::cout << i << " "; } std::cout << std::endl << "output" << std::endl; for (auto i : out) { std::cout << i << " "; } std::cout << std::endl << std::endl; }
#include <stdio.h> #include <iostream> using namespace std; int main(){ int n, i, score=0; cin>>n; int a[n], b[n]; for(i=0; i<n; i++){ cin>>a[i]; } for(i=0; i<n; i++){ cin>>b[i]; if(a[i]>b[i]){ score+=3; } else if(a[i]==b[i]){ score+=1; } } cout<<score<<endl; return 0; }
#pragma once #include "GameState.h" const int NUM_OF_MENU = 4; class MainMenu : public GameState { public: MainMenu(int windowWidth, int windowHeight); void Update(sf::RenderWindow* window); void Draw(sf::RenderWindow *window); private: sf::Texture texture; sf::Sprite sprite; sf::Font *font; sf::Text title; sf::Text menu[NUM_OF_MENU]; int selected; };
#include "ColormapWin.h" ColormapWin::ColormapWin(QWidget *parent) :QDialog(parent) { ui.setupUi(this); connect(ui.yesBtn, SIGNAL(clicked()), this, SLOT(yesBtnPressed())); connect(ui.noBtn, SIGNAL(clicked()), this, SLOT(noBtnPressed())); } ColormapWin::~ColormapWin() { } void ColormapWin::yesBtnPressed() { ColormapClass cc; cc.max = ui.maxLineedit->text().toShort(); cc.min = ui.minLineedit->text().toShort(); if (ui.radioButton_0->isChecked()) cc.type = 0; else if (ui.radioButton_1->isChecked()) cc.type = 1; else if (ui.radioButton_2->isChecked()) cc.type = 2; else if (ui.radioButton_4->isChecked()) cc.type = 4; else if (ui.radioButton_9->isChecked()) cc.type = 9; else if (ui.radioButton_11->isChecked()) cc.type = 11; else this->close(); emit infoSend(cc); this->close(); } void ColormapWin::noBtnPressed() { this->close(); }
#ifndef DYNAMICCOREHANDLER_H #define DYNAMICCOREHANDLER_H #include <dlfcn.h> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include "../DynamicLibraryLoader/dynamic_library_loader.hpp" #include "../Multigraph/MultiGraph.h" #include "DynamicCore.h" class DynamicCoreHandler { DynamicLibraryLoader< NamedFunctionSignature<"create", DynamicCore *(const parameterType &parameters)>, NamedFunctionSignature<"metadata", std::map<std::string, std::string> *()>> lib; std::unique_ptr<std::map<std::string, std::string>> metadata; public: DynamicCoreHandler(const std::string &so_path) : lib(so_path), metadata(lib.call<"metadata">()) {} const std::map<std::string, std::string> &get_metadata() const { return *metadata; } std::unique_ptr<DynamicCore> create(const parameterType &parameters) const { return std::unique_ptr<DynamicCore>(lib.call<"create">(parameters)); } }; #endif
#include <iostream> #include <cmath> using namespace std; int main() { int k = 1; double t = 1; int sum = 0; while (t < 9) { t = 10.0/pow(10, 1.0/k); sum = sum + (10 - t); k++; } cout << sum << endl; return 0; }
/** * @brief Deals with in game mechanisms and subsystems * @file BaseLogic.h * @author matthewpoletin */ #pragma once #include "ILogic.h" #include "../../Levels/LevelManager.h" #include "../../Actors/ActorFactory.h" #include "../../Input/InputManager.h" #include "../../Utilities/Timer/Timer.h" namespace liman { class LevelManager; class ActorFactory; class BaseLogic : public ILogic { public: BaseLogic(); ~BaseLogic(); public: virtual bool VInit(void); public: virtual bool VLoadGame(const char* levelName); public: LevelManager* GetLevelManager(); ActorFactory* GetActorFactory(); InputManager* GetInputManager() { return m_pInputManager; } Timer* GetTimer() { return m_pTimer; } protected: LevelManager* m_pLevelManager; ActorFactory* m_pActorFactory; InputManager* m_pInputManager; // TIP: ingame time (may be paused during the application is running) Timer* m_pTimer; }; }
#ifndef __SCREEN_H__ #define __SCREEN_H__ #include <string> class Screen { public: typedef std::string::size_type pos; Screen() = default; Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c) {} char get() const { return contents[cursor]; } inline char get(pos ht, pos wd) const; Screen &move(pos r, pos c); private: pos cursor = 0; pos height = 0, width = 0; std::string contents; }; #endif
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> // C RunTime Header Files #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <mfidl.h> #include <mfapi.h> #include <mmdeviceapi.h> #include <mferror.h> #include <stdio.h> #include <assert.h> #include <Evntprov.h> #include <evntrace.h> #include <iostream> #include <sstream> #include <tuple> #include <uuids.h> #define DECL_TUPLE(x) {x, _T(#x)} #define CHECK_HR(hr) if(FAILED((hr)))goto done #define MediaEventType_Name(x) (\ (x) == MEUnknown? _T("MEUnknown"):(\ (x) == MEError?_T("MEError"):(\ (x) == MEExtendedType?_T("MEExtendedType"):(\ (x) == MENonFatalError?_T("MENonFatalError"):(\ (x) == MESessionUnknown?_T("MESessionUnknown"):(\ (x) == MESessionTopologySet?_T("MESessionTopologySet"):(\ (x) == MESessionTopologiesCleared?_T("MESessionTopologiesCleared"):(\ (x) == MESessionStarted?_T("MESessionStarted"):(\ (x) == MESessionPaused?_T("MESessionPaused"):(\ (x) == MESessionStopped?_T("MESessionStopped"):(\ (x) == MESessionClosed?_T("MESessionClosed"):(\ (x) == MESessionEnded?_T("MESessionEnded"):(\ (x) == MESessionRateChanged?_T("MESessionRateChanged"):(\ (x) == MESessionScrubSampleComplete?_T("MESessionScrubSampleComplete"):(\ (x) == MESessionCapabilitiesChanged?_T("MESessionCapabilitiesChanged"):(\ (x) == MESessionTopologyStatus?_T("MESessionTopologyStatus"):(\ (x) == MESessionNotifyPresentationTime?_T("MESessionNotifyPresentationTime"):(\ (x) == MENewPresentation?_T("MENewPresentation"):(\ (x) == MELicenseAcquisitionStart?_T("MELicenseAcquisitionStart"):(\ (x) == MELicenseAcquisitionCompleted?_T("MELicenseAcquisitionCompleted"):(\ (x) == MEIndividualizationStart?_T("MEIndividualizationStart"):(\ (x) == MEIndividualizationCompleted?_T("MEIndividualizationCompleted"):(\ (x) == MEEnablerProgress?_T("MEEnablerProgress"):(\ (x) == MEEnablerCompleted?_T("MEEnablerCompleted"):(\ (x) == MEPolicyError?_T("MEPolicyError"):(\ (x) == MEPolicyReport?_T("MEPolicyReport"):(\ (x) == MEBufferingStarted?_T("MEBufferingStarted"):(\ (x) == MEBufferingStopped?_T("MEBufferingStopped"):(\ (x) == MEConnectStart?_T("MEConnectStart"):(\ (x) == MEConnectEnd?_T("MEConnectEnd"):(\ (x) == MEReconnectStart?_T("MEReconnectStart"):(\ (x) == MEReconnectEnd?_T("MEReconnectEnd"):(\ (x) == MERendererEvent?_T("MERendererEvent"):(\ (x) == MESessionStreamSinkFormatChanged?_T("MESessionStreamSinkFormatChanged"):(\ (x) == MESourceUnknown?_T("MESourceUnknown"):(\ (x) == MESourceStarted?_T("MESourceStarted"):(\ (x) == MEStreamStarted?_T("MEStreamStarted"):(\ (x) == MESourceSeeked?_T("MESourceSeeked"):(\ (x) == MEStreamSeeked?_T("MEStreamSeeked"):(\ (x) == MENewStream?_T("MENewStream"):(\ (x) == MEUpdatedStream?_T("MEUpdatedStream"):(\ (x) == MESourceStopped?_T("MESourceStopped"):(\ (x) == MEStreamStopped?_T("MEStreamStopped"):(\ (x) == MESourcePaused?_T("MESourcePaused"):(\ (x) == MEStreamPaused?_T("MEStreamPaused"):(\ (x) == MEEndOfPresentation?_T("MEEndOfPresentation"):(\ (x) == MEEndOfStream?_T("MEEndOfStream"):(\ (x) == MEMediaSample?_T("MEMediaSample"):(\ (x) == MEStreamTick?_T("MEStreamTick"):(\ (x) == MEStreamThinMode?_T("MEStreamThinMode"):(\ (x) == MEStreamFormatChanged?_T("MEStreamFormatChanged"):(\ (x) == MESourceRateChanged?_T("MESourceRateChanged"):(\ (x) == MEEndOfPresentationSegment?_T("MEEndOfPresentationSegment"):(\ (x) == MESourceCharacteristicsChanged?_T("MESourceCharacteristicsChanged"):(\ (x) == MESourceRateChangeRequested?_T("MESourceRateChangeRequested"):(\ (x) == MESourceMetadataChanged?_T("MESourceMetadataChanged"):(\ (x) == MESequencerSourceTopologyUpdated?_T("MESequencerSourceTopologyUpdated"):(\ (x) == MESinkUnknown?_T("MESinkUnknown"):(\ (x) == MEStreamSinkStarted?_T("MEStreamSinkStarted"):(\ (x) == MEStreamSinkStopped?_T("MEStreamSinkStopped"):(\ (x) == MEStreamSinkPaused?_T("MEStreamSinkPaused"):(\ (x) == MEStreamSinkRateChanged?_T("MEStreamSinkRateChanged"):(\ (x) == MEStreamSinkRequestSample?_T("MEStreamSinkRequestSample"):(\ (x) == MEStreamSinkMarker?_T("MEStreamSinkMarker"):(\ (x) == MEStreamSinkPrerolled?_T("MEStreamSinkPrerolled"):(\ (x) == MEStreamSinkScrubSampleComplete?_T("MEStreamSinkScrubSampleComplete"):(\ (x) == MEStreamSinkFormatChanged?_T("MEStreamSinkFormatChanged"):(\ (x) == MEStreamSinkDeviceChanged?_T("MEStreamSinkDeviceChanged"):(\ (x) == MEQualityNotify?_T("MEQualityNotify"):(\ (x) == MESinkInvalidated?_T("MESinkInvalidated"):(\ (x) == MEAudioSessionNameChanged?_T("MEAudioSessionNameChanged"):(\ (x) == MEAudioSessionVolumeChanged?_T("MEAudioSessionVolumeChanged"):(\ (x) == MEAudioSessionDeviceRemoved?_T("MEAudioSessionDeviceRemoved"):(\ (x) == MEAudioSessionServerShutdown?_T("MEAudioSessionServerShutdown"):(\ (x) == MEAudioSessionGroupingParamChanged?_T("MEAudioSessionGroupingParamChanged"):(\ (x) == MEAudioSessionIconChanged?_T("MEAudioSessionIconChanged"):(\ (x) == MEAudioSessionFormatChanged?_T("MEAudioSessionFormatChanged"):(\ (x) == MEAudioSessionDisconnected?_T("MEAudioSessionDisconnected"):(\ (x) == MEAudioSessionExclusiveModeOverride?_T("MEAudioSessionExclusiveModeOverride"):(\ (x) == MECaptureAudioSessionVolumeChanged?_T("MECaptureAudioSessionVolumeChanged"):(\ (x) == MECaptureAudioSessionDeviceRemoved?_T("MECaptureAudioSessionDeviceRemoved"):(\ (x) == MECaptureAudioSessionFormatChanged?_T("MECaptureAudioSessionFormatChanged"):(\ (x) == MECaptureAudioSessionDisconnected?_T("MECaptureAudioSessionDisconnected"):(\ (x) == MECaptureAudioSessionExclusiveModeOverride?_T("MECaptureAudioSessionExclusiveModeOverride"):(\ (x) == MECaptureAudioSessionServerShutdown?_T("MECaptureAudioSessionServerShutdown"):(\ (x) == METrustUnknown?_T("METrustUnknown"):(\ (x) == MEPolicyChanged?_T("MEPolicyChanged"):(\ (x) == MEContentProtectionMessage?_T("MEContentProtectionMessage"):(\ (x) == MEPolicySet?_T("MEPolicySet"):(\ (x) == MEWMDRMLicenseBackupCompleted?_T("MEWMDRMLicenseBackupCompleted"):(\ (x) == MEWMDRMLicenseBackupProgress?_T("MEWMDRMLicenseBackupProgress"):(\ (x) == MEWMDRMLicenseRestoreCompleted?_T("MEWMDRMLicenseRestoreCompleted"):(\ (x) == MEWMDRMLicenseRestoreProgress?_T("MEWMDRMLicenseRestoreProgress"):(\ (x) == MEWMDRMLicenseAcquisitionCompleted?_T("MEWMDRMLicenseAcquisitionCompleted"):(\ (x) == MEWMDRMIndividualizationCompleted?_T("MEWMDRMIndividualizationCompleted"):(\ (x) == MEWMDRMIndividualizationProgress?_T("MEWMDRMIndividualizationProgress"):(\ (x) == MEWMDRMProximityCompleted?_T("MEWMDRMProximityCompleted"):(\ (x) == MEWMDRMLicenseStoreCleaned?_T("MEWMDRMLicenseStoreCleaned"):(\ (x) == MEWMDRMRevocationDownloadCompleted?_T("MEWMDRMRevocationDownloadCompleted"):(\ (x) == METransformUnknown?_T("METransformUnknown"):(\ (x) == METransformNeedInput?_T("METransformNeedInput"):(\ (x) == METransformHaveOutput? _T("METransformHaveOutput") : (\ (x) == METransformDrainComplete? _T("METransformDrainComplete") : (\ (x) == METransformMarker? _T("METransformMarker") : (\ (x) == MEByteStreamCharacteristicsChanged?_T("MEByteStreamCharacteristicsChanged"):(\ (x) == MEVideoCaptureDeviceRemoved?_T("MEVideoCaptureDeviceRemoved"):(\ (x) == MEVideoCaptureDevicePreempted?_T("MEVideoCaptureDevicePreempted"):(\ (x) == MEStreamSinkFormatInvalidated?_T("MEStreamSinkFormatInvalidated"):(\ (x) == MEEncodingParameters?_T("MEEncodingParameters"):(\ (x) == MEContentProtectionMetadata?_T("MEContentProtectionMetadata"):_T("Reserved"))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) #define TopoStatus_Name(x) (\ (x) == MF_TOPOSTATUS_INVALID?_T("MF_TOPOSTATUS_INVALID"):(\ (x) == MF_TOPOSTATUS_READY?_T("MF_TOPOSTATUS_READY"):(\ (x) == MF_TOPOSTATUS_STARTED_SOURCE?_T("MF_TOPOSTATUS_STARTED_SOURCE"):(\ (x) == MF_TOPOSTATUS_DYNAMIC_CHANGED?_T("MF_TOPOSTATUS_DYNAMIC_CHANGED"):(\ (x) == MF_TOPOSTATUS_SINK_SWITCHED?_T("MF_TOPOSTATUS_SINK_SWITCHED"):(\ (x) == MF_TOPOSTATUS_ENDED?_T("MF_TOPOSTATUS_ENDED"):_T("Unknown Status"))))))) #define IS_RATE_ZERO(rate) ((rate) > -0.01f && (rate) < 0.01f) #define IS_UNMUTE_RATE(rate) ((rate) > 0.99f && (rate) < 1.01f) #define IS_RATE(rate1, rate2) ((rate1 - rate2 > -0.01f) && (rate1 -rate2 < 0.01f)) template<typename T> #ifdef _UNICODE inline std::wstring GetBitsString(std::tuple<T, const TCHAR*>* bit_names, size_t bits_count, T bits_value) #else inline std::string GetBitsString(std::tuple<T, const TCHAR*>* bit_names, size_t bits_count, T bits_value) #endif { bool bFirst = true; #ifdef _UNICODE std::wostringstream oss; #else std::ostringstream oss; #endif for (int idxBit = 0; idxBit < bits_count; idxBit++) { if (std::get<0>(bit_names[idxBit])&bits_value) { oss << (bFirst ? _T("") : _T(", ")) << std::get<1>(bit_names[idxBit]); if (bFirst) bFirst = false; } } oss << std::ends; return oss.str(); } #define DP0(x, ...) {\ TCHAR szLogOutput[1024];\ _stprintf_s(szLogOutput, 1024, x, ##__VA_ARGS__);\ _tprintf(szLogOuptut);\ OutputDebugString(szLogOutput);\ } #define DPA0(x, ...) {\ char szLogOutput[1024];\ sprintf_s(szLogOutput, 1024, x, ##__VA_ARGS__);\ printf(szLogOutput);\ OutputDebugStringA(szLogOutput);\ } #define DP(x, ...) {\ TCHAR szLogOutput[1024];\ _stprintf_s(szLogOutput, 1024, x, ##__VA_ARGS__);\ _tprintf(szLogOutput);\ OutputDebugString(szLogOutput);\ EventWriteString(g_ETWHandle, 0, 0, szLogOutput);\ } #define DPA(x, ...) {\ char szLogOutput[1024];\ stprintf_s(szLogOutput, 1024, x, ##__VA_ARGS__);\ printf(szLogOutput);\ OutputDebugStringA(szLogOutput);\ EventWriteStringA(g_ETWHandle, 0, 0, szLogOutput);\ } // TODO: reference additional headers your program requires here
#include "rendering.h" namespace Rendering { int RenderModule::MakeWindow(int width, int height, const char* title) { printf("Gets here 1"); m_Title = title; m_Width = width; m_Height = height; m_CursorFocused = false; m_Camera = new Camera(glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0)); if (!glfwInit()) { return -1; } glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); printf("Gets here 2"); m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL, NULL); if (!m_Window) { return -2; } printf("Gets here 3"); glfwMakeContextCurrent(m_Window); glfwSetWindowUserPointer(m_Window, this); glfwSetFramebufferSizeCallback(m_Window, window_resize); glfwSetKeyCallback(m_Window, key_callback); glfwSetMouseButtonCallback(m_Window, mouse_button_callback); glfwSetCursorPosCallback(m_Window, cursor_position_callback); glfwSetWindowCloseCallback(m_Window, window_close_callback); glfwSetWindowFocusCallback(m_Window, window_loss_focus_callback); glfwSwapInterval(0); printf("Gets here 4"); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { return -3; } printf("Gets here 5"); m_WorldShader = new Shader(ReadFile("Resources\\Shaders\\World.vs").c_str(), ReadFile("Resources\\Shaders\\World.fs").c_str()); m_PPShader = new Shader(ReadFile("Resources\\Shaders\\PP.vs").c_str(), ReadFile("Resources\\Shaders\\PP.fs").c_str()); m_GUIShader = new Shader(ReadFile("Resources\\Shaders\\GUI.vs").c_str(), ReadFile("Resources\\Shaders\\GUI.fs").c_str()); m_PPBuffer = new FrameBuffer(1280, 720); glEnable(GL_DEPTH_TEST); // glEnable(GL_CULL_FACE); // glCullFace(GL_FRONT); // glFrontFace(GL_CW); glEnable(GL_FRAMEBUFFER_SRGB); glEnable(GL_MULTISAMPLE); printf("Gets here 6"); m_GUI = new GUI(glm::vec3(0), glm::vec3(0)); glGenVertexArrays(1, &m_SquareModelID); glBindVertexArray(m_SquareModelID); GLfloat vertices[] = { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f }; GLfloat textures[] = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f }; m_SquareModelSize = sizeof(vertices) / sizeof(vertices[0]); GLuint vboID; glGenBuffers(1, &vboID); glBindBuffer(GL_ARRAY_BUFFER, vboID); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glGenBuffers(1, &vboID); glBindBuffer(GL_ARRAY_BUFFER, vboID); glBufferData(GL_ARRAY_BUFFER, sizeof(textures), textures, GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0); glBindVertexArray(0); m_TerrainTexture = new Texture("Resources\\Data\\1\\1.png"); return 0; } int RenderModule::AddModel(const char* source) { Model* m = new Model(source); if (m->GetSize() > 0) m_Models.push_back(m); return 0; } int RenderModule::AddTexture(const char* source) { Texture* text = new Texture(source); m_Textures.push_back(text); return 0; } bool RenderModule::IsKeyPressed(unsigned int keycode) const { if (keycode >= MAX_KEYS) return false; return m_Keys[keycode]; } bool RenderModule::IsKeyTyped(unsigned int keycode) const { if (keycode >= MAX_KEYS) return false; return m_KeyTyped[keycode]; } bool RenderModule::IsMouseButtonPressed(unsigned int button) const { if (button >= MAX_BUTTONS) return false; return m_MouseButtons[button]; } bool RenderModule::IsMouseButtonClicked(unsigned int button) const { if (button >= MAX_BUTTONS) return false; return m_MouseClicked[button]; } void window_resize(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); RenderModule* win = (RenderModule*)glfwGetWindowUserPointer(window); win->m_Width = width; win->m_Height = height; win->m_PPBuffer = new FrameBuffer(width, height); } void window_close_callback(GLFWwindow *window) { RenderModule* win = (RenderModule*)glfwGetWindowUserPointer(window); win->Close(); } void window_loss_focus_callback(GLFWwindow* window, int focused) { RenderModule* win = (RenderModule*)glfwGetWindowUserPointer(window); if (win->m_CursorFocused == true) { if (focused == false) win->m_CursorFocused = false; } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { RenderModule* win = (RenderModule*)glfwGetWindowUserPointer(window); win->m_Keys[key] = action != GLFW_RELEASE; } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { RenderModule* win = (RenderModule*)glfwGetWindowUserPointer(window); win->m_MouseButtons[button] = action != GLFW_RELEASE; } void cursor_position_callback(GLFWwindow* window, double xpos, double ypos) { RenderModule* win = (RenderModule*)glfwGetWindowUserPointer(window); win->mdx = win->mx - xpos; win->mdy = win->my - ypos; win->mx = xpos; win->my = ypos; } int RenderModule::PrepareRender() { m_ModelsToRender.clear(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); return 0; } int RenderModule::RenderWorld(std::vector<Terrain::Terrain*> m_Terrains) { // m_PPBuffer->Bind(); m_WorldShader->Start(); glm::mat4 view = glm::mat4(1.0f); view = glm::rotate(view, ToRadians(m_Camera->m_Rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); view = glm::rotate(view, ToRadians(m_Camera->m_Rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); view = glm::translate(view, m_Camera->m_Position); m_WorldShader->SetUniformMat4("view", view); m_WorldShader->SetUniformMat4("proj", glm::perspective(ToRadians(90.0f), ((float)(m_Width * 1.0f) / (float)(m_Height * 1.0f)), 0.1f, 1000.0f)); for (unsigned int i = 0; i < m_Models.size(); i++) { if (m_Models[i]->GetVAOID() == 3452816845) continue; m_Textures[i]->Bind(0); std::vector<glm::mat4> matrixes = m_ModelsToRender[m_Models[i]]; if (matrixes.size() != 0) for (unsigned int j = 0; j < matrixes.size(); j++) { m_WorldShader->SetUniformMat4("model", matrixes[j]); glBindVertexArray(m_Models[i]->GetVAOID()); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); // glDrawElements(GL_TRIANGLES, m_Models[i]->GetSize(), GL_UNSIGNED_INT, 0); glDrawArrays(GL_TRIANGLES, 0, m_Models[i]->GetSize()); } } for (unsigned int i = 0; i < m_Terrains.size(); i++) { Terrain::Terrain* t = m_Terrains[i]; if (t != nullptr) { float d = glm::distance(t->GetPosition(), m_Camera->m_Position); m_WorldShader->SetUniformMat4("model", glm::translate(glm::mat4(1.0), t->GetPosition())); glBindVertexArray(t->m_VAOID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); m_TerrainTexture->Bind(0); glDrawElements(GL_TRIANGLES, t->m_Size, GL_UNSIGNED_INT, 0); } } glBindVertexArray(0); m_WorldShader->Stop(); m_PPBuffer->UnBind(m_Width, m_Height); return 0; } int RenderModule::RenderPostProccessEffects() { m_PPShader->Start(); float aspect = (float)m_Width / (float)m_Height; m_PPShader->SetUniformMat4("proj", glm::ortho(-aspect, aspect, -1.0f, 1.0f, 1.0f, -1.0f)); glBindVertexArray(m_SquareModelID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glm::mat4 m = glm::mat4(1.0); glm::translate(m, glm::vec3(-aspect, 0, 0)); glm::scale(m, glm::vec3(1 + aspect, 2, 1)); m_PPShader->SetUniformMat4("model", m); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE0, m_PPBuffer->m_Texture); // glDrawArrays(GL_QUADS, 0, m_SquareModelSize); glBindVertexArray(0); m_PPShader->Stop(); return 0; } int RenderModule::RenderGUI() { m_GUIShader->Start(); float aspect = (float)m_Width / (float)m_Height; m_GUIShader->SetUniformMat4("proj", glm::ortho(-aspect, aspect, -1.0f, 1.0f, 1.0f, -1.0f)); glBindVertexArray(m_SquareModelID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); for (unsigned int i = 0; i < m_GUI->m_GUIItems.size(); i++) { glm::mat4 m = glm::mat4(1.0); glm::translate(m, m_GUI->m_GUIItems[i]->m_Position); glm::scale(m, m_GUI->m_GUIItems[i]->m_Size); m_WorldShader->SetUniformMat4("model", m); glDrawElements(GL_QUADS, m_SquareModelSize, GL_UNSIGNED_INT, 0); } glBindVertexArray(0); m_GUIShader->Stop(); return 0; } int RenderModule::EndRender() { for (int i = 0; i < MAX_KEYS; i++) m_KeyTyped[i] = m_Keys[i] && !m_KeyState[i]; for (int i = 0; i < MAX_BUTTONS; i++) m_MouseClicked[i] = m_MouseButtons[i] && !m_MouseState[i]; memcpy(m_KeyState, m_Keys, MAX_KEYS); memcpy(m_MouseState, m_MouseButtons, MAX_BUTTONS); if (m_CursorFocused) { glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } else { glfwSetInputMode(m_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } glfwPollEvents(); glfwSwapBuffers(m_Window); GLenum error = glGetError(); if (error != GL_NO_ERROR) { return -1; } return 0; } glm::vec2 RenderModule::GetMousePosition() const { return glm::vec2(mx, my); } glm::vec2 RenderModule::GetMouseDelta() const { return glm::vec2(mdx, mdy); } bool RenderModule::IsCursorFocused() const { return m_CursorFocused; } void RenderModule::SetCursor(bool r) { m_CursorFocused = r; } Camera* RenderModule::GetCamera() { return m_Camera; } GUI* RenderModule::GetGUI() { return m_GUI; } void RenderModule::SetGUI(GUI* gui) { m_GUI = gui; } int RenderModule::AddModelToRender(int id, glm::mat4 trans) { m_ModelsToRender[m_Models[id]].push_back(trans); return 0; } int RenderModule::AddModelToRender(int id, glm::vec3 position, glm::quat rotation, glm::vec3 scale) { glm::mat4 identity = glm::mat4(1.0); glm::mat4 translation = glm::translate(identity, position); glm::mat4 rot = glm::mat4_cast(rotation); glm::mat4 scal = glm::scale(identity, scale); return AddModelToRender(id, translation * rot * scal); } glm::vec2 RenderModule::GetWindowSize() { return glm::vec2(m_Width, m_Height); } }
#ifndef FOGCATCHSTATEMENT_HXX #define FOGCATCHSTATEMENT_HXX class FogCatchStatement : public FogStatement { typedef FogStatement Super; typedef FogCatchStatement This; TYPEDECL_SINGLE(This, Super) PRIMREF_DERIVED_DECLS(This) // FOGTOKEN_DERIVED_DECLS FOGTOKEN_MEMBER_DECLS FOGTOKEN_LEAF_DECLS private: FogExprRef _exception; FogRawRef _statement; private: This& mutate() const { return *(This *)this; } protected: FogCatchStatement(); FogCatchStatement(const This& aStatement); virtual ~FogCatchStatement(); public: FogCatchStatement(FogExpr& anExpr, FogRaw& aStatement); virtual size_t executable_tokens() const; virtual std::ostream& print_depth(std::ostream& s, int aDepth) const; virtual std::ostream& print_members(std::ostream& s, int aDepth) const; virtual void set_is_meta(); }; #endif
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // Copyright (c) 2018-2020, The Qwertycoin Group. // // This file is part of Qwertycoin. // // Qwertycoin 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 3 of the License, or // (at your option) any later version. // // Qwertycoin 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 Qwertycoin. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <algorithm> #include <numeric> #include <vector> namespace Common { template <class T> double meanValue(const std::vector<T>& v) { if (v.empty()) { return T(); } T sum = std::accumulate(v.begin(), v.end(), T()); return double(sum) / double(v.size()); } template <class T> double stddevValue(const std::vector<T>& v) { if (v.size() < 2) { return T(); } double mean = meanValue(v); std::vector<T> diff(v.size()); std::transform(v.begin(), v.end(), diff.begin(), [mean](T x) { return x - mean; }); T sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), T()); return std::sqrt(double(sq_sum) / double(v.size())); } template <class T> double medianValue(std::vector<T> &v) { if (v.empty()) { return T(); } if (v.size() == 1) { return v[0]; } auto n = (v.size()) / 2; std::sort(v.begin(), v.end()); if (v.size() % 2) { // 1, 3, 5... return v[n]; } else { // 2, 4, 6... return double(v[n - 1] + v[n]) / 2.0; } } } // namespace Common
// // 46_Permutations.hpp // algorithms // // Created by Maple Yin on 2020/4/24. // Copyright © 2020 Maple Yin. All rights reserved. // #ifndef _6_Permutations_hpp #define _6_Permutations_hpp #include <stdio.h> #include <vector> using namespace std; class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> resultVector(0); auto size = nums.size(); if (size == 0) { return resultVector; } resultVector.push_back(vector<int>(1,nums[0])); for (unsigned long i = 1; i < size; ++i) { resultVector = addElement(nums[i], resultVector); } return resultVector; } vector<vector<int>> addElement(int num, vector<vector<int>>&nums) { auto size = nums.size(); for (unsigned long i = 0; i < size; ++i) { vector<int> each = nums[i]; auto eachSize = each.size(); for (unsigned long eachIndex = 0; eachIndex < eachSize; ++eachIndex) { vector<int> copyEach(each); copyEach.insert(copyEach.begin() + eachIndex, num); nums.push_back(copyEach); } nums[i].insert(nums[i].end(), num); } return nums; } }; #endif /* _6_Permutations_hpp */ ;
/************************************************************* * > File Name : c1090_0.cpp * > Author : Tony_Wong * > Created Time : 2019/11/13 11:34:07 * > Algorithm : **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; inline int read() { int x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - 48; ch = getchar(); } return x * f; } const int maxn = 110; int n; int main() { // freopen("triangle.in", "r", stdin); // freopen("triangle.out", "w", stdout); n = read(); if (n < 6) { printf("0\n"); return 0; } if (n == 6) { printf("1\n"); } else if (n == 7) { printf("7\n"); } else if (n == 8) { printf("28\n"); } else { long long m = (long long)n; printf("%lld\n", m * (m - 1) * (m - 2) * (m - 3) * (m - 4) * (m - 5) / 720); } return 0; }
#ifndef __SNESAPU_FILTER_H__ #define __SNESAPU_FILTER_H__ namespace SnesApu { class Filter { public: Filter(int taps); ~Filter(); void SetCoefficient(int index, unsigned char value); int Next(int value); private: int taps; unsigned char *coefficients; int *buffer; int bufferPos; }; } #endif
#include "ScoreScreen.h" #include "Entity.h" #include "Counter.h" #include "EntityGenerators.h" #include "Rendering.h" int ScoreScreen::highScore = 0; ScoreScreen::ScoreScreen() {} ScoreScreen::~ScoreScreen() { delete _gameScore; delete _highScore; delete _scoreboard; delete _medal; } void ScoreScreen::setScore(int score) { double scale = 4.0; int sbX = 100; int sbY = 100; int medalX = sbX + (13*scale); int medalY = sbY + (50 * scale); double scoreScale = 1.8; int scoreX = sbX + (90 * scale); int scoreY = sbY + (45 * scale); int hscoreY = sbY + (65 * scale); _scoreboard = EntityGenerator::getInstance().createScoreboard(sbX, sbY, scale); // init Counters _gameScore = new Counter(scoreX, scoreY, scoreScale, score); _highScore = new Counter(scoreX, hscoreY, scoreScale, highScore); // set medal if (score <= 1) _medal = nullptr; else if (score < 5) _medal = EntityGenerator::getInstance().createMedalBronze(medalX, medalY, scale); else if (score < 10) _medal = EntityGenerator::getInstance().createMedalSilver(medalX, medalY, scale); else if (score < 20) _medal = EntityGenerator::getInstance().createMedalGold(medalX, medalY, scale); else _medal = EntityGenerator::getInstance().createMedalPlatinum(medalX, medalY, scale); // check for new high score if (score > highScore) highScore = score; } void ScoreScreen::render(Renderer* renderer) { if (_scoreboard != nullptr) { _scoreboard->render(renderer); _gameScore->render(renderer); if (_highScore != nullptr) _highScore->render(renderer); if (_medal != nullptr) _medal->render(renderer); } }
#ifndef ANSWERWINDOW_H #define ANSWERWINDOW_H #include <QMainWindow> class AnswerWindow : public QMainWindow { Q_OBJECT public: AnswerWindow(QWidget *parent = 0); ~AnswerWindow(); void showAnswer(); void solve(); void setGrid(int v); void setThread(int v); private: int grid=51; int thread=1; //int timeElapsed=0; }; #endif // ANSWERWINDOW_H
#include <iostream> using namespace std; class parentMember { public: parentMember() { cout << "Construct parent member class" << endl; } ~parentMember() { cout << "Destruct parent member class" << endl; } }; class childMember { public: childMember() { cout << "Construct child member class" << endl; } ~childMember() { cout << "Destruct child member class" << endl; } }; class father { parentMember parentMember; public: father() { cout << "Construct father class" << endl; } ~father() { cout << "Destruct father class" << endl; } }; class mother { parentMember parentMember; public: mother() { cout << "Construct mother class" << endl; } ~mother() { cout << "Destruct mother class" << endl; } }; class child : public father, public mother { childMember childMember; public: child() { cout << "Construct child class" << endl; } ~child() { cout << "Destruct child class" << endl; } }; int main() { child c; cout << "-----------" << endl; return 0; }
#include <cstdio> //#include <ctime> int main() { //freopen("..\\file\\input.txt","r",stdin); //freopen("..\\file\\output.txt","w",stdout); /*clock_t s,e; s=clock();*/ int a,b; while(scanf("%d%d",&a,&b)==2) printf("%d\n",a+b); /*e=clock(); printf("Use %.0lf ms\n", (((double)(e-s))/CLOCKS_PER_SEC)*1000);*/ return 0; }
#include<stdio.h> #include<stdlib.h> #define size 10 int arr[size]; void binarySearch(int arr[],int ele,int startIndex,int endIndex) { while(startIndex<=endIndex) { int mid=(startIndex+endIndex)/2; if(arr[mid]==ele) { printf("\n index is %d ",mid); return; } if(arr[mid]>ele) endIndex=mid-1; else startIndex=mid+1; } printf("\n unsuccessful search ,element not found"); } int main() { int i,ele; printf("\nenter elements in sorted order"); for(i=0;i<=size-1;i++) { scanf("\n%d",&arr[i]); } printf("\nenter element to search"); scanf("\n%d",&ele); binarySearch(arr,ele,0,size-1); }
#pragma once #include <sc2api/sc2_api.h> #include <sc2utils/sc2_manage_process.h> #include <SC2.h> #include <EventListener.h> #include <utils/GridUtils.h> #include <algorithm> #include <iostream> #include <fstream> #include <set> namespace sc2::utils { class Map; } class Kubot : public sc2::Agent { public: ~Kubot() override; Kubot(); void OnGameStart() final override; void OnStep() override; void OnUnitCreated(const sc2::Unit* unit) override; void OnBuildingConstructionComplete(const sc2::Unit* unit) override; void OnUnitDestroyed(const sc2::Unit*) override; void OnUnitIdle(const sc2::Unit*) override; std::vector<std::unique_ptr<EventListener>> m_listeners; SC2 m_sc2; std::unique_ptr<sc2::utils::Map> m_map; };
#include<iostream> using namespace std; int main() { int iNum,iDen,iAns; cout<<"enter the Number and Denonter\t"; cin>>iNum>>iDen; try { if(0==iDen) throw iDen; else iAns=iNum/iDen; } catch(int exception ) { cout<<"exception found\t"<<exception<<endl; return 0; } cout<<"exception not found\t"<<endl; cout<<"Ans\t"<<iAns; return 0; }
#ifndef _SPLASHSCREEN_H_ #define _SPLASHSCREEN_H_ #include "cocos2d.h" #include <vector> class SplashScreen :public cocos2d::Layer { public: static cocos2d::Scene *createScene(); virtual bool init(); bool setupSprites(); void swapPosition(cocos2d::Sprite* spr1, cocos2d::Sprite* spr2); void startMove(float dt); void moveKeSpriteToLeft(); void moveMaiSpriteToLeft(); void spriteFadeOut(); void gotoMenuScene(); CREATE_FUNC(SplashScreen); private: cocos2d::Sprite *pSprCheng; cocos2d::Sprite *pSprKe; cocos2d::Sprite *pSprJi; cocos2d::Sprite *pSprMai; cocos2d::Size spriteSize; }; #endif
#include <windows.h> #include <gl/glut.h> void DoDisplay(); void DoMenu(int value); int Action; int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance ,LPSTR lpszCmdParam,int nCmdShow) { glutCreateWindow("OpenGL"); glutDisplayFunc(DoDisplay); glutCreateMenu(DoMenu); glutAddMenuEntry("변환 없음",0); glutAddMenuEntry("이동",1); glutAddMenuEntry("엉뚱한 위치에 나타나는 이동",2); glutAddMenuEntry("단위 행렬로 리셋",3); glutAddMenuEntry("스택에 저장 및 복구",4); glutAddMenuEntry("확대",5); glutAddMenuEntry("뒤집기",6); glutAddMenuEntry("x축 기준 회전",7); glutAddMenuEntry("y축 기준 회전",8); glutAddMenuEntry("z축 기준 회전",9); glutAddMenuEntry("확대 후 이동",10); glutAddMenuEntry("이동 후 확대",11); glutAddMenuEntry("원점 기준 회전",12); glutAddMenuEntry("제자리 회전",13); glutAttachMenu(GLUT_RIGHT_BUTTON); glutMainLoop(); return 0; } void DoMenu(int value) { if (value < 100) { Action = value; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,1,1); glutPostRedisplay(); return; } } void DoDisplay() { switch(Action) { case 0: // 변환 없음 glClear(GL_COLOR_BUFFER_BIT); glutWireTeapot(0.2); glFlush(); break; case 1: // 이동 glClear(GL_COLOR_BUFFER_BIT); glutWireTeapot(0.2); glTranslatef(0.6, 0.0, 0.0); glutWireTeapot(0.2); glFlush(); break; case 2: // 엉뚱한 위치에 나타나는 이동 glClear(GL_COLOR_BUFFER_BIT); glutWireTeapot(0.2); glTranslatef(0.6, 0.0, 0.0); glutWireTeapot(0.2); glTranslatef(0.0, 0.6, 0.0); glutWireTeapot(0.2); glFlush(); break; case 3: // 단위 행렬로 리셋 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glutWireTeapot(0.2); glTranslatef(0.6, 0.0, 0.0); glutWireTeapot(0.2); glLoadIdentity(); glTranslatef(0.0, 0.6, 0.0); glutWireTeapot(0.2); glFlush(); break; case 4: // 스택에 저장 및 복구 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glutWireTeapot(0.2); glPushMatrix(); glTranslatef(0.6, 0.0, 0.0); glutWireTeapot(0.2); glPopMatrix(); glTranslatef(0.0, 0.6, 0.0); glutWireTeapot(0.2); glPopMatrix(); glFlush(); break; case 5: // 확대 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glScalef(2.0, 3.0, 1.0); glutWireTeapot(0.2); glPopMatrix(); glFlush(); break; case 6: // 뒤집기 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glScalef(-2.0, 3.0, 1.0); glutWireTeapot(0.2); glPopMatrix(); glFlush(); break; case 7: // x축 기준 회전 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glRotatef(45.0, 1.0, 0.0, 0.0); glutWireTeapot(0.4); glPopMatrix(); glFlush(); break; case 8: // y축 기준 회전 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glRotatef(45.0, 0.0, 1.0, 0.0); glutWireTeapot(0.4); glPopMatrix(); glFlush(); break; case 9: // z축 기준 회전 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glRotatef(45.0, 0.0, 0.0, 1.0); glutWireTeapot(0.4); glPopMatrix(); glFlush(); break; case 10: // 확대 후 이동 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslatef(0.5, 0.5, 0.0); glScalef(1.5, 1.5, 1.0); glutWireTeapot(0.2); glPopMatrix(); glFlush(); break; case 11: // 이동 후 확대 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glScalef(1.5, 1.5, 1.0); glTranslatef(0.5, 0.5, 0.0); glutWireTeapot(0.2); glPopMatrix(); glFlush(); break; case 12: // 원점 기준 회전 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glBegin(GL_TRIANGLES); glVertex2f(0.5, 0.8); glVertex2f(0.2, 0.2); glVertex2f(0.8, 0.2); glEnd(); glRotatef(45.0, 0.0, 0.0, 1.0); glColor3f(1,1,0); glBegin(GL_TRIANGLES); glVertex2f(0.5, 0.8); glVertex2f(0.2, 0.2); glVertex2f(0.8, 0.2); glEnd(); glPopMatrix(); glFlush(); break; case 13: // 제자리 회전 glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glBegin(GL_TRIANGLES); glVertex2f(0.5, 0.8); glVertex2f(0.2, 0.2); glVertex2f(0.8, 0.2); glEnd(); glTranslatef(0.5, 0.5, 0.0); glRotatef(45.0, 0.0, 0.0, 1.0); glTranslatef(-0.5, -0.5, 0.0); glColor3f(1,1,0); glBegin(GL_TRIANGLES); glVertex2f(0.5, 0.8); glVertex2f(0.2, 0.2); glVertex2f(0.8, 0.2); glEnd(); glPopMatrix(); glFlush(); break; } }
#include <bits/stdc++.h> using namespace std; class Solution { public: int solve(int n) { int count = 0; for (int i = 5; n / i >= 1; i *= 5) count++; return count; } }; int main() { Solution solve; cout << solve.solve(18); return 0; }
#include <ESP8266WiFi.h> #include <Wire.h> #include <WiFiUdp.h> /* I2C MPU6050*/ const int8_t R_CONFIG = 0x1A; const int8_t R_GYRO_CONFIG = 0x1B; const int8_t R_ACCEL_CONFIG = 0x1C; const int MPU_ADDR = 0x68; int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; /* WiFi */ const char* ssid = "Sergio_LINK"; const char* password = "4F48C9n?t-"; /* WiFi Reconnection */ const int wifiCheckTimeout = 10000; int lastCheckTime = 0; /* UDP */ const unsigned int udpPort = 27020; WiFiUDP Udp; const IPAddress udpServer(192, 168, 0, 255); // udp server address void mpuWrite(int8_t addr, int8_t data){ Wire.beginTransmission(MPU_ADDR); Wire.write(addr); Wire.write(data); Wire.endTransmission(true); } void mpuInitConfig(){ mpuWrite(R_CONFIG, 0b00000011); //write to filter DLP_CFG value 3 Serial.print(" >> Configured filter.\n"); mpuWrite(R_GYRO_CONFIG, 0b10000000); // run gyroX self test mpuWrite(R_GYRO_CONFIG, 0b01000000); // run gyroY self test mpuWrite(R_GYRO_CONFIG, 0b00100000); // run gyroZ self test mpuWrite(R_GYRO_CONFIG, 0b00011000); // set gyro scale range to +/- 2000 C/s Serial.print(" >> Configured gyroscope.\n"); mpuWrite(R_ACCEL_CONFIG, 0b10000000); // run accelX self test mpuWrite(R_ACCEL_CONFIG, 0b01000000); // run accelY self test mpuWrite(R_ACCEL_CONFIG, 0b00100000); // run accelZ self test mpuWrite(R_ACCEL_CONFIG, 0b00011000); // set accel scale to +/- 16g //mpuWrite(R_ACCEL_CONFIG, 0b00011000); // set accel DHPF(Difital High Pass Filter) Serial.print(" >> Configured accelerometer.\n"); } void espConnectWifi(){ WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while(WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi Connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void uartDebugPrint(){ Serial.print("AcX = "); Serial.print(AcX); Serial.print(" | AcY = "); Serial.print(AcY); Serial.print(" | AcZ = "); Serial.print(AcZ); Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet Serial.print(" | GyX = "); Serial.print(GyX); Serial.print(" | GyY = "); Serial.print(GyY); Serial.print(" | GyZ = "); Serial.println(GyZ); } void buildAndSendStringPacket(){ String packet = ""; packet += String(AcX) + " "; packet += String(AcY) + " "; packet += String(AcZ) + " "; packet += String(GyX) + " "; packet += String(GyY) + " "; packet += String(GyZ) + " "; packet += String(Tmp / 340.00 + 36.53); byte packetBuffer[packet.length()+1]; packet.getBytes(packetBuffer, packet.length()+1); udpWritePacket(packetBuffer, packet.length()+1); } void buildAndSendBytePacket(){ // packet size 14 bytes with temp two bytes // +2 bytes for packet end marker(packet delimiter) const size_t packetSize = 16; byte packet[packetSize] = {0}; packet[0] = (AcX & 0x00FF); packet[1] = ((AcX & 0xFF00) >> 8); packet[2] = (AcY & 0x00FF); packet[3] = ((AcY & 0xFF00) >> 8); packet[4] = (AcZ & 0x00FF); packet[5] = ((AcZ & 0xFF00) >> 8); packet[6] = (GyX & 0x00FF); packet[7] = ((GyX & 0xFF00) >> 8); packet[8] = (GyY & 0x00FF); packet[9] = ((GyY & 0xFF00) >> 8); packet[10] = (GyZ & 0x00FF); packet[11] = ((GyZ & 0xFF00) >> 8); // Calculate temp by formula Tmp / 340.00 + 36.53 on receive side packet[12] = (Tmp & 0x00FF); packet[13] = ((Tmp & 0xFF00) >> 8); // Two byte packet end marker, chosed values equal to 132 celsium temperature // which is unreal for temp in normal environment packet[14] = 0x7F; packet[15] = 0xFF; Serial.write(packet, packetSize); // Debug udpWritePacket(packet, packetSize); } void udpWritePacket(byte *packetBuffer, unsigned int packetSize){ Udp.beginPacket(udpServer, udpPort); Udp.write(packetBuffer, packetSize); Udp.endPacket(); } void mpuReadData(){ Wire.beginTransmission(MPU_ADDR); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(MPU_ADDR, 14, true); // request a total of 14 registers AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L) GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L) GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L) GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L) } void setup() { // put your setup code here, to run once: Wire.begin(); Wire.beginTransmission(MPU_ADDR); Wire.write(0x6B); Wire.write(0); Wire.endTransmission(true); Serial.begin(115200); Serial.println(""); mpuInitConfig(); Serial.println("Connecting..."); espConnectWifi(); delay(2000); } void loop() { if(millis() - lastCheckTime > wifiCheckTimeout){ if(WiFi.status() != WL_CONNECTED){ Serial.println("Reconnecting..."); espConnectWifi(); } lastCheckTime = millis(); } mpuReadData(); //buildAndSendStringPacket(); buildAndSendBytePacket(); //uartDebugPrint(); delay(5); }
#include "ResMagicChain.h" void ResMagicChain::setData(char *buf, int offset) { mType = (int)buf[offset] & 0xff; mIndex = (int)buf[offset + 1] & 0xff; mNum = (int)buf[offset + 2] & 0xff; int index = offset + 3; mMagics.resize(mNum); for (int i = 0; i < mNum; i++) { int magicType = (int)buf[index++]; int magicIndex = (int)buf[index++]; mMagics[i] = (BaseMagic *)DatLib::GetRes(DatLib::RES_MRS, magicType, magicIndex); } } ResMagicChain::ResMagicChain() { mLearnNum = 0; } ResMagicChain::~ResMagicChain() { for (int i = 0; i < (int)(mMagics.size()); i++) { delete mMagics[i]; } mMagics.clear(); } int ResMagicChain::getLearnNum() { return mLearnNum; } void ResMagicChain::setLearnNum(int num) { mLearnNum = num; } void ResMagicChain::learnNextMagic() { ++mLearnNum; } int ResMagicChain::getMagicSum() { return mNum; } BaseMagic * ResMagicChain::getMagic(int index) // TODO fix NULL { return mMagics[index]; }
/* * SPDX-FileCopyrightText: (C) 2018 Daniel Nicoletti <dantti12@gmail.com> * SPDX-License-Identifier: BSD-3-Clause */ #ifndef HPACKTABLES_H #define HPACKTABLES_H #include <QHash> #include <QString> #include <QVector> namespace Cutelyst { struct DynamicTableEntry { QString key; QString value; }; class Headers; class CWsgiEngine; class H2Stream; class HPack { public: HPack(int maxTableSize); ~HPack(); void encodeHeaders(int status, const QMultiHash<QString, QString> &headers, QByteArray &buf, CWsgiEngine *engine); int decode(unsigned char *it, unsigned char *itEnd, H2Stream *stream); private: QVector<DynamicTableEntry> m_dynamicTable; int m_dynamicTableSize = 0; int m_currentMaxDynamicTableSize = 0; int m_maxTableSize; }; } // namespace Cutelyst #endif // HPACKTABLES_H
#include<bits/stdc++.h> #define ll long long #define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) using namespace std; #define N 100000 #define mod 1000000007 template <typename T> void print(T x){cout<<x<<"\n";} template <typename T1, typename T2> void print2(T1 x,T2 y){cout<<x<<" "<<y<<"\n";} template <typename T1, typename T2,typename T3> void print3(T1 x, T2 y,T3 z){cout<<x<<" "<<y<<" "<<z<<"\n";} void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } vector<int> threeWayPartition(vector<int> arr) { int start=0,end=arr.size()-1; for(int i=0;i<=end;) { if(arr[i]<1) swap(&arr[i++],&arr[start++]); else if(arr[i]>1) swap(&arr[i],&arr[end--]); else i++; } return arr; } int main() { io; ll test_case; cin>>test_case; //test_case=1; while(test_case--) { int n; cin>>n; vector<int> A(n); for(int i=0;i<n;i++) cin>>A[i]; vector<int> res=threeWayPartition(A); for(int i=0;i<res.size();i++) cout<<res[i]<<" "; cout<<"\n"; } }
#include "../memPool_t.h" #include <assert.h> #include <string.h> int main() { memPool_t::setNewPageSize(1024); memPool_t *pool = new memPool_t(5); assert(pool->getPageCount() == 5); assert(pool->getCapacity() == 5 * 1024); assert(pool->getSize() == 0); assert(pool->isEmpty()); assert(pool->getPosition() == 0); int arr1[10000] = {0}; for (int i = 0; i < 10000; ++i) { arr1[i] = 10000 - i; } assert(pool->write(arr1, sizeof(arr1)) == sizeof(arr1)); assert(pool->getPosition() == sizeof(arr1)); assert(pool->getSize() == pool->getPosition()); int arr2[10000] = {0}; assert(pool->setPosition(0) == 0); assert(pool->getSize() == sizeof(arr1)); assert(pool->read(arr2, 100000) == sizeof(arr1)); for (int i = 0; i < 10000; ++i) { if (arr2[i] != 10000 - i) assert(1 == 0); } delete pool; memPool_t::setNewPageSize(4); pool = new memPool_t(); for (int i = 0; i < 111; ++i) { assert(pool->write(&i, sizeof(i)) == sizeof(i)); } assert(pool->getPageCount() == 111); delete pool; }
#include "Bullet.h" #include "Tank.h" #include "Buff.h" int Bullet::run() { for (int i = 0; i < speed; i++) { draw(false); if (map.map[y][x / 2] && map.map[y][x / 2]->getType() == type) map.map[y][x / 2] = nullptr; if (x <= 2 || x >= WIDTH - 4 || y <= 1 || y >= HEIGHT - 2) return -1; if (coll || collision()) { return -1; } switch (direct) { case UP: y -= 1; break; case DOWN: y += 1; break; case LEFT: x -= 2; break; case RIGHT: x += 2; break; default: break; } map.map[y][x / 2] = this; } return 0; } void Bullet::draw(bool filling) { if (filling) drawAtPoint(x, y, "¡ñ", GOLD); else drawAtPoint(x, y, " ", ""); } bool Bullet::collision() { Element* p; TYPE opptype; BUFFTYPE buff; switch (direct) { case UP: if (map.map[y - 1][x / 2]) { p = map.map[y - 1][x / 2]; opptype = p->getType(); if (opptype == WALL || power >= 2 && opptype == IRONWALL) { p->draw(false); map.map[y - 1][x / 2] = nullptr; } else if (opptype == BASE) { if (belong->getCamp() == ENEMY) { active = false; } } else if (opptype == TANK) { if (belong->getCamp() != ((Tank*)p)->getCamp()) { ((Tank*)p)->reduceLife(power); } } else if (opptype == BULLET) { ((Bullet*)p)->coll = true; } else if (opptype == BUFF) { buff = ((Buff*)p)->getBuff(); switch (buff) { case LIFEBUFF: belong->addLife(false, 1); break; case SPEEDBUFF: belong->addSpeed(1); break; case POWERBUFF: belong->powerUp(); break; case VOLUMEBUFF: belong->volumeUP(); break; default: break; } map.map[y - 1][x / 2] = nullptr; p->draw(false); } return true; } break; case DOWN: if (map.map[y + 1][x / 2]) { p = map.map[y + 1][x / 2]; opptype = p->getType(); if (opptype == WALL || power >= 2 && opptype == IRONWALL) { p->draw(false); map.map[y + 1][x / 2] = nullptr; } else if (opptype == BASE) { if (belong->getCamp() == ENEMY) { active = false; } } else if (opptype == TANK) { if (belong->getCamp() != ((Tank*)p)->getCamp()) { ((Tank*)p)->reduceLife(power); } } else if (opptype == BULLET) { ((Bullet*)p)->coll = true; } else if (opptype == BUFF) { buff = ((Buff*)p)->getBuff(); switch (buff) { case LIFEBUFF: belong->addLife(false, 1); break; case SPEEDBUFF: belong->addSpeed(1); break; case POWERBUFF: belong->powerUp(); break; case VOLUMEBUFF: belong->volumeUP(); break; default: break; } map.map[y + 1][x / 2] = nullptr; p->draw(false); } return true; } break; case LEFT: if (map.map[y][x / 2 - 1]) { p = map.map[y][x / 2 - 1]; opptype = p->getType(); if (opptype == WALL || power >= 2 && opptype == IRONWALL) { p->draw(false); map.map[y][x / 2 - 1] = nullptr; } else if (opptype == BASE) { if (belong->getCamp() == ENEMY) { active = false; } } else if (opptype == TANK) { if (belong->getCamp() != ((Tank*)p)->getCamp()) { ((Tank*)p)->reduceLife(power); } } else if (opptype == BULLET) { ((Bullet*)p)->coll = true; } else if (opptype == BUFF) { buff = ((Buff*)p)->getBuff(); switch (buff) { case LIFEBUFF: belong->addLife(false, 1); break; case SPEEDBUFF: belong->addSpeed(1); break; case POWERBUFF: belong->powerUp(); break; case VOLUMEBUFF: belong->volumeUP(); break; default: break; } map.map[y][x / 2 - 1] = nullptr; p->draw(false); } return true; } break; case RIGHT: if (map.map[y][x / 2 + 1]) { p = map.map[y][x / 2 + 1]; opptype = p->getType(); if (opptype == WALL || power >= 2 && opptype == IRONWALL) { p->draw(false); map.map[y][x / 2 + 1] = nullptr; } else if (opptype == BASE) { if (belong->getCamp() == ENEMY) { active = false; } } else if (opptype == TANK) { if (belong->getCamp() != ((Tank*)p)->getCamp()) { ((Tank*)p)->reduceLife(power); } } else if (opptype == BULLET) { ((Bullet*)p)->coll = true; } else if (opptype == BUFF) { buff = ((Buff*)p)->getBuff(); switch (buff) { case LIFEBUFF: belong->addLife(false, 1); break; case SPEEDBUFF: belong->addSpeed(1); break; case POWERBUFF: belong->powerUp(); break; case VOLUMEBUFF: belong->volumeUP(); break; default: break; } map.map[y][x / 2 + 1] = nullptr; p->draw(false); } return true; } break; default: break; } return false; }
#include <iostream> #include <fstream> const char * file1 = "input1.txt"; const char * file2 = "input2.txt"; const char * file3 = "output1.txt"; int main() { using namespace std; ifstream fin1(file1, ios_base::in); ifstream fin2(file2, ios_base::in); ofstream fout1(file3, ios_base::out); if (!fin1.is_open() || !fin2.is_open()) { cerr << "wrong input file!\n"; exit(EXIT_FAILURE); } char ch; if (!fout1.is_open()) { cerr << "Can't open this for output:\n"; exit(EXIT_FAILURE); } else { while (!fin1.eof() || !fin2.eof()) { if(!fin1.eof()) { while (fin1.get(ch) && ch != '\n') fout1 << ch; fout1 << ' '; } if(!fin2.eof()) { while (fin2.get(ch) && ch != '\n') fout1 << ch; } fout1 << '\n'; } } fin1.close(); fin2.close(); fout1.close(); return 0; }
#ifndef SSPEDITOR_AIHANDLER_AIHANDLER_H #define SSPEDITOR_AIHANDLER_AIHANDLER_H #include "Header.h" #include "../AIDLL/AIComponent.h" #include <vector> /* Author: Martin Clementson This Class holds the AI components that is in use by the current level. The components are related to a container/entity and share the same ID. To remove use the ID. When a new level is created. This class is cleared of its data. */ class AiHandler { private: std::vector<AiContainer*>m_Components; public: AiHandler(); virtual ~AiHandler(); //Path Component Functions AiContainer* NewPathComponent(); AiContainer* GetPathComponent(int EntityID); std::vector<AiContainer*>* GetAllPathComponents(); void DeletePathComponent(int EntityID); void UpdatePathComponent(int entityID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation); ///////////////////////////////////////////// void Destroy(); //Used when a new level is loaded. }; #endif
#pragma once #include <string> #include <unordered_map> #include "paraphrase.h" #include "errorID.h" PP_API extern Context *GlobalContext; PP_API extern std::unordered_map<std::string,const Word*> Dict; extern unsigned int G_NumOfCores; PP_API bool Docol(Context& inContext) NOEXCEPT;
#include <iostream> #include <vector> #include <algorithm> using namespace std; int bubbleSort(vector<int> &a); int printVector(vector<int> a); int linear_search(vector<int> a, int); int main() { int input,n,num; vector<int> a; cout<<"Enter the number of inputs: "; cin>>n; cout << "Enter your numbers to be evaluated: " << endl; for(int i=0;i<n;i++){ cin >> input; a.push_back(input); } cout<<"Before sorting: \n "; printVector(a); bubbleSort(a); cout<<"After sorting: \n "; printVector(a); cout<<"\nEnter the value to be searched:\n "; cin>>num; linear_search(a,num); return 0; } int bubbleSort(vector<int>& a) { bool swapp = true; while(swapp){ swapp = false; for (size_t i = 0; i < a.size()-1; i++) { if (a[i]>a[i+1] ){ a[i] += a[i+1]; a[i+1] = a[i] - a[i+1]; a[i] -=a[i+1]; swapp = true; } } } } int printVector(vector<int> a){ for (size_t i=0; i <a.size(); i++) { cout<<a[i]<<" "; } cout<<endl; } int linear_search(vector<int> v, int a){ for (int i = 0; i < v.size(); i++){ if (v[i] == a) cout<<a<<" found at position "<<i; return i; } cout<<"\nValue not found..!!\n"; return -1; }
#ifndef PETSC_FD_UTILS_H #define PETSC_FD_UTILS_H #include <fd/Operator.h> #include <vector> #include <utility> #include <tuple> #include <optional> #include <variant> #include <memory> #include <fstream> #include <cfenv> namespace fd { /* NOTE: DO NOT CALL VecCreate() on out! This routine does that! You DO, however, need to call VecDestroy() when you're done with it.*/ PetscErrorCode ScatterVecToZero(Vec in, Vec *out) { PetscErrorCode ierr; VecScatter ctx; PetscFunctionBeginUser; ierr = VecScatterCreateToZero(in,&ctx,out);CHKERRQ(ierr); ierr = VecScatterBegin(ctx,in,*out,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr); ierr = VecScatterEnd(ctx,in,*out,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr); ierr = VecScatterDestroy(&ctx);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode VecToGNUPlot(RectangularOperator *gridop, Vec X, std::string filename) { PetscMPIInt rank,size; Vec rootvals; const PetscScalar *x; FILE *file; PetscErrorCode ierr; PetscFunctionBeginUser; MPI_Comm_rank(gridop->Comm(),&rank); MPI_Comm_size(gridop->Comm(),&size); if (!rank) { if (!filename.ends_with(".plt")) { auto pos = filename.find_last_of("."); if (pos != std::string::npos) { std::string newfname = filename.substr(0,pos); filename = newfname; } filename += std::string{".plt"}; } } MPI_Barrier(gridop->Comm()); ierr = ScatterVecToZero(X,&rootvals);CHKERRQ(ierr); if (!rank) { PetscFOpen(gridop->Comm(),filename.c_str(),"w",&file); auto [nx,ny] = gridop->GridSize(); ierr = VecGetArrayRead(rootvals,&x);CHKERRQ(ierr); for (PetscInt i=1; i<nx; ++i) { for (PetscInt j=1; j<nx; ++j) { auto [xp,yp] = gridop->CoordinateMap(i,j); auto p = gridop->GridToVectorMap(i,j); PetscFPrintf(gridop->Comm(),file,"%g %g %g\n",xp,yp,x[p]); } PetscFPrintf(gridop->Comm(),file,"\n"); } ierr = VecRestoreArrayRead(rootvals,&x);CHKERRQ(ierr); ierr = PetscFClose(gridop->Comm(),file);CHKERRQ(ierr); } ierr = VecDestroy(&rootvals);CHKERRQ(ierr); PetscFunctionReturn(0); } /* each result is a tuple of (RMS error, L2 error, Max Pointwise Error) */ using TestResultPointer = std::unique_ptr<std::vector<std::tuple<PetscReal,PetscReal,PetscReal>>>; /* the second parameter should manufacture the solution you want from coordinates, third parameter is tuples of (atol,rtol,maxiter) */ template<class Operator_t> std::variant<TestResultPointer,PetscErrorCode> TestConvergence(MPI_Comm comm, const std::vector<std::tuple<PetscInt,PetscInt,PetscReal>>& grid_sizes_and_length, PetscScalar(*func)(PetscScalar,PetscScalar), std::optional<std::vector<std::tuple<PetscReal,PetscReal,PetscInt>>> ksp_tolerances = std::nullopt, std::optional<PetscScalar> scale=std::nullopt, bool set_from_options=false, std::optional<std::vector<std::string>> solution_plot_filenames=std::nullopt) { PetscErrorCode ierr; PetscReal l2,rms,maxerr; PetscFunctionBeginUser; if (!func) { SETERRQ(comm,PETSC_ERR_ARG_NULL,"Error, must pass a valid function pointer to fd::TestConvergence<>()!"); } std::size_t ntest = grid_sizes_and_length.size(); auto results = std::make_unique<std::vector<std::tuple<PetscReal,PetscReal,PetscReal>>>(ntest); if (ksp_tolerances) { if (ksp_tolerances->size() < ntest) { PetscPrintf(comm,"WARNING: there are %D tests to run, and you supplied KSP tolerance parameters for %D of them!\n",ntest,ksp_tolerances->size()); } } MPI_Barrier(comm); std::size_t i=0; for (const auto& [nx,ny,gridlen] : grid_sizes_and_length) { MPI_Barrier(comm); Operator_t A(comm,nx,ny,gridlen); if (set_from_options) { ierr = A.SetFromOptions();CHKERRQ(ierr); } if (scale) { ierr = A.SetScale(*scale);CHKERRQ(ierr); } if (ksp_tolerances) { if (i < ksp_tolerances->size()) { const auto& [rtol,atol,maxiter] = ksp_tolerances->at(i); ierr = A.SetKSPTolerances(rtol,atol,maxiter);CHKERRQ(ierr); } } A.SetDirichletBCFunction(func); ierr = A.SetRHSForManufacturedSolution(func);CHKERRQ(ierr); MPI_Barrier(comm); ierr = A.Assemble();CHKERRQ(ierr); ierr = A.SteadyStateSolve();CHKERRQ(ierr); MPI_Barrier(comm); if (solution_plot_filenames) { if (i < solution_plot_filenames->size()) { auto plotfile = solution_plot_filenames->at(i); ierr = VecToGNUPlot(std::addressof(A),A.GetSteadyStateSolution(),plotfile);CHKERRQ(ierr); } } try { auto err = A.ManufacturedSolutionError().value();CHKERRQ(ierr); rms = err.PointwiseRMS; l2 = err.L2; maxerr = err.PointwiseMax; } catch(std::bad_optional_access& exc) { PetscPrintf(comm,"Error: %s",exc.what()); } MPI_Barrier(comm); if (!A.Converged()) { PetscPrintf(comm,"On test number %D, KSP for Operator %s failed to converge with reason %s\n",i+1,A.Name().c_str(),A.ConvergedReason()); } else { PetscPrintf(comm,"After %D iterations solving %s(X) = f with MMS on a %D-by-%D grid, error statistics are:\nPointwise RMS Error : %g\nL2 Error: %g\nMaximum Pointwise Error : %g\n", A.NumIter(),A.Name().c_str(),nx,ny,rms,l2,maxerr); } MPI_Barrier(comm); results->at(i) = std::make_tuple(rms,l2,maxerr); i++; } return results; } }//namespace fd #endif
/* Fichero calculadora2.cc que almacena el módulo principal del programa */ #include <iostream> #include "../calculos1/calculos.h" #include "calculosGen.h" using namespace std; /* * Pre: --- * Post: Presenta el menu de opciones disponibles */ void presentarMenu () { cout << "\nMENU DE OPERACIONES\n===================" << endl; cout << "0 - Finalizar" << endl; cout << "1 - Calcular el numero de cifras de un entero" << endl; cout << "2 - Sumar las cifras de un entero" << endl; cout << "3 - Extraer una cifra de un entero" << endl; cout << "4 - Calcular la imagen especular de un entero" << endl; cout << "5 - Comprobar si un entero es primo" << endl; cout << "6 - Calcular la cifra más significativa de un numero" << endl; cout << "7 - Calcular la mayor cifra de un numero" << endl; cout << "8 - Duplicar las cifras de un numero" << endl; cout << "9 - Cerificar un numero" << endl; cout << "10 - Calcular el numero de cifras de un numero en base b" << endl; cout << "11 - Sumar las cifras de un numero en base b" << endl; cout << "12 - Extraer una cifra de un numero en base b" << endl; cout << "13 - Calcular la cifra más significativa de un numero en base b" << endl; cout << "14 - Calcular la mayor cifra de un numero en base b" << endl << endl; } /* * Pre: --- * Post: Ejecuta las acciones asociadas a la orden cuyo código es [operación] */ void ejecutarOrden (int operacion) { if (operacion >= 1 && operacion <= 14) { /* * Se va a ejcutar una operación válida. En primer lugar se pide al operador * que defina un número entero */ int numero; cout << "Escriba un numero entero : " << flush; cin >> numero; if (operacion==1) { /* Informa del número de cifras de [numero] */ cout << "El numero " << numero << " tiene " << numCifras(numero) << " cifras" << endl; } else if (operacion==2) { /* Informa de la suma de las cifras de [numero] */ cout << "Las cifras de " << numero << " suman " << sumaCifras(numero) << endl; } else if (operacion==3) { /* El operador debe definir la posición de una cifra de [número] */ int posicion; cout << "Seleccione la posicion de una cifra: " << flush; cin >> posicion; /* Informa del valor de la cifra ubicada en [posición] de [numero] */ cout << "La cifra situada en la posicion " << posicion << " del numero " << numero << " es " << cifra(numero, posicion) << endl; } else if (operacion==4) { /* Informa del valor de la imagen especular de [numero] */ cout << "El numero imagen especular del " << numero << " es el " << imagen(numero) << endl; } else if (operacion==5) { /* Informa si [numero] es un número primo o no lo es */ cout << "El numero " << numero; if (!esPrimo(numero)) { cout << " no"; } cout << " es primo" << endl; } else if (operacion==6) { cout << "Su cifra más significativa es " << cifraMasSignificativa(numero) << endl; } else if (operacion==7) { cout << "Su mayor cifra es " << cifraMayor(numero) << endl; } else if (operacion==8) { cout << "El resultado es " << duplicarCifras(numero) << endl; } else if (operacion==9) { cout << "El resultado es " << cerificar(numero) << endl; } else if (operacion>=10 && operacion <= 14) { int b; cout << "Introduce una base: " << flush; cin >> b; if (operacion == 10) { cout << "El número de cifras es " << numCifras(numero,b) << endl; } if (operacion == 11) { cout << "La suma de cifras es " << sumaCifras(numero,b) << endl; } if (operacion == 12) { int pos; cout << "Seleccione la posicion de una cifra: " << flush; cin >> pos; cout << "La cifra en esa posicion es " << cifra(numero,pos,b) << endl; } if (operacion == 13) { cout << "La cifra más significativa es " << cifraMasSignificativa(numero, b) << endl; } if (operacion == 14) { cout << "La mayor cifra es " << cifraMayor(numero, b) << endl; } } else { /* El código de operación no es válido */ cout << "Opción desconocida" << endl; } } } /* * Plantea al operador de forma reiterada un menú con varias opciones, lee * la respuesta del operador y presenta los resultados de ejecutar la opción * elegida. Concluye cuando el operador selecciona la opción [0] */ int main () { /* * Presenta por primera vez el menú de opciones y lee la respuesta del operador */ presentarMenu(); int operacion; cout << "Seleccione una operacion [0-14]: " << flush; cin >> operacion; /* * Itera hasta que el valor de [opcion] sea igual a 0 */ while (operacion!=0) { /* * Ejecuta la última operación seleccionada */ ejecutarOrden(operacion); /* * Presenta de nuevo el menú de opciones */ presentarMenu(); /* * Lee la respuesta del operador */ cout << "\nSeleccione una operacion [0-14]: " << flush; cin >> operacion; } }
#include<bits/stdc++.h> using namespace std; int arr[100000], len; void read_inputs(string file_name) { ifstream input_stream; input_stream.open(file_name); if (!input_stream) { cout << "Cannot open file or File dose not exist.\n"; exit(1); } int num, i = 0; while(input_stream >> num) { arr[i++] = num; } len = i; input_stream.close(); } void find_min_max(int &min_num, int &max_num, int left, int right) { if(left == right) { min_num = min(min_num, arr[left]); max_num = max(max_num, arr[right]); return; } else if(left == right -1) { if(arr[left] < arr[right]) { min_num = min(arr[left], min_num); max_num = max(max_num, arr[right]); } else { min_num = min(arr[right], min_num); max_num = max(max_num, arr[left]); } return; } else { int mid = (left + right)/2; find_min_max(min_num, max_num, left, mid); find_min_max(min_num, max_num, mid+1, right); } } int main() { int min_num, max_num; read_inputs("input.txt"); min_num = INT_MAX; max_num = INT_MIN; find_min_max(min_num, max_num, 0, len); cout<<"Minimum : " << min_num<< endl<<"Maximum : " << max_num<<endl; return 0; }
#include <cstddef> typedef int Rank; #define ListNodePosi(T) ListNode<T>* // 文本宏替换 template <typename T> class ListNode { public: // Data member T data; ListNodePosi ( T ) pred; ListNodePosi ( T ) succ; // 数据区,前驱,后继 // constructor ListNode ( T e, ListNodePosi ( T ) p = nullptr, ListNodePosi ( T ) s = nullptr ) : data ( e ), pred ( p ), succ ( s ) {} // default constructor ListNode () {} // for header and trailer // operation ListNodePosi ( T ) insertAsPred ( T const &e ); ListNodePosi ( T ) insertAsSucc ( T const &e ); }; /******************************************************************************* * implementation * *******************************************************************************/ template <typename T> ListNodePosi ( T ) ListNode<T>::insertAsPred ( T const &e ) { // new 退出作用域之后 还存在 ListNodePosi ( T ) node = new ListNode ( e, this->pred, this ); pred->succ = node; pred = node; // 先设置前驱的后继,再设置后继的前驱 return node; } template <typename T> ListNodePosi ( T ) ListNode<T>::insertAsSucc ( T const &e ) { ListNodePosi ( T ) node = new ListNode ( e, this, this->succ ); succ->pred = node; succ = node; return node; }
#ifndef __PROXY_FACTORY_H__ #define __PROXY_FACTORY_H__ #include "Proxy.h" #include <memory> class ProxyFactory { std::shared_ptr<Proxy> getObject(); }; #endif // __PROXY_FACTORY_H__
// // Created by wqy on 19-12-11. // #ifndef VERIFIER_ACTION_H #define VERIFIER_ACTION_H #include "../Term/AttributeTerm.h" namespace esc { class Action { public: //Action(); //Action(const string& toParse); virtual string to_string() const; virtual int getID() = 0; // ID : {1 : AssignmentAction, 2 : SignalAction} }; } #endif //VERIFIER_ACTION_H
#include "randomizer_options.hpp" #include <iostream> #include <landstalker-lib/constants/item_codes.hpp> #include <landstalker-lib/tools/stringtools.hpp> #include <landstalker-lib/tools/vectools.hpp> #include <landstalker-lib/tools/bitstream_writer.hpp> #include <landstalker-lib/tools/bitstream_reader.hpp> #include <landstalker-lib/exceptions.hpp> #include "tools/base64.hpp" static const std::array<const char*, 3> GOALS_TABLE = { "beat_gola", "reach_kazalt", "beat_dark_nole" }; static uint8_t get_goal_id(const std::string& goal_string) { for(size_t i=0 ; i<GOALS_TABLE.size() ; ++i) if(GOALS_TABLE[i] == goal_string) return i; throw LandstalkerException("Unknown goal '" + goal_string + "'."); } RandomizerOptions::RandomizerOptions(const ArgumentDictionary& args, const std::array<std::string, ITEM_COUNT>& item_names, const std::vector<std::string>& spawn_location_names) { _item_names = item_names; _spawn_location_names = spawn_location_names; _starting_items.fill(0); _items_distribution.fill(0); std::string permalink_string = args.get_string("permalink"); if(!permalink_string.empty()) { // Permalink case: unpack it to find the preset and seed and generate the same world this->parse_permalink(permalink_string); } else { // Regular case: pick a random seed, read a preset file to get the config and generate a new world _seed = (uint32_t) std::chrono::system_clock::now().time_since_epoch().count(); std::string preset_path = args.get_string("preset"); stringtools::trim(preset_path); if(preset_path.empty()) { if(args.get_boolean("stdin", true)) { std::cout << "Please specify a preset name (name of a file inside the 'presets' folder, leave empty for default): "; std::getline(std::cin, preset_path); stringtools::trim(preset_path); } if(preset_path.empty()) preset_path = "default"; } // If a path was given, filter any kind of directories only keeping the last part of the path if(preset_path.find('/') == std::string::npos) preset_path = "./presets/" + preset_path; if(!preset_path.ends_with(".json")) preset_path += ".json"; std::ifstream preset_file(preset_path); if(!preset_file) throw LandstalkerException("Could not open preset file at given path '" + preset_path + "'"); std::cout << "Preset: '" << preset_path << "'\n"; Json preset_json; preset_file >> preset_json; this->parse_json(preset_json); } this->validate(); } Json RandomizerOptions::to_json() const { Json json; // Game settings json["gameSettings"]["goal"] = this->goal(); json["gameSettings"]["jewelCount"] = _jewel_count; json["gameSettings"]["armorUpgrades"] = _use_armor_upgrades; json["gameSettings"]["startingGold"] = _starting_gold; json["gameSettings"]["startingLife"] = _starting_life; json["gameSettings"]["startingItems"] = Json::object(); for(uint8_t i=0 ; i<ITEM_LIFESTOCK ; ++i) { if(_starting_items[i] > 0) json["gameSettings"]["startingItems"][_item_names[i]] = _starting_items[i]; } json["gameSettings"]["fixArmletSkip"] = _fix_armlet_skip; json["gameSettings"]["removeTreeCuttingGlitchDrops"] = _remove_tree_cutting_glitch_drops; json["gameSettings"]["consumableRecordBook"] = _consumable_record_book; json["gameSettings"]["consumableSpellBook"] = _consumable_spell_book; json["gameSettings"]["removeGumiBoulder"] = _remove_gumi_boulder; json["gameSettings"]["removeTiborRequirement"] = _remove_tibor_requirement; json["gameSettings"]["allTreesVisitedAtStart"] = _all_trees_visited_at_start; json["gameSettings"]["ekeekeAutoRevive"] = _ekeeke_auto_revive; json["gameSettings"]["enemiesDamageFactor"] = _enemies_damage_factor; json["gameSettings"]["enemiesHealthFactor"] = _enemies_health_factor; json["gameSettings"]["enemiesArmorFactor"] = _enemies_armor_factor; json["gameSettings"]["enemiesGoldsFactor"] = _enemies_golds_factor; json["gameSettings"]["enemiesDropChanceFactor"] = _enemies_drop_chance_factor; json["gameSettings"]["healthGainedPerLifestock"] = _health_gained_per_lifestock; json["gameSettings"]["fastTransitions"] = _fast_transitions; json["gameSettings"]["archipelagoWorld"] = _archipelago_world; json["gameSettings"]["finiteGroundItems"] = Json::array(); for(uint8_t item_id : _finite_ground_items) json["gameSettings"]["finiteGroundItems"].emplace_back(_item_names[item_id]); json["gameSettings"]["finiteShopItems"] = Json::array(); for(uint8_t item_id : _finite_shop_items) json["gameSettings"]["finiteShopItems"].emplace_back(_item_names[item_id]); // Randomizer settings json["randomizerSettings"]["allowSpoilerLog"] = _allow_spoiler_log; json["randomizerSettings"]["spawnLocations"] = Json::array(); for(uint8_t spawn_loc_id : _possible_spawn_locations) json["randomizerSettings"]["spawnLocations"].emplace_back(_spawn_location_names[spawn_loc_id]); json["randomizerSettings"]["shuffleTrees"] = _shuffle_tibor_trees; json["randomizerSettings"]["shopPricesFactor"] = _shop_prices_factor; json["randomizerSettings"]["enemyJumpingInLogic"] = _enemy_jumping_in_logic; json["randomizerSettings"]["damageBoostingInLogic"] = _damage_boosting_in_logic; json["randomizerSettings"]["treeCuttingGlitchInLogic"] = _tree_cutting_glitch_in_logic; json["randomizerSettings"]["allowWhistleUsageBehindTrees"] = _allow_whistle_usage_behind_trees; json["randomizerSettings"]["ensureEkeEkeInShops"] = _ensure_ekeeke_in_shops; std::map<std::string, uint8_t> items_distribution_with_names; for(size_t i=0 ; i < _items_distribution.size() ; ++i) { uint8_t amount = _items_distribution[i]; const std::string& item_name = _item_names[i]; if(amount > 0) items_distribution_with_names[item_name] = amount; } json["randomizerSettings"]["itemsDistributions"] = items_distribution_with_names; json["randomizerSettings"]["fillerItem"] = _item_names[_filler_item]; json["randomizerSettings"]["hintsDistribution"] = { { "regionRequirement", _hints_distribution_region_requirement }, { "itemRequirement", _hints_distribution_item_requirement }, { "itemLocation", _hints_distribution_item_location }, { "darkRegion", _hints_distribution_dark_region }, { "joke", _hints_distribution_joke } }; if(!_model_patch_items.empty()) json["modelPatch"]["items"] = _model_patch_items; if(!_model_patch_spawns.empty()) json["modelPatch"]["spawnLocations"] = _model_patch_spawns; if(!_model_patch_hint_sources.empty()) json["modelPatch"]["hintSources"] = _model_patch_hint_sources; json["christmasEvent"] = _christmas_event; json["secretEvent"] = _secret_event; return json; } void RandomizerOptions::parse_json(const Json& json) { if(json.contains("permalink")) { this->parse_permalink(json.at("permalink")); return; } if(json.contains("modelPatch")) { const Json& model_patch_json = json.at("modelPatch"); if(model_patch_json.contains("items")) _model_patch_items = model_patch_json.at("items"); if(model_patch_json.contains("spawnLocations")) { _model_patch_spawns = model_patch_json.at("spawnLocations"); for(const auto& [name, _] : _model_patch_spawns.items()) _spawn_location_names.emplace_back(name); } if(model_patch_json.contains("hintSources")) _model_patch_hint_sources = model_patch_json.at("hintSources"); } if(json.contains("gameSettings")) { const Json& game_settings_json = json.at("gameSettings"); if(game_settings_json.contains("goal")) _goal = get_goal_id(game_settings_json.at("goal")); if(game_settings_json.contains("jewelCount")) _jewel_count = game_settings_json.at("jewelCount"); if(game_settings_json.contains("armorUpgrades")) _use_armor_upgrades = game_settings_json.at("armorUpgrades"); if(game_settings_json.contains("startingLife")) _starting_life = game_settings_json.at("startingLife"); if(game_settings_json.contains("startingGold")) _starting_gold = game_settings_json.at("startingGold"); if(game_settings_json.contains("fixArmletSkip")) _fix_armlet_skip = game_settings_json.at("fixArmletSkip"); if(game_settings_json.contains("removeTreeCuttingGlitchDrops")) _remove_tree_cutting_glitch_drops = game_settings_json.at("removeTreeCuttingGlitchDrops"); if(game_settings_json.contains("consumableRecordBook")) _consumable_record_book = game_settings_json.at("consumableRecordBook"); if(game_settings_json.contains("consumableSpellBook")) _consumable_spell_book = game_settings_json.at("consumableSpellBook"); if(game_settings_json.contains("removeGumiBoulder")) _remove_gumi_boulder = game_settings_json.at("removeGumiBoulder"); if(game_settings_json.contains("removeTiborRequirement")) _remove_tibor_requirement = game_settings_json.at("removeTiborRequirement"); if(game_settings_json.contains("allTreesVisitedAtStart")) _all_trees_visited_at_start = game_settings_json.at("allTreesVisitedAtStart"); if(game_settings_json.contains("ekeekeAutoRevive")) _ekeeke_auto_revive = game_settings_json.at("ekeekeAutoRevive"); if(game_settings_json.contains("enemiesDamageFactor")) _enemies_damage_factor = game_settings_json.at("enemiesDamageFactor"); if(game_settings_json.contains("enemiesHealthFactor")) _enemies_health_factor = game_settings_json.at("enemiesHealthFactor"); if(game_settings_json.contains("enemiesArmorFactor")) _enemies_armor_factor = game_settings_json.at("enemiesArmorFactor"); if(game_settings_json.contains("enemiesGoldsFactor")) _enemies_golds_factor = game_settings_json.at("enemiesGoldsFactor"); if(game_settings_json.contains("enemiesDropChanceFactor")) _enemies_drop_chance_factor = game_settings_json.at("enemiesDropChanceFactor"); if(game_settings_json.contains("healthGainedPerLifestock")) _health_gained_per_lifestock = game_settings_json.at("healthGainedPerLifestock"); if(game_settings_json.contains("fastTransitions")) _fast_transitions = game_settings_json.at("fastTransitions"); if(game_settings_json.contains("archipelagoWorld")) _archipelago_world = game_settings_json.at("archipelagoWorld"); if(game_settings_json.contains("startingItems")) { std::map<std::string, uint8_t> starting_items = game_settings_json.at("startingItems"); for(auto& [item_name, quantity] : starting_items) { auto it = std::find(_item_names.begin(), _item_names.end(), item_name); if(it == _item_names.end()) throw LandstalkerException("Unknown item name '" + item_name + "' in starting items section of preset file."); uint8_t item_id = std::distance(_item_names.begin(), it); _starting_items[item_id] = quantity; } } _finite_ground_items = { ITEM_LIFESTOCK, ITEM_SHORT_CAKE, ITEM_PAWN_TICKET }; if(game_settings_json.contains("finiteGroundItems")) parse_json_item_array(game_settings_json.at("finiteGroundItems"), _finite_ground_items); _finite_shop_items = { ITEM_PAWN_TICKET }; if(game_settings_json.contains("finiteShopItems")) parse_json_item_array(game_settings_json.at("finiteShopItems"), _finite_shop_items); } if(json.contains("randomizerSettings")) { const Json& randomizer_settings_json = json.at("randomizerSettings"); if(randomizer_settings_json.contains("allowSpoilerLog")) _allow_spoiler_log = randomizer_settings_json.at("allowSpoilerLog"); if(randomizer_settings_json.contains("spawnLocations")) { std::vector<std::string> spawn_loc_names; randomizer_settings_json.at("spawnLocations").get_to(spawn_loc_names); for(const std::string& name : spawn_loc_names) { auto it = std::find(_spawn_location_names.begin(), _spawn_location_names.end(), name); if(it == _spawn_location_names.end()) throw LandstalkerException("Unknown spawn location '" + name + "' in preset file."); _possible_spawn_locations.emplace_back((uint8_t)std::distance(_spawn_location_names.begin(), it)); } } else if(randomizer_settings_json.contains("spawnLocation")) { std::string name = randomizer_settings_json.at("spawnLocation"); auto it = std::find(_spawn_location_names.begin(), _spawn_location_names.end(), name); if(it == _spawn_location_names.end()) throw LandstalkerException("Unknown spawn location '" + name + "' in preset file."); _possible_spawn_locations.emplace_back((uint8_t)std::distance(_spawn_location_names.begin(), it)); } if(randomizer_settings_json.contains("shuffleTrees")) _shuffle_tibor_trees = randomizer_settings_json.at("shuffleTrees"); if(randomizer_settings_json.contains("shopPricesFactor")) _shop_prices_factor = randomizer_settings_json.at("shopPricesFactor"); if(randomizer_settings_json.contains("enemyJumpingInLogic")) _enemy_jumping_in_logic = randomizer_settings_json.at("enemyJumpingInLogic"); if(randomizer_settings_json.contains("damageBoostingInLogic")) _damage_boosting_in_logic = randomizer_settings_json.at("damageBoostingInLogic"); if(randomizer_settings_json.contains("treeCuttingGlitchInLogic")) _tree_cutting_glitch_in_logic = randomizer_settings_json.at("treeCuttingGlitchInLogic"); if(randomizer_settings_json.contains("allowWhistleUsageBehindTrees")) _allow_whistle_usage_behind_trees = randomizer_settings_json.at("allowWhistleUsageBehindTrees"); if(randomizer_settings_json.contains("ensureEkeEkeInShops")) _ensure_ekeeke_in_shops = randomizer_settings_json.at("ensureEkeEkeInShops"); if(randomizer_settings_json.contains("itemsDistribution")) { std::map<std::string, uint8_t> items_distribution = randomizer_settings_json.at("itemsDistribution"); for(auto& [item_name, quantity] : items_distribution) { auto it = std::find(_item_names.begin(), _item_names.end(), item_name); if(it == _item_names.end()) throw LandstalkerException("Unknown item name '" + item_name + "' in items distribution section of preset file."); uint8_t item_id = std::distance(_item_names.begin(), it); _items_distribution[item_id] = quantity; } } if(randomizer_settings_json.contains("fillerItem")) { std::string item_name = randomizer_settings_json.at("fillerItem"); auto it = std::find(_item_names.begin(), _item_names.end(), item_name); if(it == _item_names.end()) throw LandstalkerException("Unknown item name '" + item_name + "' in filler item of preset file."); uint8_t item_id = std::distance(_item_names.begin(), it); _filler_item = item_id; } if(randomizer_settings_json.contains("hintsDistribution")) { const Json& hints_distrib_json = randomizer_settings_json.at("hintsDistribution"); if(hints_distrib_json.contains("regionRequirement")) _hints_distribution_region_requirement = hints_distrib_json.at("regionRequirement"); if(hints_distrib_json.contains("itemRequirement")) _hints_distribution_item_requirement = hints_distrib_json.at("itemRequirement"); if(hints_distrib_json.contains("itemLocation")) _hints_distribution_item_location = hints_distrib_json.at("itemLocation"); if(hints_distrib_json.contains("darkRegion")) _hints_distribution_dark_region = hints_distrib_json.at("darkRegion"); if(hints_distrib_json.contains("joke")) _hints_distribution_joke = hints_distrib_json.at("joke"); } } _christmas_event = json.value("christmasEvent", false); _secret_event = json.value("secretEvent", false); if(json.contains("world")) _world_json = json.at("world"); if(json.contains("seed")) _seed = json.at("seed"); } void RandomizerOptions::parse_json_item_array(const Json& json, std::vector<uint8_t>& output) { output.reserve(ITEM_COUNT); if(json.is_string()) { std::string str = json; if(str == "all") { output = {}; for(uint8_t i=0 ; i<ITEM_COUNT ; ++i) output.emplace_back(i); } else if(str == "none") output = {}; } else if(json.is_array()) { output = {}; for(std::string item_name : json) { auto it = std::find(_item_names.begin(), _item_names.end(), item_name); if(it == _item_names.end()) throw LandstalkerException("Unknown item name '" + item_name + "' inside item array in preset file."); uint8_t item_id = std::distance(_item_names.begin(), it); output.emplace_back(item_id); } } } void RandomizerOptions::validate() const { if(_jewel_count > 9) throw LandstalkerException("Jewel count must be between 0 and 9."); } std::string RandomizerOptions::goal() const { return GOALS_TABLE.at(_goal); } std::vector<std::string> RandomizerOptions::possible_spawn_locations() const { std::vector<std::string> ret; for(uint8_t spawn_loc_id : _possible_spawn_locations) ret.emplace_back(_spawn_location_names[spawn_loc_id]); return ret; } std::vector<std::string> RandomizerOptions::hash_words() const { std::vector<std::string> words = { "EkeEke", "Nail", "Horn", "Fang", "Magic", "Ice", "Thunder", "Gaia", "Mars", "Moon", "Saturn", "Venus", "Detox", "Statue", "Golden", "Mind", "Card", "Lantern", "Garlic", "Paralyze", "Chicken", "Death", "Jypta", "Sun", "Book", "Lithograph", "Red", "Purple", "Jewel", "Pawn", "Gola", "Nole", "Logs", "Oracle", "Stone", "Idol", "Key", "Safety", "Pass", "Bell", "Massan", "Gumi", "Ryuma", "Mercator", "Verla", "Destel", "Kazalt", "Greedly", "Mir", "Miro", "Prospero", "Fara", "Orc", "Mushroom", "Slime", "Cyclops", "Kado", "Kan", "Well", "Dungeon", "Loria", "Kayla", "Wally", "Ink", "Palace", "Gold", "Waterfall", "Shrine", "Swamp", "Hideout", "Greenmaze", "Mines", "Helga", "Fahl", "Yard", "Twinkle", "Firedemon", "Spinner", "Golem", "Boulder", "Kindly", "Route", "Shop", "Green", "Yellow", "Blue", "Fireproof", "Iron", "Spikes", "Healing", "Snow", "Repair", "Casino", "Ticket", "Axe", "Ribbon", "Armlet", "Einstein", "Whistle", "Spell", "King", "Dragon", "Dahl", "Restoration", "Friday", "Short", "Cake", "Life", "Stock", "Zak", "Duke", "Dex", "Slasher", "Marley", "Nigel", "Ninja", "Ghost", "Tibor", "Knight", "Pockets", "Arthur", "Crypt", "Mummy", "Poison", "Labyrinth", "Lake", "Volcano", "Crate", "Jar", "Mayor", "Dexter", "Treasure", "Chest", "Ludwig", "Quake", "Hyper", "Shell", "Chrome", "Steel", "Boots", "Sword", "Teller", "Marty", "Cutter", "Greenpea", "Kelketo", "Unicorn", "Lizard", "Tree", "Cave", "Kan", "Foxy" }; std::mt19937 rng(_seed); vectools::shuffle(words, rng); return { words.begin(), words.begin()+4 }; } std::string RandomizerOptions::permalink() const { BitstreamWriter bitpack; bitpack.pack((uint8_t)MAJOR_RELEASE); bitpack.pack(_goal); bitpack.pack(_jewel_count); bitpack.pack(_starting_life); bitpack.pack(_starting_gold); bitpack.pack(_health_gained_per_lifestock); bitpack.pack(_fast_transitions); bitpack.pack(_seed); bitpack.pack(_use_armor_upgrades); bitpack.pack(_fix_armlet_skip); bitpack.pack(_remove_tree_cutting_glitch_drops); bitpack.pack(_consumable_record_book); bitpack.pack(_consumable_spell_book); bitpack.pack(_remove_gumi_boulder); bitpack.pack(_remove_tibor_requirement); bitpack.pack(_all_trees_visited_at_start); bitpack.pack(_ekeeke_auto_revive); bitpack.pack(_allow_spoiler_log); bitpack.pack(_shuffle_tibor_trees); bitpack.pack(_enemy_jumping_in_logic); bitpack.pack(_tree_cutting_glitch_in_logic); bitpack.pack(_damage_boosting_in_logic); bitpack.pack(_allow_whistle_usage_behind_trees); bitpack.pack(_ensure_ekeeke_in_shops); bitpack.pack_array(_items_distribution); bitpack.pack(_filler_item); bitpack.pack(_hints_distribution_region_requirement); bitpack.pack(_hints_distribution_item_requirement); bitpack.pack(_hints_distribution_item_location); bitpack.pack(_hints_distribution_dark_region); bitpack.pack(_hints_distribution_joke); bitpack.pack(_christmas_event); bitpack.pack(_secret_event); bitpack.pack_if(_enemies_damage_factor != 100, _enemies_damage_factor); bitpack.pack_if(_enemies_health_factor != 100, _enemies_health_factor); bitpack.pack_if(_enemies_armor_factor != 100, _enemies_armor_factor); bitpack.pack_if(_enemies_golds_factor != 100, _enemies_golds_factor); bitpack.pack_if(_enemies_drop_chance_factor != 100, _enemies_drop_chance_factor); bitpack.pack_if(_shop_prices_factor != 100, _shop_prices_factor); for(size_t i=0 ; i<_starting_items.size() ; ++i) { uint8_t item_id = (uint8_t)i; uint8_t quantity = _starting_items[i]; if(quantity != 0) { bitpack.pack(true); bitpack.pack(item_id); bitpack.pack(quantity); } } bitpack.pack(false); bitpack.pack_vector(_possible_spawn_locations); bitpack.pack_vector(_finite_ground_items); bitpack.pack_vector(_finite_shop_items); bitpack.pack_vector_if(!_world_json.empty(), Json::to_msgpack(_world_json)); bitpack.pack_vector_if(!_model_patch_items.empty(), Json::to_msgpack(_model_patch_items)); bitpack.pack_vector_if(!_model_patch_spawns.empty(), Json::to_msgpack(_model_patch_spawns)); bitpack.pack_vector_if(!_model_patch_hint_sources.empty(), Json::to_msgpack(_model_patch_hint_sources)); return "l" + base64_encode(bitpack.bytes()) + "s"; } void RandomizerOptions::parse_permalink(std::string permalink) { stringtools::trim(permalink); if(!permalink.starts_with("l") || !permalink.ends_with("s")) throw LandstalkerException("This permalink is malformed, please make sure you copied the full permalink string."); std::vector<uint8_t> bytes = base64_decode(permalink.substr(1, permalink.size() - 2)); BitstreamReader bitpack(bytes); uint8_t version = bitpack.unpack<uint8_t>(); if(version != (uint8_t)MAJOR_RELEASE) throw WrongVersionException("This permalink comes from an incompatible version of Randstalker (" + std::to_string(version) + ")."); _goal = bitpack.unpack<uint8_t>(); _jewel_count = bitpack.unpack<uint8_t>(); _starting_life = bitpack.unpack<uint8_t>(); _starting_gold = bitpack.unpack<uint16_t>(); _health_gained_per_lifestock = bitpack.unpack<uint8_t>(); _fast_transitions = bitpack.unpack<bool>(); _seed = bitpack.unpack<uint32_t>(); _use_armor_upgrades = bitpack.unpack<bool>(); _fix_armlet_skip = bitpack.unpack<bool>(); _remove_tree_cutting_glitch_drops = bitpack.unpack<bool>(); _consumable_record_book = bitpack.unpack<bool>(); _consumable_spell_book = bitpack.unpack<bool>(); _remove_gumi_boulder = bitpack.unpack<bool>(); _remove_tibor_requirement = bitpack.unpack<bool>(); _all_trees_visited_at_start = bitpack.unpack<bool>(); _ekeeke_auto_revive = bitpack.unpack<bool>(); _allow_spoiler_log = bitpack.unpack<bool>(); _shuffle_tibor_trees = bitpack.unpack<bool>(); _enemy_jumping_in_logic = bitpack.unpack<bool>(); _tree_cutting_glitch_in_logic = bitpack.unpack<bool>(); _damage_boosting_in_logic = bitpack.unpack<bool>(); _allow_whistle_usage_behind_trees = bitpack.unpack<bool>(); _ensure_ekeeke_in_shops = bitpack.unpack<bool>(); _items_distribution = bitpack.unpack_array<uint8_t, ITEM_COUNT>(); _filler_item = bitpack.unpack<uint8_t>(); _hints_distribution_region_requirement = bitpack.unpack<uint8_t>(); _hints_distribution_item_requirement = bitpack.unpack<uint8_t>(); _hints_distribution_item_location = bitpack.unpack<uint8_t>(); _hints_distribution_dark_region = bitpack.unpack<uint8_t>(); _hints_distribution_joke = bitpack.unpack<uint8_t>(); _christmas_event = bitpack.unpack<bool>(); _secret_event = bitpack.unpack<bool>(); if(bitpack.unpack<bool>()) _enemies_damage_factor = bitpack.unpack<uint16_t>(); if(bitpack.unpack<bool>()) _enemies_health_factor = bitpack.unpack<uint16_t>(); if(bitpack.unpack<bool>()) _enemies_armor_factor = bitpack.unpack<uint16_t>(); if(bitpack.unpack<bool>()) _enemies_golds_factor = bitpack.unpack<uint16_t>(); if(bitpack.unpack<bool>()) _enemies_drop_chance_factor = bitpack.unpack<uint16_t>(); if(bitpack.unpack<bool>()) _shop_prices_factor = bitpack.unpack<uint16_t>(); while(bitpack.unpack<bool>()) { uint8_t item_id = bitpack.unpack<uint8_t>(); uint8_t quantity = bitpack.unpack<uint8_t>(); _starting_items[item_id] = quantity; } _possible_spawn_locations = bitpack.unpack_vector<uint8_t>(); _finite_ground_items = bitpack.unpack_vector<uint8_t>(); _finite_shop_items = bitpack.unpack_vector<uint8_t>(); if(bitpack.unpack<bool>()) _world_json = Json::from_msgpack(bitpack.unpack_vector<uint8_t>()); if(bitpack.unpack<bool>()) _model_patch_items = Json::from_msgpack(bitpack.unpack_vector<uint8_t>()); if(bitpack.unpack<bool>()) _model_patch_spawns = Json::from_msgpack(bitpack.unpack_vector<uint8_t>()); if(bitpack.unpack<bool>()) _model_patch_hint_sources = Json::from_msgpack(bitpack.unpack_vector<uint8_t>()); }