text
stringlengths
8
6.88M
#include "menubox.h" MenuBox::MenuBox(QWidget *parent) : QComboBox(parent) { setPalette( QPalette( Qt::blue ) ); }
/* * Copyright (c) 2016-2019 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_COMPARATORS_PARTIAL_GREATER_H_ #define CPPSORT_COMPARATORS_PARTIAL_GREATER_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <type_traits> #include <utility> #include <cpp-sort/comparators/weak_greater.h> #include <cpp-sort/utility/branchless_traits.h> #include <cpp-sort/utility/static_const.h> namespace cppsort { namespace detail { //////////////////////////////////////////////////////////// // Weak order for floating point types template<typename T> auto partial_greater(T lhs, T rhs) noexcept -> std::enable_if_t<std::is_floating_point<T>::value, bool> { return lhs > rhs; } //////////////////////////////////////////////////////////// // Generic overload: a weak order is also a partial order template<typename T> auto partial_greater(const T& lhs, const T& rhs) noexcept(noexcept(cppsort::weak_greater(lhs, rhs))) -> decltype(cppsort::weak_greater(lhs, rhs)) { return cppsort::weak_greater(lhs, rhs); } //////////////////////////////////////////////////////////// // Customization point struct partial_greater_fn { template<typename T, typename U> constexpr auto operator()(T&& lhs, U&& rhs) const noexcept(noexcept(partial_greater(std::forward<T>(lhs), std::forward<U>(rhs)))) -> decltype(partial_greater(std::forward<T>(lhs), std::forward<U>(rhs))) { return partial_greater(std::forward<T>(lhs), std::forward<U>(rhs)); } using is_transparent = void; }; } using partial_greater_t = detail::partial_greater_fn; namespace { constexpr auto&& partial_greater = utility::static_const< detail::partial_greater_fn >::value; } // Branchless traits namespace utility { template<typename T> struct is_probably_branchless_comparison<cppsort::partial_greater_t, T>: std::is_arithmetic<T> {}; } } #endif // CPPSORT_COMPARATORS_PARTIAL_GREATER_H_
#ifndef Catipillar_h #define Catipillar_h #include "Animation.h" class Catipillar : public Animation { public: Catipillar(void); virtual void loop(variables_t *vars); virtual void reset(variables_t *vars); private: }; #endif
#include<iostream> #include<vector> using namespace std; int M,N; struct Node{ int steps; int sum; }; vector<vector<int>> compute_cost; int res=0; void dfs(int i,int j,vector<vector<int>> visited,vector<vector<Node>> dp) { if(visited[i][j]==1) return; visited[i][j]=1; if(i==M-1&&j==N-1) { res=max(res,dp[i][j].sum/dp[i][j].steps); return; } int cursum,cursteps; if(i-1>=0) { dp[i-1][j].sum=dp[i][j].sum+compute_cost[i-1][j]; dp[i-1][j].steps=dp[i][j].steps+1; dfs(i-1,j,visited,dp); } if(i+1<M) { dp[i+1][j].sum=dp[i][j].sum+compute_cost[i+1][j]; dp[i+1][j].steps=dp[i][j].steps+1; dfs(i+1,j,visited,dp); } if(j-1>=0) { dp[i][j-1].sum=dp[i][j].sum+compute_cost[i][j-1]; dp[i][j-1].steps=dp[i][j].steps+1; dfs(i,j-1,visited,dp); } if(j+1<N) { dp[i][j+1].sum=dp[i][j].sum+compute_cost[i][j+1]; dp[i][j+1].steps=dp[i][j].steps+1; dfs(i,j+1,visited,dp); } } int main() { cin>>M>>N; vector<vector<Node>> dp; vector<vector<int>> visited(M,vector<int>(N,0)); for(int i=0;i<M;i++) { vector<int> tmp; vector<Node> tmp1; for(int j=0;j<N;j++) { int x; Node y; y.steps=1; y.sum=0; cin>>x; tmp.push_back(x); tmp1.push_back(y); } compute_cost.push_back(tmp); dp.push_back(tmp1); } dp[0][0].sum=compute_cost[0][0]; dp[0][0].steps=1; dfs(0,0,visited,dp); cout<<res<<endl; }
#define encoder_motor_pin_A 2 //change to corresponding pins in mega #define encoder_motor_pin_B 3 //change to corresponding pins in mega #define encoder_motor_pin_input_1 10 #define encoder_motor_pin_input_2 12 #define encoder_motor_pin_enable 11 volatile unsigned int encoder_motor_pos = 2250; void setup() { pinMode(encoder_motor_pin_A, INPUT); pinMode(encoder_motor_pin_B, INPUT); attachInterrupt(0, doEncoderA, CHANGE); attachInterrupt(1, doEncoderB, CHANGE); pinMode(encoder_motor_pin_input_1, OUTPUT); pinMode(encoder_motor_pin_input_2, OUTPUT); pinMode(encoder_motor_pin_enable, OUTPUT); Serial.begin (9600); } void loop() { encoderMotorPos(2250); delay(4000); encoderMotorPos(3250); delay(4000); } void encoderMotorPos(int encoder_motor_final_pos) { while(encoder_motor_pos<encoder_motor_final_pos) { digitalWrite(encoder_motor_pin_input_1, HIGH); digitalWrite(encoder_motor_pin_input_2, LOW); analogWrite(encoder_motor_pin_enable, 120); } while(encoder_motor_pos>encoder_motor_final_pos) { digitalWrite(encoder_motor_pin_input_1, LOW); digitalWrite(encoder_motor_pin_input_2, HIGH); analogWrite(encoder_motor_pin_enable, 120); } digitalWrite(encoder_motor_pin_input_1, HIGH); digitalWrite(encoder_motor_pin_input_2, HIGH); analogWrite(encoder_motor_pin_enable, 0); } void encoderMotorCW(int encoder_motor_steps) { int encoder_motor_final_pos= encoder_motor_pos+encoder_motor_steps; while(encoder_motor_final_pos>encoder_motor_pos) { digitalWrite(encoder_motor_pin_input_1, HIGH); digitalWrite(encoder_motor_pin_input_2, LOW); analogWrite(encoder_motor_pin_enable, 120); } digitalWrite(encoder_motor_pin_input_1, HIGH); digitalWrite(encoder_motor_pin_input_2, HIGH); analogWrite(encoder_motor_pin_enable, 0); } void encoderMotorCCW(int encoder_motor_steps) { int encoder_motor_final_pos= encoder_motor_pos-encoder_motor_steps; while(encoder_motor_final_pos<encoder_motor_pos) { digitalWrite(encoder_motor_pin_input_1, LOW); digitalWrite(encoder_motor_pin_input_2, HIGH); analogWrite(encoder_motor_pin_enable, 120); } digitalWrite(encoder_motor_pin_input_1, HIGH); digitalWrite(encoder_motor_pin_input_2, HIGH); analogWrite(encoder_motor_pin_enable, 0); } void doEncoderA(){ if (digitalRead(encoder_motor_pin_A) == HIGH) { if (digitalRead(encoder_motor_pin_B) == LOW) { encoder_motor_pos = encoder_motor_pos + 1; // CW } else { encoder_motor_pos = encoder_motor_pos - 1; // CCW } } else { if (digitalRead(encoder_motor_pin_B) == HIGH) { encoder_motor_pos = encoder_motor_pos + 1; // CW } else { encoder_motor_pos = encoder_motor_pos - 1; // CCW } } } void doEncoderB(){ if (digitalRead(encoder_motor_pin_B) == HIGH) { if (digitalRead(encoder_motor_pin_A) == HIGH) { encoder_motor_pos = encoder_motor_pos + 1; // CW } else { encoder_motor_pos = encoder_motor_pos - 1; // CCW } } else { if (digitalRead(encoder_motor_pin_A) == LOW) { encoder_motor_pos = encoder_motor_pos + 1; // CW } else { encoder_motor_pos = encoder_motor_pos - 1; // CCW } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Espen Sand */ #ifndef _X11_ICON_H_ #define _X11_ICON_H_ #include "platforms/utilix/x11_all.h" class OpBitmap; class X11Icon { public: X11Icon(int screen=-1); ~X11Icon(); OP_STATUS SetBuffer(OpBitmap* bitmap); OP_STATUS SetBuffer(class OpWidgetImage* image); OP_STATUS SetBuffer(const UINT8* buffer, UINT32 num_bytes); OP_STATUS SetPixmap(OpBitmap* bitmap, BOOL make_mask, UINT32 depth = 24, UINT32 color = 0x00FFFFFF); OP_STATUS SetPixmap(class OpWidgetImage* image, BOOL make_mask, UINT32 depth = 24, UINT32 color = 0x00FFFFFF); OP_STATUS SetPixmap(const UINT8* buffer, UINT32 num_bytes, BOOL make_mask, UINT32 depth = 24, UINT32 color = 0x00FFFFFF); /** * Install icon on window. * * @param window Window to receive icon data */ void Apply(X11Types::Window window); /** * Clears allocated data. Use this if reusing the icon object */ void Reset(); /** * Modified dithering when paiting pixmap on bitmap with no alpha */ void SetDitherLevel(INT32 level) { m_dither_level = level; } /** * Sets size of returned icon. Using this can introduce scaling on the applied * image */ void SetSize(UINT32 width, UINT32 height) { m_width = width; m_height = height; } /** * Sets the background to a single color */ OP_STATUS SetBackground( UINT32 color ); /** * Sets the background using handle as the source */ OP_STATUS SetBackground( X11Types::Drawable handle, OpRect& rect, UINT32 depth ); /** * Returns bitmaps if SetBuffer() has been used, otherwise NULL. Bitmap is valid * until next call to SetBuffer() */ OpBitmap* GetBitmap() { MakeBitmap(); return m_bitmap; } /** * Returns pixmap if SetPixmap() has been used, otherwise None */ X11Types::Pixmap GetPixmap() const { return m_pixmap; } /** * Returns pixmap mask if SetPixmap has been used with make_mask parameter * set, otherwise None */ X11Types::Pixmap GetMask() const { return m_mask; } /** * Returns buffer if SetBuffer() has been used, otherwise NULL * Returns 32 bit elements. Format <width><height><data>...<data> * <data> is ARGB */ UINT32* GetBuffer() const { return m_buffer; } /** * Returns size of buffer if SetBuffer() has been used. Otherwise 0 */ UINT32 GetBufferSize() const { return m_buffer ? 2 + (m_buffer[0]*m_buffer[1]) : 0; } /** * Returns icon width */ UINT32 GetWidth() const { return m_width; } /** * Returns icon height */ UINT32 GetHeight() const { return m_height; } /** * Returns icon depth */ UINT32 GetDepth() const { return m_depth; } /** * Blends two lines together */ void BlendLine( const UINT32* src, UINT32* dest, UINT32 size ); /** * Utility function for setting standard application icon on * the window that belongs to 'widget'. It only makes sense * to set it on top level windows. */ static void SetApplicationIcon( class X11Widget* widget ); //void DumpBuffer(BOOL c_format); private: OP_STATUS ScaleBuffer(UINT32 width, UINT32 height); OP_STATUS MakeBitmap(); OP_STATUS MakeMask( BOOL use_buffer, UINT32 mask_color ); OP_STATUS MakeBuffer(OpBitmap* bitmap); /** Create an OpBitmap as a copy of the image in an OpWidgetImage. * * This method will return a newly created OpBitmap in 'ret_bmp'. * This pixmap will have size 'width' x 'height'. It will be * filled with 'bg_color' and then 'image' will be painted into * it. * * If the function does not return OpStatus::OK, '*ret_bmp' will * be 0 on return. Otherwise, '*ret_bmp' will be a valid OpBitmap * that must be deleted by the caller (using OP_DELETE). * * @param image The image to copy. * @param ret_bmp Returns the newly created OpBitmap. * @param width The width of the newly created OpBitmap. * @param height The height of the newly created OpBitmap. * @param bg_color The background colour to use in opera's * COLORREF format. Must be a pure colour, not a magic value. * @return Success or error status. */ OP_STATUS CreateOpBitmapFromOpWidgetImage(OpWidgetImage * image, OpBitmap ** ret_bmp, UINT32 width, UINT32 height, COLORREF bg_color); private: OpBitmap* m_bitmap; X11Types::Pixmap m_pixmap; X11Types::Pixmap m_mask; int m_screen; UINT32 m_width; UINT32 m_height; UINT32 m_depth; INT32 m_dither_level; UINT32* m_buffer; UINT32* m_background_buffer; BOOL m_has_background_color; UINT32 m_background_color; }; #endif
/* ** $Id: ldo.h,v 2.28 2015/11/23 11:29:43 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #ifndef ldo_h #define ldo_h #include "lobject.h" #include "lstate.h" #include "lzio.h" namespace youmecommon { /* ** Macro to check stack size and grow stack if needed. Parameters ** 'pre'/'pos' allow the macro to preserve a pointer into the ** stack across reallocations, doing the work only when needed. ** 'condmovestack' is used in heavy tests to force a stack reallocation ** at every check. */ #define luaD_checkstackaux(L,n,pre,pos) \ if (L->stack_last - L->top <= (n)) \ { pre; luaD_growstack(L, n); pos; } else { condmovestack(L,pre,pos); } /* In general, 'pre'/'pos' are empty (nothing to save) */ #define luaD_checkstack(L,n) luaD_checkstackaux(L,n,,) #define savestack(L,p) ((char *)(p) - (char *)L->stack) #define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) /* type of protected functions, to be ran by 'runprotected' */ typedef void(*Pfunc) (lua_State *L, void *ud); LUAI_FUNC int luaD_protectedparser(lua_State *L, ZIO *z, const char *name, const char *mode); LUAI_FUNC void luaD_hook(lua_State *L, int event, int line); LUAI_FUNC int luaD_precall(lua_State *L, StkId func, int nresults); LUAI_FUNC void luaD_call(lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_callnoyield(lua_State *L, StkId func, int nResults); LUAI_FUNC int luaD_pcall(lua_State *L, Pfunc func, void *u, ptrdiff_t oldtop, ptrdiff_t ef); LUAI_FUNC int luaD_poscall(lua_State *L, CallInfo *ci, StkId firstResult, int nres); LUAI_FUNC void luaD_reallocstack(lua_State *L, int newsize); LUAI_FUNC void luaD_growstack(lua_State *L, int n); LUAI_FUNC void luaD_shrinkstack(lua_State *L); LUAI_FUNC void luaD_inctop(lua_State *L); LUAI_FUNC l_noret luaD_throw(lua_State *L, int errcode); LUAI_FUNC int luaD_rawrunprotected(lua_State *L, Pfunc f, void *ud); } #endif
#include "StaticObjectCoinsView.h" #include "Core.h" void StaticObjectCoinsView::initView(StaticObjectModel* staticObjectModel) { m_staticObjectModel = staticObjectModel; //Obtain the atlas key looking up where the mesh is. Could be any mesh. m_atlasKey = Core::singleton().textureManager().findAtlas("ccoins"); addAnim("ccoins", Core::singleton().textureManager().getTextureAtlas(m_atlasKey)->mesh("ccoins")); setAnim("ccoins"); }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "12602" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int CASE; scanf("%d",&CASE); string str; int a,b; while( CASE-- ){ cin >> str; a = (str[0]-'A')*676 + (str[1]-'A')*26 + (str[2]-'A') ; b = (str[4]-'0')*1000 + (str[5]-'0')*100 + (str[6]-'0')*10 + (str[7]-'0') ; if( abs(a-b) <= 100 ) printf("nice\n"); else printf("not nice\n"); } return 0; }
#pragma once #include <cstdint> #include "..\object.hpp" #include "..\math.hpp" namespace leaves { namespace pipeline { class sampler : public object { public: enum class filter_mode : std::uint8_t { min_p_mag_p_mip_p, min_p_mag_p_mip_l, min_p_mag_l_mip_l, min_p_mag_l_mip_p, min_l_mag_p_mip_p, min_l_mag_p_mip_l, min_l_mag_l_mip_p, min_l_mag_l_mip_l, anisotropic, }; enum class filter_ext : std::uint8_t { none, comparison, minimum, maximum, }; enum class address_mode : std::uint8_t { wrap, mirror, clamp, border, mirror_once, }; enum class cmp_func : std::uint8_t { never, less, equal, less_equal, grater, not_equal, greater_equal, always, }; public: explicit sampler(string&& name) : object(object_type::sampler, std::move(name)) , filter(filter_mode::min_p_mag_p_mip_p) , address_u(address_mode::wrap) , address_v(address_mode::wrap) , address_w(address_mode::wrap) , mip_level_bias(0.0f) , min_mip_level(0.0f) , max_mip_level(0.0f) , border_color(0.0f, 0.0f, 0.0f, 0.0f) , comparison(cmp_func::never) , filter_extend(filter_ext::none) { } public: filter_mode filter; address_mode address_u; address_mode address_v; address_mode address_w; float mip_level_bias; float min_mip_level; float max_mip_level; float4 border_color; cmp_func comparison; filter_ext filter_extend; }; } }
#pragma once #include "Module/GraphicsManager.h" #include "OpenGL/OpenGLPipelineStateManager.h" #include "OpenGL/OpenGLFrameBuffer.h" #include "OpenGL/OpenGLVertexArray.h" #include "OpenGL/OpenGLVertexBuffer.h" #include "OpenGL/OpenGLIndexBuffer.h" #include "OpenGL/OpenGLUniformBuffer.h" #include "OpenGL/OpenGLShader.h" #include "OpenGL/OpenGLTexture.h" struct GLFWwindow; namespace Rocket { class OpenGLGraphicsManager : implements GraphicsManager { public: RUNTIME_MODULE_TYPE(OpenGLGraphicsManager); OpenGLGraphicsManager() = default; virtual ~OpenGLGraphicsManager() = default; virtual int Initialize() final; virtual void Finalize() final; virtual void Tick(Timestep ts) final; void Present() final; void SetPipelineState(const Ref<PipelineState>& pipelineState, const Frame& frame) final; void DrawBatch(const Frame& frame) final; void DrawFullScreenQuad() final; void BeginFrame(const Frame& frame) final; void EndFrame(const Frame& frame) final; void BeginFrameBuffer(const Frame& frame) final; void EndFrameBuffer(const Frame& frame) final; void SetPerFrameConstants(const DrawFrameContext& context) final; void SetLightInfo(const DrawFrameContext& context) final; void SetPerBatchConstants(const DrawBatchContext& context) final; void GenerateSkyBox() {} void GenerateBRDFLUT(int32_t dim) {} void BeginScene(const Scene& scene) final; void EndScene() final; // For Debug void DrawPoint(const Point3D& point, const Vector3f& color) final; void DrawPointSet(const Point3DSet& point_set, const Vector3f& color) final; void DrawPointSet(const Point3DSet& point_set, const Matrix4f& trans, const Vector3f& color) final; void DrawLine(const Point3D& from, const Point3D& to, const Vector3f &color) final; void DrawLine(const Point3DList& vertices, const Vector3f &color) final; void DrawLine(const Point3DList& vertices, const Matrix4f& trans, const Vector3f &color) final; void DrawTriangle(const Point3DList& vertices, const Vector3f &color) final; void DrawTriangle(const Point3DList& vertices, const Matrix4f& trans, const Vector3f &color) final; void DrawTriangleStrip(const Point3DList& vertices, const Vector3f &color) final; bool OnWindowResize(EventPtr& e) final; protected: void SwapBuffers(); bool Resize(int32_t width, int32_t height); private: GLFWwindow* m_WindowHandle = nullptr; bool m_VSync = true; int32_t m_Width; int32_t m_Height; struct OpenGLDrawBatchContext : public DrawBatchContext { Ref<OpenGLVertexArray> VAO; Vec<Ref<Texture2D>>* Textures; uint32_t Mode = 0; uint32_t Type = 0; uint32_t Count = 0; uint32_t MaxTextures = 0; }; struct DebugDrawBatchContext : public OpenGLDrawBatchContext { Vector3f Color; Matrix4f Trans; }; OpenGLDrawBatchContext m_DrawContext; OpenGLDrawBatchContext m_DebugContext; }; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const int move[4][2] = {1,0,-1,0,0,1,0,-1}; struct data { int x,y; }; data from,to; int vis[510][510],n,m,sum = 0; char G[510][510]; bool check(int x,int y) { if (x == to.x && y == to.y) return true; if (x < 1 || x > n || y < 1 || y > m) return false; if (G[x][y] != '.') return false; return true; } bool bfs() { queue<data> Q; data d = from; Q.push(d); while (!Q.empty()) { data s = Q.front();Q.pop(); //cout << s.x << " " << s.y << endl; for (int i = 0;i < 4; i++) { data t; t.x = s.x + move[i][0]; t.y = s.y + move[i][1]; //cout << t.x << " " << t.y << " " << G[t.x][t.y] << endl; if (check(t.x,t.y) && !vis[t.x][t.y]) { vis[t.x][t.y] = 1; if (t.x == to.x && t.y == to.y) return sum > 0; Q.push(t); //cout << t.x << " " << t.y << endl; } } } return false; } int main() { scanf("%d%d",&n,&m); //cout << n << " " << m << endl; for (int i = 1;i <= n; i++) { scanf("%*c"); for (int j = 1;j <= m; j++) scanf("%c",&G[i][j]); } scanf("%d%d",&from.x,&from.y); scanf("%d%d",&to.x,&to.y); if (G[to.x][to.y] == 'X') sum = 1; else { sum = -1; for (int i = 0;i < 4; i++) { if (G[to.x + move[i][0]][to.y + move[i][1]] == '.') sum++; if (to.x + move[i][0] == from.x && to.y + move[i][1] == from.y && G[from.x][from.y] == 'X') sum++; } } cout << sum << endl; if (bfs()) printf("YES\n"); else printf("NO\n"); return 0; }
#ifndef CRECT_H #define CRECT_H // system includes #include <vector> // project includes #include "CPoint.h" // external include #include "xmlParser.h" // global namespace declaration using namespace std; // forward declaration class CRect; class CRect : public CShape { public: CRect( const CPoint& inP1, const CPoint& inP2 ); ~CRect(); void SetExtremes( const CPoint& inP1, const CPoint& inP2 ); void GetExtremes( CPoint& outLT, CPoint& outRB ); void Shift( const CPoint& inPShift ); bool Intersect( const CRect& inRect ) const; bool Inside( const CPoint& inP ); bool Inside( const CRect& inRect ); CPoint GetLT() const { return mLT; }; CPoint GetRB() const { return mRB; }; double GetWidth() const { return mRB.GetX()- mLT.GetX() ;}; double GetHeight() const { return mRB.GetY()- mLT.GetY() ;}; CRect RClipping( const CRect& inRect ) const; void Draw() const; static CShape* CreateFromXml( XMLNode& inNode ); virtual void SaveXml ( XMLNode& inNode ); void MapPoints( const CRect& inDstRect, const vector< CPoint >& inVec, vector<CPoint>& outVec) const; private: CPoint mLT; CPoint mRB; }; #endif // CRECT_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2006-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_CERTIFICATE_H #define OP_CERTIFICATE_H /** @short Information about an X.509 certificate. * * This is an interface that was created to hold X.509 certificates from * an External SSL stack. In External SSL mode certificate instances * originating from connections to HTTPS servers are both retrieved * and destructed in External_SSL_Comm class. In this case the intended * life cycle of the certificate is like this: * * 1) Core makes a HTTPS connection to a server. * * 2) The server presents its certificate. Core retrieves the certificate * instance by calling OpSocket::ExtractCertificate(). After that Core * owns the certificate. * * 3) The certificate is presented to the user on loading if it [certificate] * can't be verified automatically or when the user invokes its display * via UI. * * 4) When the user leaves the site where the certificate belongs, it is * destructed by Core by calling the destructor. * * In this case certificate instances are created and destructed while Opera * is initialized. * * Alternatively, a certificate can be retrieved from certificate manager, * i.e. local certificate database. In this case certificates are owned * by the certificate manager. Please refer to @ref OpCertificateManager * documentation on the validity of the retrieved pointer to the certificate. * * There are plans to extend this interface beyond External SSL, so that * both Native and External SSL would share the same interface for certificates. * So far OpSSLListener::SSLCertificate is made inherited from this class, * but Native SSL still uses OpSSLListener::SSLCertificate everywhere. * */ class OpCertificate { public: /** Empty virtual destructor. */ virtual ~OpCertificate() {} /** @name Getters. * Pointed data is owned by the certificate instance. * Pointers are valid as long as the instance is not destructed. * @{ */ /** Get the short name of the certificate. */ virtual const uni_char* GetShortName() const = 0; /** Get the full name of the certificate. */ virtual const uni_char* GetFullName() const = 0; /** Get the issuer of the certificate. */ virtual const uni_char* GetIssuer() const = 0; /** Get start date/time of the certificate validity. */ virtual const uni_char* GetValidFrom() const = 0; /** Get end date/time of the certificate validity. */ virtual const uni_char* GetValidTo() const = 0; /** Get any extra data related to the certificate. * * This can include public keys, fingerprints, etc. */ virtual const uni_char* GetInfo() const = 0; /** used to uniquely identify the certificate */ virtual const char* GetCertificateHash(unsigned int &length) const = 0; /** @} */ }; #endif // OP_CERTIFICATE_H
#include <I2Y0A21.h> #include <LED.h> #include <TPC8407.h> I2Y0A21 ri(6, 0.05); I2Y0A21 li(1, 0.05); I2Y0A21 fi(0, 0.05); TPC8407 rmotor(2, 4, 3, 5,176); TPC8407 lmotor(7, 8, 6, 9,170); LED fled(16); LED lled(18); LED rled(17); LED bled(19); double distr, distl, distf; double pdistr, pdistl, pdistf; boolean right, left, front; int range = 35; void setup() { Serial.begin(9600); right = false; left = false; front = false; distr = ri.measure(); delay(20); distl = li.measure(); delay(20); distf = fi.measure(); pdistr = distr; pdistl = distl; pdistf = distf; } void led(int f, int r, int l, int b) { if (f == 1) { fled.on(); } else { fled.off(); } if (r == 1) { rled.on(); } else { rled.off(); } if (l == 1) { lled.on(); } else { lled.off(); } if (b == 1) { bled.on(); } else { bled.off(); } } void direct() { if (front) { if (right && left || !right && !left) { rmotor.back(200); lmotor.back(); led(0, 0, 0, 1); delay(10); } else if (right) { rmotor.forward(); lmotor.halt(); led(0, 0, 1, 0); delay(10); } else if (left) { rmotor.halt(); lmotor.forward(); led(0, 1, 0, 0); delay(10); } } else { if (right) { rmotor.forward(); lmotor.halt(); led(0, 0, 1, 0); delay(10); } else if (left) { rmotor.halt(); lmotor.forward(); led(0, 1, 0, 0); delay(10); } else { rmotor.forward(); lmotor.forward(); led(1, 0, 0, 0); Serial.println("HI"); delay(10); } } } void onpa() { delay(10); distr = ri.measure(); delay(10); distl = li.measure(); delay(10); distf = fi.measure(); right = distr <= range && pdistr <= range ? true : false; left = distl <= range && pdistl <= range ? true : false; front = distf <= range && pdistf <= range ? true : false; pdistr = distr; pdistl = distl; pdistf = distf; Serial.print(distr); Serial.print(","); Serial.print(distl); Serial.print(","); Serial.println(distf); } void loop() { onpa(); direct(); }
#pragma once #include <vector> #include "Object.hpp" class Entity : public Object { public: void setHealth(int h) { health = h; } void setMaxHealth(int h) { maxHealth = h; } int getHealth() { return health; } int getMaxHealth() { return maxHealth; } int createCycle(int row, int w, int h, int amount, int speed); void setCurAnimation(int c) { begin = 0; currAnimation = c; } void updateAnimation(); bool updateAnimationOnce(); int getCurAnimation() const { return currAnimation; } // private: int health, maxHealth; struct cycle { int row; int w; int h; int amount; int speed; int tick; }; int currAnimation; int begin; int newAnim; vector<cycle> animations; };
/** * Copyright (c) 2022, Timothy Stack * * All rights reserved. * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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. */ #include <map> #include "static_file_vtab.hh" #include <string.h> #include "base/auto_mem.hh" #include "base/fs_util.hh" #include "base/lnav_log.hh" #include "config.h" #include "ghc/filesystem.hpp" #include "lnav.hh" #include "vtab_module.hh" const char* const STATIC_FILE_CREATE_STMT = R"( -- Access static files in the lnav configuration directories CREATE TABLE lnav_static_files ( name TEXT PRIMARY KEY, filepath TEXT, content BLOB HIDDEN ); )"; struct static_file_vtab { sqlite3_vtab base; sqlite3* db; }; struct static_file_info { ghc::filesystem::path sfi_path; }; struct sf_vtab_cursor { sqlite3_vtab_cursor base; std::map<std::string, static_file_info>::iterator vc_files_iter; std::map<std::string, static_file_info> vc_files; }; static int sfvt_destructor(sqlite3_vtab* p_svt); static int sfvt_create(sqlite3* db, void* pAux, int argc, const char* const* argv, sqlite3_vtab** pp_vt, char** pzErr) { static_file_vtab* p_vt; /* Allocate the sqlite3_vtab/vtab structure itself */ p_vt = (static_file_vtab*) sqlite3_malloc(sizeof(*p_vt)); if (p_vt == nullptr) { return SQLITE_NOMEM; } memset(&p_vt->base, 0, sizeof(sqlite3_vtab)); p_vt->db = db; *pp_vt = &p_vt->base; int rc = sqlite3_declare_vtab(db, STATIC_FILE_CREATE_STMT); return rc; } static int sfvt_destructor(sqlite3_vtab* p_svt) { static_file_vtab* p_vt = (static_file_vtab*) p_svt; /* Free the SQLite structure */ sqlite3_free(p_vt); return SQLITE_OK; } static int sfvt_connect(sqlite3* db, void* p_aux, int argc, const char* const* argv, sqlite3_vtab** pp_vt, char** pzErr) { return sfvt_create(db, p_aux, argc, argv, pp_vt, pzErr); } static int sfvt_disconnect(sqlite3_vtab* pVtab) { return sfvt_destructor(pVtab); } static int sfvt_destroy(sqlite3_vtab* p_vt) { return sfvt_destructor(p_vt); } static int sfvt_next(sqlite3_vtab_cursor* cur); static void find_static_files(sf_vtab_cursor* p_cur, const ghc::filesystem::path& dir) { auto& file_map = p_cur->vc_files; std::error_code ec; for (const auto& format_dir_entry : ghc::filesystem::directory_iterator(dir, ec)) { if (!format_dir_entry.is_directory()) { continue; } auto format_static_files_dir = format_dir_entry.path() / "static-files"; log_debug("format static files: %s", format_static_files_dir.c_str()); for (const auto& static_file_entry : ghc::filesystem::recursive_directory_iterator( format_static_files_dir, ec)) { auto rel_path = ghc::filesystem::relative(static_file_entry.path(), format_static_files_dir); file_map[rel_path.string()] = {static_file_entry.path()}; } } } static int sfvt_open(sqlite3_vtab* p_svt, sqlite3_vtab_cursor** pp_cursor) { static_file_vtab* p_vt = (static_file_vtab*) p_svt; p_vt->base.zErrMsg = nullptr; sf_vtab_cursor* p_cur = (sf_vtab_cursor*) new sf_vtab_cursor(); if (p_cur == nullptr) { return SQLITE_NOMEM; } *pp_cursor = (sqlite3_vtab_cursor*) p_cur; p_cur->base.pVtab = p_svt; for (const auto& config_path : lnav_data.ld_config_paths) { auto formats_root = config_path / "formats"; log_debug("format root: %s", formats_root.c_str()); find_static_files(p_cur, formats_root); auto configs_root = config_path / "configs"; log_debug("configs root: %s", configs_root.c_str()); find_static_files(p_cur, configs_root); } return SQLITE_OK; } static int sfvt_close(sqlite3_vtab_cursor* cur) { sf_vtab_cursor* p_cur = (sf_vtab_cursor*) cur; p_cur->vc_files_iter = p_cur->vc_files.end(); /* Free cursor struct. */ delete p_cur; return SQLITE_OK; } static int sfvt_eof(sqlite3_vtab_cursor* cur) { sf_vtab_cursor* vc = (sf_vtab_cursor*) cur; return vc->vc_files_iter == vc->vc_files.end(); } static int sfvt_next(sqlite3_vtab_cursor* cur) { sf_vtab_cursor* vc = (sf_vtab_cursor*) cur; if (vc->vc_files_iter != vc->vc_files.end()) { ++vc->vc_files_iter; } return SQLITE_OK; } static int sfvt_column(sqlite3_vtab_cursor* cur, sqlite3_context* ctx, int col) { sf_vtab_cursor* vc = (sf_vtab_cursor*) cur; switch (col) { case 0: to_sqlite(ctx, vc->vc_files_iter->first); break; case 1: { sqlite3_result_text(ctx, vc->vc_files_iter->second.sfi_path.c_str(), -1, SQLITE_TRANSIENT); break; } case 2: { auto read_res = lnav::filesystem::read_file( vc->vc_files_iter->second.sfi_path); if (read_res.isErr()) { auto um = lnav::console::user_message::error( "unable to read static file") .with_reason(read_res.unwrapErr()); to_sqlite(ctx, um); } else { auto str = read_res.unwrap(); sqlite3_result_blob( ctx, str.c_str(), str.size(), SQLITE_TRANSIENT); } break; } } return SQLITE_OK; } static int sfvt_rowid(sqlite3_vtab_cursor* cur, sqlite_int64* p_rowid) { sf_vtab_cursor* p_cur = (sf_vtab_cursor*) cur; *p_rowid = std::distance(p_cur->vc_files.begin(), p_cur->vc_files_iter); return SQLITE_OK; } static int sfvt_best_index(sqlite3_vtab* tab, sqlite3_index_info* p_info) { return SQLITE_OK; } static int sfvt_filter(sqlite3_vtab_cursor* cur, int idxNum, const char* idxStr, int argc, sqlite3_value** argv) { sf_vtab_cursor* p_cur = (sf_vtab_cursor*) cur; p_cur->vc_files_iter = p_cur->vc_files.begin(); return SQLITE_OK; } static sqlite3_module static_file_vtab_module = { 0, /* iVersion */ sfvt_create, /* xCreate - create a vtable */ sfvt_connect, /* xConnect - associate a vtable with a connection */ sfvt_best_index, /* xBestIndex - best index */ sfvt_disconnect, /* xDisconnect - disassociate a vtable with a connection */ sfvt_destroy, /* xDestroy - destroy a vtable */ sfvt_open, /* xOpen - open a cursor */ sfvt_close, /* xClose - close a cursor */ sfvt_filter, /* xFilter - configure scan constraints */ sfvt_next, /* xNext - advance a cursor */ sfvt_eof, /* xEof - inidicate end of result set*/ sfvt_column, /* xColumn - read data */ sfvt_rowid, /* xRowid - read data */ nullptr, /* xUpdate - write data */ nullptr, /* xBegin - begin transaction */ nullptr, /* xSync - sync transaction */ nullptr, /* xCommit - commit transaction */ nullptr, /* xRollback - rollback transaction */ nullptr, /* xFindFunction - function overloading */ }; int register_static_file_vtab(sqlite3* db) { auto_mem<char, sqlite3_free> errmsg; int rc; rc = sqlite3_create_module( db, "lnav_static_file_vtab_impl", &static_file_vtab_module, nullptr); ensure(rc == SQLITE_OK); if ((rc = sqlite3_exec(db, "CREATE VIRTUAL TABLE lnav_static_files USING " "lnav_static_file_vtab_impl()", nullptr, nullptr, errmsg.out())) != SQLITE_OK) { fprintf(stderr, "unable to create lnav_static_file table %s\n", errmsg.in()); } return rc; }
#include "stdafx.h" #include "ImageManager.h" ImageManager::ImageManager() { } ImageManager::~ImageManager() { } void ImageManager::Release() { DeleteAll(); } Image * ImageManager::AddImage(string strKey, const char * fileName, float x, float y, int width, int height, bool isTrans, COLORREF transColor) { Image* img = FindImage(strKey); if (img) return img; img = new Image; if (FAILED(img->Init(fileName, x, y, width, height, isTrans, transColor))) { SAFE_DELETE(img); return NULL; } _mImageList[strKey] = img; return img; } Image * ImageManager::AddImage(string strKey, const char * fileName, float x, float y, int width, int height, int frameX, int frameY, bool isTrans, COLORREF transColor) { // 검색해서 이미 있으면 추가하지 않고 그냥 리턴 Image* img = FindImage(strKey); if (img) return img; // SUCCEEDED() 인자값은 true false -> true이면 true false이면 false 반환 // FAILED() 인자값 true or false -> true이면 false false이면 true 반환 // HRESULT 일 경우 사용 // S_OK E_FAILED, INVALID DATA(유효하지 않는 데이터) 이런것도 있음 img = new Image; // 실패하면 true고 성공하면 false if (FAILED( img->Init(fileName, x, y, width, height, frameX, frameY, isTrans, transColor))) { SAFE_DELETE(img); return NULL; } _mImageList[strKey] = img; return img; } Image * ImageManager::FindImage(string strKey) { // 코드 상으로는 이게 편하지만 // iterator로 찾으면 메모리 적으로는 좋음 count는 다 확인해야되니 if (_mImageList.count(strKey) < 1) return NULL; return _mImageList[strKey]; } bool ImageManager::DeleteImage(string strKey) { return false; } bool ImageManager::DeleteAll() { map<string, Image*>::iterator iter = _mImageList.begin(); for (; iter != _mImageList.end();) { if (iter->second != NULL) { iter->second->Release(); // IMAGE_INFO 내용 삭제 SAFE_DELETE(iter->second); // image* 삭제 iter = _mImageList.erase(iter); // map에서 삭제 } else { iter++; } } _mImageList.clear(); // 목록을 한번 더 확실하게 지우기 위해서 return true; } void ImageManager::FrameRender(string strKey, HDC hdc, int destX, int destY, int currentFrameX, int currentFrameY) { Image* img = FindImage(strKey); if (img) img->FrameRender(hdc, destX, destY, currentFrameX, currentFrameY); }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long long ll; using namespace std; int a[4444], nn; pair<ll, ll> calc(int x) { if (x + x + 1 <= nn) { pair<ll, ll> p1 = calc(x + x); pair<ll, ll> p2 = calc(x + x + 1); ll v = max(p1.second, p2.second); return {p1.first + p2.first + (v - p1.second) + (v - p2.second), v + a[x]}; } return {0, a[x]}; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int n; cin >> n; nn = ((1 << (n + 1)) - 1); for (int i = 2; i <= nn; ++i) { cin >> a[i]; } pair<ll, ll> ans = calc(1); cout << ans.first << endl; return 0; }
#include "struct.hpp" #include "parse.hpp" #include "other.hpp" #include "shading.hpp" using namespace std; using namespace Eigen; int main(int argc, char* argv[]) { if (argc != 5) { // commands are insufficient to run the program cerr << "incorrect command inputs" << endl; return 1; } // Storage for what is in the file vector<Object> copies; vector<Light> lights; Camera cam; Perspective per; string algorithm = argv[4]; string a = argv[2]; string b = argv[3]; int xres = stoi(a); int yres = stoi(b); // 1. : parse the files parse(argv[1], copies, lights, cam, per); // make the needed matrices for a transform cam.world_to_cam = inv_cam_trans(cam); per.projection = pers_proj(per); // make grid and buffer for z coordinates Vector3i *grid = new Vector3i[xres*yres]; float *buffer = new float[xres*yres]; // initialize all point in both grids to [0, 0, 0] or inf Vector3i co; co << 0, 0, 0; for (int i = 0; i < xres*yres; i++) { grid[i] = co; buffer[i] = -numeric_limits<float>::max(); } /* Objects in a weird order, cubes on top appear on the bottom. Checked if * the problem was with write order, not so */ for (int c = 0; c < copies.size(); c++) { Object obj = copies[c]; obj_trans(obj); // 2. and 3. : vertex and normal transformations // Storing vertex places in ndc and screen coor for (int p = 0; p < obj.v_trans.size(); p ++) { obj.v_trans[p].ndc = trans_world_ndc(obj.v_trans[p], cam, per); obj.v_trans[p].screen = ndc_screen(obj.v_trans[p].ndc, xres, yres); } // Then implement algorithm Gourad or Phong if (algorithm == "0") { gourad(obj, lights, cam, grid, buffer, xres, yres); } else { phong(obj, lights, cam, grid, buffer, xres, yres); } } display(grid, xres, yres); free(grid); free(buffer); return 0; }
// // Created by Omer on 22/01/2018. // #include "River.h" using namespace mtm; River::River(const std::string &name) : Area(name) {} River::~River() = default; static vector<GroupPointer>::iterator getStrongestGroup (vector<GroupPointer> &groups) { auto strongest_group = groups.begin(); for (auto i = groups.begin(); i != groups.end(); i++) { if (*i > *strongest_group) strongest_group = i; } return strongest_group; } static bool tradeWithStrongestGroup(vector<GroupPointer> groups, map<string, Clan> &clan_map, const string &clan_name, const GroupPointer &new_group) { while (!groups.empty()) { auto strongest_group = getStrongestGroup(groups); const Clan &strongest_group_clan = clan_map.at((*strongest_group)->getClan()); if ((*strongest_group)->getClan() == clan_name || strongest_group_clan.isFriend(clan_map.at(clan_name))) { if ((*strongest_group)->trade(*new_group)) return true; } groups.erase(strongest_group); } return false; } static void checkGroupsArriveExceptions(const string &group_name, const string &clan_name, const map<string, Clan> &clan_map, const vector<GroupPointer> &groups) { auto clan_it = clan_map.find(clan_name); if (clan_it == clan_map.end()) { throw AreaClanNotFoundInMap(); } if (!clan_it->second.doesContain(group_name)) { throw AreaGroupNotInClan(); } GroupPointer group_ptr = clan_it->second.getGroup(group_name); for (auto i = groups.begin(); i != groups.end(); i++) { if (*i == group_ptr) throw AreaGroupAlreadyIn(); } } void River::groupArrive(const string &group_name, const string &clan_name, map<string, Clan> &clan_map) { checkGroupsArriveExceptions(group_name, clan_name, clan_map, groups); Clan &clan = clan_map.at(clan_name); const GroupPointer &new_group_ptr = clan.getGroup(group_name); tradeWithStrongestGroup(groups, clan_map, clan_name, new_group_ptr); groups.push_back(new_group_ptr); }
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <iostream> #include <string.h> using namespace std; #define INV_NUM 15 //Number of inventory slots void header (char*); class players { char name[32]; int att, def, mgk, mdef; int health, max_health; int mana, max_mana; public: // players(); void set_name(); // void choose_class(int); // void reset_stats; }; void players::set_name() { printf("Enter your hero's name: "); //getline(cin, name, '\n'); scanf("%s", name); printf("\nHero's name is %s.\n", name); //cout << "\nHero's name is " << name << "." << endl; } class Item { public: char name[32]; int stock, MAX_stock, id; bool consum, equip, key; //remember to uncomment this public, get rid of the upper one, and make functions to return all the indivdual item values // public: Item(); Item(char*, int, int, int, bool, bool, bool); void set (char*, int, int, int, bool, bool, bool); void Use(); }; Item::Item() { sprintf(name, "%s", "NULL"); stock = 0;MAX_stock = 0;id = -1; consum = false;equip = false;key=false; } /*Item::Item (string NA, int ST, int M_ST, int ID, bool CON, bool EQP, bool KEY) { name = NA;stock = ST;MAX_stock = M_ST;id = ID; consum = CON;equip = EQP;key=KEY; } */ void Item::set (char* NA, int ST, int M_ST, int ID, bool CON, bool EQP, bool KEY) { sprintf(name, "%s", NA); stock = ST;MAX_stock = M_ST;id = ID; consum = CON;equip = EQP;key=KEY; } void Item::Use() { if (id == -1) printf("CANNOT USE\n"); else { stock = stock - 1; if (stock < 0) { stock = 0; printf("Out of %s, cannot use.\n", name); } } } /*class Shop { int num_inv; Item shop_inv[num_inv]; int cost[num_inv]; };*/ class Game_sys { bool Game_win; Item Inventory[INV_NUM]; int gold; bool Quest_Prog[10]; public: Game_sys (); Game_sys (bool); int Win_Cond(); bool gold_compare (int); void gold_add (int); void gold_sub (int); void gold_disp(); void inv_add(Item,int); void inv_disp(); void inv_man(); void inv_disc(); void Quest_Prog_disp(); }; Game_sys::Game_sys() { Game_win = false; // for (int i=0;i<INV_NUM;i++) // Inventory[i]; gold = 300; //Will probably end up changing later, or may be arbitray at start and be reinitilzed upon new or load game for (int j=0;j<10;j++) Quest_Prog[j]=false; } Game_sys::Game_sys (bool a) { Game_win = a; } int Game_sys::Win_Cond() { return Game_win; } bool Game_sys::gold_compare (int cost) { bool afford; if (cost > gold) afford = false; else afford = true; return afford; } void Game_sys::gold_add (int gold_get) { gold = gold + gold_get; printf("You now have %d gold\n", gold); } void Game_sys::gold_sub (int cost) { gold = gold - cost; if (gold < 0) { gold = 0; printf("You're totally out of money brah. This really shouldn't happen, this is an error i guess\n"); } printf("You have %d gold left\n", gold); } void Game_sys::gold_disp() { printf("You have %d gold\n",gold); } void Game_sys::inv_add(Item thing, int amt) { bool loop = true, GET=true; if (loop == true) { for (int i=0; i<INV_NUM; i++) { if (Inventory[i].id == thing.id) { Inventory[i].stock = Inventory[i].stock + (amt*thing.stock); loop = false; printf("Aquired %d %s.\n", (amt * thing.stock), thing.name); // cout << "Aquired " << (amt * thing.stock) << " " << thing.name << "." << endl; if (Inventory[i].stock > Inventory[i].MAX_stock) { Inventory[i].stock = Inventory[i].MAX_stock; printf("You have reached the maximum number of %s.\n", Inventory[i].name); // cout << "You have reached the maximum number of " << Inventory[i].name << "." <<endl; } printf("Current %s stock is %d.\n", Inventory[i].name, Inventory[i].stock); // cout << "Current " << Inventory[i].name << " stock is " << Inventory[i].stock << "." << endl; } } } if (loop == true) { for (int i=0; i<INV_NUM; i++) { if ((Inventory[i].id == -1)&&(GET == true)) { Inventory[i] = thing; Inventory[i].stock = (thing.stock * amt); GET = false; loop = false; printf("Aquired %d %s.\n", (amt * thing.stock), thing.name); // cout << "Aquired " << (amt * thing.stock) << " " << thing.name << "." << endl; printf("Current %s stock is %d.\n", Inventory[i].name, Inventory[i].stock); // cout << "Current " << Inventory[i].name << " stock is " << Inventory[i].stock << "." << endl; } } } if (loop == true) { // cout << "No more inventory space. " << thing.name << "was discarded." << endl; printf("No more inventory space. %s was discarded\n", thing.name); } } void Game_sys::inv_disp() { header("Inventory"); for (int i=0; i<INV_NUM; i++) // cout << i+1 << ". " << Inventory[i].name << " x" << Inventory[i].stock << endl; printf("%-2.2d. %-20s x%d\n", i+1, Inventory[i].name, Inventory[i].stock); } void Game_sys::inv_man() { Item temp; header("Invetory Managament"); int confirm_sel; printf("Swap items?\n1. Yes\n2. No\n"); scanf("%d", &confirm_sel); switch (confirm_sel) { case 1: { inv_disp(); int swap1_sel; int swap2_sel; printf("You will pick two items in inventory to have their places swapped\n"); printf("Select 1st item: "); scanf("%d", &swap1_sel); swap1_sel = swap1_sel - 1; printf("Select 2nd item: "); scanf("%d", &swap2_sel); swap2_sel = swap2_sel - 1; int swap_confirm; cout << "Swap " << Inventory[swap1_sel].name << " with " << Inventory[swap2_sel].name << "?\n1. Yes\n2. No" << endl; scanf("%d", &swap_confirm); switch (swap_confirm) { case 1: { //cout << "Swapping " << Inventory[swap1_sel].name << " with " << Inventory[swap2_sel].name << "..." << endl; printf("Swapping %s with %s...\n", Inventory[swap1_sel].name, Inventory[swap2_sel].name); temp = Inventory[swap1_sel]; Inventory[swap1_sel] = Inventory[swap2_sel]; Inventory[swap2_sel] = temp; break; } case 2: { printf("Cancelling action...\n"); break; } } break; } case 2: { printf("Exiting Inventory Management...\n"); break; } } } void Game_sys::inv_disc() { Item discard; header("Discard Item"); int confirm_sel; printf("Do you want to discard an item?\n1. Yes\n2. No\n"); scanf("%d", &confirm_sel); switch (confirm_sel) { case 1: { inv_disp(); int disc_sel; //int swap2_sel; printf("Select the item you wish to discard: "); //printf("Select 1st item: "); scanf("%d", &disc_sel); disc_sel = disc_sel - 1; //printf("Select 2nd item: "); //scanf("%d", &swap2_sel); //swap2_sel = swap2_sel - 1; int disc_confirm; //cout << "This will discard all of the " << Inventory[disc_sel].name << " that you have in your inventroy. Is this ok?\n1. Yes\n2. No" << endl; printf("This will discard all of the %s that ypu have in your inventroy. Is this ok?\n1. Yes\n2. No\n", Inventory[disc_sel].name); scanf("%d", &disc_confirm); switch (disc_confirm) { case 1: { //cout << "Discarding " << Inventory[disc_sel].name << " from inventroy..." << endl; printf("Discarding %s from inventory...\n", Inventory[disc_sel].name); //temp = Inventory[swap1_sel]; Inventory[disc_sel] = discard; //Inventory[swap2_sel] = temp; break; } case 2: { printf("Cancelling action...\n"); break; } } break; } case 2: { printf("Exiting Inventory Management...\n"); break; } } } void Game_sys::Quest_Prog_disp() { header("Quest Progress"); for (int i=0; i<10; i++) { printf("%d. Quest %d status: ",i+1,i+1); if (Quest_Prog[i]) printf("Quest Completed\n"); else if (Quest_Prog[i] == false) printf("Uncomplete\n"); } } void header (char* title) { printf("%s\n", title); printf("----------------------------\n"); } Game_sys RPG_GO; // ---------------------This probably shouldn't be here--------------------- void Wep_Shop() { Item wep_shop[3]; /*sets what the shop has in it's inventory, in this case 3 items -(1)Sets the name of the item, (2)the stock that you would get upon buying one, (3)the maximum stock that can be held, (4)the ID number for that item, (5)determines if the item is a consumable, (6) determines if item can be equipped, (7)determines if the item is a key item. -Ex: wep_shop[NUM].set("name", stock, max_stock, ID, consumable, equip, key); */ wep_shop[0].set("Assy Sword", 1, 99, 6, false, true, false); wep_shop[1].set("Ok Sword", 1, 99, 7, false, true, false); wep_shop[2].set("Brotabulus Sword", 1, 99, 8, false, true, false); //Seperate array for the costs of each item, at this particualar shop int cost[3]; cost[0]=50; cost[1]=80; cost[2]=150; bool shopping=true; while (shopping == true) { RPG_GO.inv_disp(); header("Weapons Shop"); for (int i=0;i<3;i++) //cout << i+1 << "." << wep_shop[i].name << " COST: " << cost[i] << endl; printf("%-2.2d. %-20s COST: %d\n", i+1, wep_shop[i].name, cost[i]); printf("\n"); RPG_GO.gold_disp(); //Displays your current gold amount printf("What do you want to buy?\n"); int sel; scanf("%d", &sel);// If you type a number (< 1) or (> 15), throw error and send back to selection sel = sel - 1; //cout << "How many " << wep_shop[sel].name <<"s?"<< endl; printf("How many %ss?\n", wep_shop[sel].name); int amount; scanf("%d", &amount); //cout << "You are buying " <<amount<< " " <<wep_shop[sel].name<< ". Total is " <<amount*cost[sel]<<"g. Is this ok?" << endl; printf("You are buying %d %s. Total is %dg. Is this ok?\n", amount, wep_shop[sel].name, amount*cost[sel]); int confirm; printf("1. Yes\n2. No\n"); scanf("%d", &confirm); switch (confirm) { case 1: { if (RPG_GO.gold_compare(amount*cost[sel])) { //call functions to put items you bought in inventory, and subtract total from gold supply //maybe could return a bool that tells you if you reached inventory limit RPG_GO.inv_add(wep_shop[sel], amount); RPG_GO.gold_sub(amount*cost[sel]); } else printf("You do not have enough gold to make this purchase\n"); break; } case 2: { printf("Cancelling transaction...\n"); break; } } int exit; printf("Keep shopping?\n1. Yes\n2. No\n"); scanf("%d", &exit); switch (exit) { case 1: { printf("Ok, take your time\n"); break; } case 2: { printf("Thank you, come again soon\n"); shopping = false; break; } } } } int main() { //Declare the Game class // Game_sys RPG_GO; Remember to uncomment this, temporarily moving to line 102 //Title printf("-------RPG GO!!!-------\n\n\n"); //Intro stuff: class and player stats and name and junk players player[2]; int game_sel; bool new_load = true; while (new_load == true) { printf("1. New Game\n2. Load Game\n"); scanf("%d", &game_sel); switch (game_sel) { case 1: { //Reset and Initialize player data bool class_choose = true; while (class_choose == true) { printf("Name your hero:\n"); player[0].set_name(); int class_sel; printf("Choose your class:\n"); printf("1. Warrior - Has higher attack, but lacks defense and magic stats\n"); printf("2. Defender - Has higher defense, but lacks attack and magic stats\n"); printf("3. Mage - Has higher magic abilites, but lacks attack and defense stats\n"); scanf("%d", &class_sel); switch (class_sel) { case 1: //Sets base player stats to the warrior's printf("You have chosen the warrior class\n"); break; case 2: //Sets base player stats to the warrior's printf("You have chosen the defender class\n"); break; case 3: //Sets base player stats to the warrior's printf("You have chosen the mage class\n"); break; } //Print out player data for confirmation, ask if the information is correct header("Is player information correct?"); printf("1. Yes\n2. No\n"); int confirm; scanf("%d", &confirm); if (confirm == 1) class_choose = false; } new_load = false; break; } case 2: { bool load_success = false; //Loads player and game data, if load is unsuccessful, throw error and do not exit loop printf("Loading game...\n"); if (load_success == true) new_load = false; else if (load_success == false) printf("Load was unsuccessful\n"); break; } } } //main gameloop //may want to move game_running boolean to Game_sys class. If not you might have to pass it into any battle functions that the player could lose. bool game_running = true; while (game_running == true) { //Hub town int hub_sel; header("Main Hub"); printf("1. Free Exploration\n2. Item/Weapon Shop\n3. Quest Hall\n"); printf("4. Inn\n5. Death Dungeon\n6. Open Menu\n"); scanf("%d", &hub_sel); switch (hub_sel) { case 1: /*Return to already explored areas: Search for loot and fight monster for exp*/ //Area and battle classes work together to do stuff /*calls function that displays what areas are available -gets info from the areas class -if an area has already been traveled to, it should be available */ printf("Phasers are now in the 'fun' position\n"); break; case 2: { //Enter to do shopping and junk bool shop_enter = true; while (shop_enter == true) { int shop_sel; header("Weapon/Item Shop"); printf("1. Buy Weapons/Armor\n2. Buy Items\n"); printf("3. Exit Shop\n"); scanf("%d", &shop_sel); switch (shop_sel) { case 1: //Buy Weapons or Armor printf("What weapons you want?\n"); Wep_Shop(); break; case 2: //Buy items printf("What items you want?\n"); break; case 3: //Exits the shop printf("Thank you for coming to the shop.\n"); shop_enter = false; break; } } break; } // break; case 3: { //Enter to take on new quests bool qHall_enter = true; while (qHall_enter == true) { int qHall_sel; header("Quest Hall"); printf("1. Do things\n2. Exit Hall\n"); scanf("%d", &qHall_sel); switch (qHall_sel) { case 1: /* View which quests are available, check quest requirements, accept and go on quests */ printf("What quests you want\n"); break; case 2: //Exits the hall printf("Leaving so soon?\n"); qHall_enter = false; break; } } break; } // break; case 4: { bool inn_enter = true; while (inn_enter == true) { int inn_sel; header("Inn"); printf("1. Stay the night\n2. Exit\n"); scanf("%d", &inn_sel); switch (inn_sel) { case 1: //Restores health and mana back to full //Costs a certain gold fee //Have a confirmation option so, you don't accidentally spent gold printf("Health and mana have been restored\n"); break; case 2: //Exits the inn printf("Why you no wanna to stay at my inn?! We have'a the sheets made from the goblin hide, is very nice.\n"); inn_enter = false; break; } } break; } // break; case 5: { /*Final dungeon of game: -Opens up after the required main quests have been completed -Completing will take game out of main loop, and take you to win screen -Losing will just result in gameover, exit main loop */ printf("Entering death dungeon. You best have prepared youself son.\n"); break; } // break; case 6: { //Opens the game menu, can check quest progess, look at player stats, manage equipment, and save the game from this menu header("Game Menu"); bool menu_open = true; while (menu_open == true) { int menu_sel; printf("1. View Inventory\n2. Check Quest Progress\n3. Manage Inventory\n4. Discard Item\n5. Close menu\n"); scanf("%d", &menu_sel); switch (menu_sel) { case 1: { //Different cases call functions to do the things you mentioned eariler RPG_GO.inv_disp(); break; } case 2: { RPG_GO.Quest_Prog_disp(); break; } case 3: { RPG_GO.inv_man(); break; } case 4: { RPG_GO.inv_disc(); break; } case 5: { menu_open = false; printf("Closing menu\n"); break; } } } } } } if (RPG_GO.Win_Cond() == true) { //Victory Stuff, game complete printf("You won the game and junk\n"); } else if(RPG_GO.Win_Cond() == false) { //Game over printf("Game over, you lose. Try again chump and/or chumpette.\n"); } return 0; }
#include <afx.h> #include <fstream> #include <string> #include <sstream> #include "traderspi.h" #include "mdspi.h" #include "windows.h" #pragma warning(disable : 4996) extern int requestId; extern HANDLE g_hEvent; extern Strategy* g_strategy; void CtpMdSpi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { IsErrorRspInfo(pRspInfo); } void CtpMdSpi::OnFrontDisconnected(int nReason) { cerr<<" 响应 | 连接中断..." << " reason=" << nReason << endl; } void CtpMdSpi::OnHeartBeatWarning(int nTimeLapse) { cerr<<" 响应 | 心跳超时警告..." << " TimerLapse = " << nTimeLapse << endl; } void CtpMdSpi::OnFrontConnected() { cerr<<"MD 连接交易前置OnFrontConnected()...成功"<<endl; //登录期货账号 ReqUserLogin(m_appId, m_userId, m_passwd); SetEvent(g_hEvent); } void CtpMdSpi::ReqUserLogin(TThostFtdcBrokerIDType appId, TThostFtdcUserIDType userId, TThostFtdcPasswordType passwd) { CThostFtdcReqUserLoginField req; memset(&req, 0, sizeof(req)); strcpy(req.BrokerID, appId); strcpy(req.UserID, userId); strcpy(req.Password, passwd); int ret = m_pUserApi_md->ReqUserLogin(&req, ++requestId); cerr<<"MD 请求 | 发送登录..."<<((ret == 0) ? "成功" :"失败") << endl; SetEvent(g_hEvent); } void CtpMdSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if (!IsErrorRspInfo(pRspInfo) && pRspUserLogin) { cerr<<"行情模块登录成功"<<endl; //cerr<<"---"<<"错误代码为0表示成功:"<<pRspInfo->ErrorID<<",错误信息:"<<pRspInfo->ErrorMsg<<endl; //SubscribeMarketData_all();//订阅全市场行情 SubscribeMarketData(m_instId);//订阅交易合约的行情 //订阅持仓合约的行情 if(m_charNewIdList_holding_md) { cerr<<"m_charNewIdList_holding_md大小:"<<strlen(m_charNewIdList_holding_md)<<","<<m_charNewIdList_holding_md<<endl; cerr<<"有持仓,订阅行情:"<<endl; SubscribeMarketData(m_charNewIdList_holding_md);//流控为6笔/秒,如果没有持仓,就不要订阅 delete []m_charNewIdList_holding_md;//订阅完成,释放内存 } else cerr<<"当前没有持仓"<<endl; //策略启动后默认禁止开仓是个好的风控习惯 cerr<<endl<<endl<<endl<<"策略默认禁止开仓,如需允许交易,请输入指令(允许开仓:yxkc, 禁止开仓:jzkc):"<<endl; } if(bIsLast) SetEvent(g_hEvent); } void CtpMdSpi::SubscribeMarketData(char* instIdList) { vector<char*> list; char *token = strtok(instIdList, ","); while( token != NULL ){ list.push_back(token); token = strtok(NULL, ","); } unsigned int len = list.size(); char** pInstId = new char* [len]; for(unsigned int i=0; i<len;i++) pInstId[i]=list[i]; int ret=m_pUserApi_md->SubscribeMarketData(pInstId, len); cerr<<" 请求 | 发送行情订阅... "<<((ret == 0) ? "成功" : "失败")<< endl; SetEvent(g_hEvent); } //订阅全市场行情 void CtpMdSpi::SubscribeMarketData_all() { SubscribeMarketData(m_charNewIdList_all); delete []m_charNewIdList_all; } void CtpMdSpi::OnRspSubMarketData( CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { cerr<<" 响应 | 行情订阅...成功"<<endl; if(bIsLast) SetEvent(g_hEvent); } void CtpMdSpi::OnRspUnSubMarketData( CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { cerr<<" 响应 | 行情取消订阅...成功"<<endl; if(bIsLast) SetEvent(g_hEvent); } void CtpMdSpi::OnRtnDepthMarketData( CThostFtdcDepthMarketDataField *pDepthMarketData) { g_strategy->OnTickData(pDepthMarketData); } bool CtpMdSpi::IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo) { bool ret = ((pRspInfo) && (pRspInfo->ErrorID != 0)); if (ret){ cerr<<" 响应 | "<<pRspInfo->ErrorMsg<<endl; } return ret; } void CtpMdSpi::setAccount(TThostFtdcBrokerIDType appId1, TThostFtdcUserIDType userId1, TThostFtdcPasswordType passwd1) { strcpy(m_appId, appId1); strcpy(m_userId, userId1); strcpy(m_passwd, passwd1); } //设置交易的合约代码 void CtpMdSpi::setInstId(string instId) { strcpy(m_instId, instId.c_str()); } void CtpMdSpi::setInstIdList_holding_md(string instId) { //strcpy(m_instIdList_holding_md, instId.c_str()); int sizeInstId = instId.size(); m_charNewIdList_holding_md = new char[sizeInstId+1]; memset(m_charNewIdList_holding_md,0,sizeof(char)*(sizeInstId+1)); strcpy(m_charNewIdList_holding_md, instId.c_str()); /*strcpy(m_instIdList_all, instIdList_all.c_str());*/ cerr<<"有持仓的合约:"<<strlen(m_charNewIdList_holding_md)<<","<<sizeof(m_charNewIdList_holding_md)<<","<<_msize(m_charNewIdList_holding_md)<<endl<<m_charNewIdList_holding_md<<endl; } //保存全市场合约,在TD进行 void CtpMdSpi::set_instIdList_all(string instIdList_all) { int sizeIdList_all = instIdList_all.size(); m_charNewIdList_all = new char[sizeIdList_all+1]; memset(m_charNewIdList_all,0,sizeof(char)*(sizeIdList_all+1)); strcpy(m_charNewIdList_all, instIdList_all.c_str()); /*strcpy(m_instIdList_all, instIdList_all.c_str());*/ if(!m_charNewIdList_all)//用strlen时m_charNewIdList_all不能为空 cerr<<"收到的全市场合约:"<<strlen(m_charNewIdList_all)<<","<<sizeof(m_charNewIdList_all)<<","<<_msize(m_charNewIdList_all)<<endl<<m_charNewIdList_all<<endl; }
/** * Revised on Jan 7, 2018. * @author: Zijie Jiang * Changes: Added comments * */ #include"Chamber.h" #include"Floor.h" #include<iostream> Chamber::Chamber(int x, int y, int length, int width, int chamberIndex) :Entity(x, y, '.', "Chamber") { this->length = length; this->width = width; this->hasPlayer = false; this->hasStairs = false; this->initXBoundaries(chamberIndex); } Chamber::~Chamber() { characterList.clear(); potionList.clear(); treasureList.clear(); } void Chamber::initXBoundaries(int chamberIndex) { switch (chamberIndex) { case 0: case 2: case 3: for (int i = 0; i < this->getLength(); i++) { for (int j = 0; j < this->getWidth(); j++) { xBoundaries[this->getY() + i] = std::make_pair(this->getX(), this->getX() + this->getWidth()); } } break; case 1: xBoundaries[3] = std::make_pair(39, 61); xBoundaries[4] = std::make_pair(39, 61); xBoundaries[5] = std::make_pair(39, 69); xBoundaries[6] = std::make_pair(39, 72); for (int i = 7; i <= 12; i++) { xBoundaries[i] = std::make_pair(61, 75); } break; case 4: for (int i = 16; i <= 18; i++) { xBoundaries[i] = std::make_pair(65, 75); } for (int i = 19; i <= 22; i++) { xBoundaries[i] = std::make_pair(37, 75); } } } void Chamber::initChamber() { this->characterList.clear(); this->potionList.clear(); this->treasureList.clear(); this->hasPlayer = false; this->hasStairs = false; } void Chamber::updateCharacterList() { std::vector<Character*>::iterator it = this->characterList.begin(); while (it != characterList.end()) { //Update Character, only if the flag Floor::stopwander is false if (!Floor::getInstance()->getPlayer()->getStopWander()) { (*it)->update(); } //如果it指向的Character死了,则把Character从list中删去 if ((*it)->getIsDead()) { int lastX = (*it)->getX(); int lastY = (*it)->getY(); //Assign appropriate potions and treasures to the last coordinate of the dead enemy if ((*it)->getType() == "GridBug") { int num = rand() % 6; switch (num) { case 0:addPotion(new RestoreHealthPotion(lastX, lastY)); break; case 1:addPotion(new BoostAtkPotion(lastX, lastY)); break; case 2:addPotion(new BoostDefPotion(lastX, lastY)); break; case 3:addPotion(new PoisonHealthPotion(lastX, lastY)); break; case 4:addPotion(new WoundAtkPotion(lastX, lastY)); break; case 5:addPotion(new WoundDefPotion(lastX, lastY)); break; } //Update enemy display:char to potion display:char Floor::getInstance()->getMap()[lastY][lastX] = '!'; } else if ((*it)->getType() == "Goblin" || (*it)->getType() == "Merchant" || (*it)->getType() == "Dragon") { //Update enemy display:char to treasure display:char Floor::getInstance()->getMap()[lastY][lastX] = '$'; addTreasure(new GoldPile(lastX, lastY)); } //If the enemy does not produce neither potion nor treasure, replace it with a '.' default board character else { Floor::getInstance()->getMap()[lastY][lastX] = '.'; } delete *it; it = characterList.erase(it); } else { ++it; } } } void Chamber::updatePotionList() { //Same as updateCharacterList std::vector<Potion*>::iterator it = this->potionList.begin(); while (it != potionList.end()) { if ((*it)->getIsUsed()) { //Restore map to '.' from '!' since potion is used. Floor::getInstance()->getMap()[(*it)->getY()][(*it)->getX()] = '.'; it = potionList.erase(it); } else { ++it; } } } void Chamber::updateTreasureList() { //Same as updateCharacterList std::vector<Treasure*>::iterator it = this->treasureList.begin(); while (it != treasureList.end()) { if ((*it)->getIsUsed()) { //Restore map to '.' from '$' since treasure is used. Floor::getInstance()->getMap()[(*it)->getY()][(*it)->getX()] = '.'; it = treasureList.erase(it); } else { ++it; } } } void Chamber::addCharacter(Character *c) { this->characterList.push_back(c); Floor::getInstance()->getMap()[c->getY()][c->getX()] = c->getDisplay(); } void Chamber::addPotion(Potion *p) { this->potionList.push_back(p); Floor::getInstance()->getMap()[p->getY()][p->getX()] = p->getDisplay(); } void Chamber::addTreasure(Treasure *t) { this->treasureList.push_back(t); Floor::getInstance()->getMap()[t->getY()][t->getX()] = t->getDisplay(); } bool Chamber::isInChamber(int x, int y) { return this->xBoundaries[y].first < x&&x < this->xBoundaries.at(y).second; } int Chamber::getLength() { return this->length; } int Chamber::getWidth() { return this->width; } bool Chamber::getHasPlayer() { return this->hasPlayer; } bool Chamber::getHasStairs() { return this->hasStairs; } void Chamber::setHasPlayer(bool hasPlayer) { this->hasPlayer = hasPlayer; } void Chamber::setHasStairs(bool hasStairs) { this->hasStairs = hasStairs; } Character* Chamber::getCharacter(int x, int y) { for (Character *c : this->characterList) { if (c->getY() == y&&c->getX() == x) { return c; } } return nullptr; } Potion* Chamber::getPotion(int x, int y) { for (Potion *p : this->potionList) { if (p->getY() == y&&p->getX() == x) { return p; } } return nullptr; } Treasure* Chamber::getTreasure(int x, int y) { for (Treasure *t : this->treasureList) { if (t->getY() == y&&t->getX() == x) { return t; } } return nullptr; } void Chamber::updateChamber() { this->updateCharacterList(); this->updatePotionList(); this->updateTreasureList(); }
#include <iostream> #include <limits> using namespace std; //creates variable choice for user int Choice; int main() { do { //prompts the user to choose a beverage cout << "Please choose a number 1 through 5" << endl << "1 for Mountain Dew, 2 for Coca Cola, 3 for Lemonade, 4 for Dr. Pepper, and 5 for Water\n"; //sets choice to a value chosen by user cin >> Choice; //switch that takes in the variable choice and gives response based on the case switch (Choice) { case 1: cout << "Here is your Mountain Dew\n"; break; case 2: cout << "Here is your Coke\n"; break; case 3: cout << "Here is your Lemonade\n"; break; case 4: cout << "Here is your Dr. Pepper\n"; break; case 5: cout << "Here is your Water\n"; break; //a default case that is used if no other case matches the switch default: cout << "Error, Sorry that choice was not valid, Here is your money back "; break; } } //makes sure the switch is only used if the choice fits the requirements while (Choice < 1 || Choice>5); system("PAUSE"); return 0; }
#ifndef __MEDIA_PARSER_HH__ #define __MEDIA_PARSER_HH__ class CMediaParser { public: static CMediaParser* CreateNew(); protected: CMediaParser(); ~CMediaParser(); public: int getFrameWidth() { return mVideoFrameWidth; } long getDurationMs() { return mVideoDuration / 1000 ; } float getVideoFrameRate(){ // fps return mVideoFrameRate ; } int getFrameHeight() { return mVideoFrameHeight; } int getAudioChannels() { return mAudioChannels; } int getAudioSamplingRate() { return mAudioSamplingRate; } void prepare(); void start(); void pause(); void start(); void stop(); void setState(int state); void getState(int state); private: int mAudioSamplingRate; int mAudioChannels; int mVideoFrameHeight; int mVideoFrameWidth; long mVideoDuration; float mVideoFrameRate; }; #endif
#include "endgame.h" #include "ui_endgame.h" endgame::endgame(QWidget *parent) : QDialog(parent), ui(new Ui::endgame) { ui->setupUi(this); } void endgame::setState(int black, int white){ if(black > white){ char txt[100]; snprintf(txt, sizeof(txt), "Black won with score %d/%d", black, white); ui->label_2->setText(txt); } else if(white > black){ char txt[100]; snprintf(txt, sizeof(txt), "White won with score %d/%d", white, black); ui->label_2->setText(txt); } else { ui->label_2->setText("Draw"); } update(); } endgame::~endgame() { delete ui; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/style/css_gradient.h" #ifdef CSS_GRADIENT_SUPPORT #include "modules/logdoc/htm_lex.h" #include "modules/util/tempbuf.h" #include "modules/style/css.h" #include "modules/display/vis_dev.h" #include "modules/libvega/src/oppainter/vegaoppainter.h" #include "modules/layout/layoutprops.h" CSSValueType CSS_Gradient::GetCSSValueType() const { if (GetType() == LINEAR) { if (repeat) return CSS_FUNCTION_REPEATING_LINEAR_GRADIENT; else { if (webkit_prefix) return CSS_FUNCTION_WEBKIT_LINEAR_GRADIENT; else if (o_prefix) return CSS_FUNCTION_O_LINEAR_GRADIENT; else return CSS_FUNCTION_LINEAR_GRADIENT; } } else { if (repeat) return CSS_FUNCTION_REPEATING_RADIAL_GRADIENT; else return CSS_FUNCTION_RADIAL_GRADIENT; } } // Copying OP_STATUS CSS_Gradient::CopyTo(CSS_Gradient& copy) const { if (this != &copy) { copy.repeat = repeat; copy.webkit_prefix = webkit_prefix; copy.o_prefix = o_prefix; return copy.CopyStops(stops, stop_count); } // Copy to self is weird but not an error. return OpStatus::OK; } OP_STATUS CSS_LinearGradient::CopyToLinear(CSS_LinearGradient& copy) const { if (this != &copy) { copy.line = line; return CSS_Gradient::CopyTo(copy); } // Copy to self is weird but not an error. return OpStatus::OK; } OP_STATUS CSS_RadialGradient::CopyToRadial(CSS_RadialGradient& copy) const { if (this != &copy) { copy.pos = pos; copy.form = form; return CSS_Gradient::CopyTo(copy); } // Copy to self is weird but not an error. return OpStatus::OK; } CSS_LinearGradient* CSS_LinearGradient::Copy() const { CSS_LinearGradient* copy = OP_NEW(CSS_LinearGradient, ()); if (!copy || CopyToLinear(*copy) != OpStatus::OK) { OP_DELETE(copy); return NULL; } return copy; } CSS_LinearGradient* CSS_LinearGradient::CopyL() const { CSS_LinearGradient* copy = Copy(); if (!copy) LEAVE(OpStatus::ERR_NO_MEMORY); return copy; } CSS_RadialGradient* CSS_RadialGradient::Copy() const { CSS_RadialGradient* copy = OP_NEW(CSS_RadialGradient, ()); if (!copy || CopyToRadial(*copy) != OpStatus::OK) { OP_DELETE(copy); return NULL; } return copy; } CSS_RadialGradient* CSS_RadialGradient::CopyL() const { CSS_RadialGradient* copy = Copy(); if (!copy) LEAVE(OpStatus::ERR_NO_MEMORY); return copy; } // Misc. BOOL CSS_Gradient::IsOpaque() const { for (int i = 0; i < stop_count; i++) if (stops[i].color == CSS_COLOR_transparent || OP_GET_A_VALUE(HTM_Lex::GetColValByIndex(stops[i].color)) < 255) { return false; } return true; } void CSS_LinearGradient::CalculateShape(VisualDevice*, const OpRect& rect) const { OP_ASSERT(line.end_set || line.angle_set); // Checked in CSS_Parser::SetLinearGradientL if (line.end_set) { if (line.to && line.x != CSS_VALUE_center && line.y != CSS_VALUE_center) { // "Magic corners" double corner_ccw = 0; // Angle of the neighboring corner in the counter-clockwise direction if (line.x == CSS_VALUE_left && line.y == CSS_VALUE_top ) corner_ccw = op_atan2((double) -rect.height, -rect.width); else if (line.x == CSS_VALUE_right && line.y == CSS_VALUE_top ) corner_ccw = op_atan2((double) rect.height, -rect.width); else if (line.x == CSS_VALUE_right && line.y == CSS_VALUE_bottom) corner_ccw = op_atan2((double) rect.height, rect.width); else if (line.x == CSS_VALUE_left && line.y == CSS_VALUE_bottom) corner_ccw = op_atan2((double) -rect.height, rect.width); else OP_ASSERT(!"line.x can be only left, right or center."); CalculateShape(M_PI - corner_ccw, rect); } else { // Horizontal or vertical gradient line, or old syntax (no 'to': no magic corners) switch (line.x) { case CSS_VALUE_left: start.x = rect.width; break; case CSS_VALUE_right: start.x = 0; break; case CSS_VALUE_center: start.x = rect.width / 2.0; break; default: OP_ASSERT(!"line.x can be only left, right or center."); } switch (line.y) { case CSS_VALUE_top: start.y = rect.height; break; case CSS_VALUE_bottom: start.y = 0; break; case CSS_VALUE_center: start.y = rect.height / 2.0; break; default: OP_ASSERT(!"line.y can be only top, bottom or center."); } // This if can be removed once the prefixes are gone. if (!line.to) { start.x = rect.width - start.x; start.y = rect.height - start.y; } end.x = rect.width - start.x; end.y = rect.height - start.y; } } else if (line.angle_set) { CalculateShape(line.angle, rect); } double width = end.x - start.x; double height = end.y - start.y; length = op_sqrt(width*width + height*height); angle = op_atan2(height, width); } void CSS_LinearGradient::CalculateShape(double t, const OpRect& rect) const { // Convert the top-origin, clockwise angle into a right origin, counter-clockwise angle, for easier math // Don't do it when prefixed though, as the angle is that way. if (!webkit_prefix && !o_prefix) t = M_PI/2.0 - t; // Normalize the gradient angle to -M_PI <= t < M_PI to easily compare to c_angle t = op_fmod(t, 2*M_PI); if (t > 0) { if (t >= M_PI) t -= 2*M_PI; } else if (t < -M_PI) t += 2*M_PI; // Find the length of the corner line double c = op_sqrt((rect.width)*(rect.width)/4.0 + (rect.height)*(rect.height)/4.0); // Pick the right corner and find the angle there. double c_angle; if (t >= -M_PI && t < -M_PI/2.0) c_angle = op_atan2((double) -rect.height, -rect.width); else if (t >= -M_PI/2.0 && t < 0 ) c_angle = op_atan2((double) -rect.height, rect.width); else if (t >= 0 && t < M_PI/2.0 ) c_angle = op_atan2((double) rect.height, rect.width); else c_angle = op_atan2((double) rect.height, -rect.width); double A = op_fabs(t - c_angle); // A: the angle between the corner line and the gradient_line. double B = M_PI/2.0 - A; // B: the angle between the corner line and the line perpendicular to the gradient line. // Use the sine rule to find... double b = c * op_sin(B); // b: the distance from the center of the box to the end of the gradient line // x, y: the end of the gradient line. double x = b * op_cos(t); double y = b * op_sin(t); start.x = rect.width / 2.0 - x; start.y = rect.height / 2.0 + y; end.x = rect.width / 2.0 + x; end.y = rect.height / 2.0 - y; } void CSS_RadialGradient::CalculateEllipseCorner(const OpDoublePoint& end) const { if (vrad == 0 || length == 0) // Degenerate; avoid divide by 0 // MakeVEGAGradient will handle the 0-height case; CalculateShape handles 0-width return; // Find angle and distance to the corner double corner_dist = op_sqrt((start.x - end.x)*(start.x - end.x) + (start.y - end.y)*(start.y - end.y)); double angle = op_atan2(end.x - start.x, end.y - start.y); // Current radius in the direction of the corner double current_rad = length * vrad / op_sqrt((length*op_cos(angle))*(length*op_cos(angle)) + ((vrad * op_sin(angle)) * (vrad * op_sin(angle)))); // Scale the ellipse so that the circumference intersects the corner length = length * corner_dist / current_rad; vrad = vrad * corner_dist / current_rad; } void CSS_RadialGradient::CalculateShape(VisualDevice* vd, const OpRect& rect) const { CSSLengthResolver length_resolver(vd); length_resolver.FillFromVisualDevice(); // Find the used center of the gradient. pos.Calculate(vd, rect, start, length_resolver); OpDoublePoint center = OpDoublePoint(rect.width / 2.0, rect.height / 2.0); if (form.has_explicit_size) { length = length_resolver.ChangePercentageBase(float(rect.width)).GetLengthInPixels(form.explicit_size[0], form.explicit_size_unit[0]); if (form.explicit_size[1] == -1.0) // Special handling, maintaining circle shape vrad = length; else vrad = length_resolver.ChangePercentageBase(float(rect.height)).GetLengthInPixels(form.explicit_size[1], form.explicit_size_unit[1]); } else { OpDoublePoint end; switch (form.shape) { case CSS_VALUE_circle: switch (form.size) { case CSS_VALUE_closest_side: vrad = length = op_fabs(MIN(MIN(start.x, rect.width - start.x), MIN(start.y, rect.height - start.y))); break; case CSS_VALUE_farthest_side: vrad = length = MAX(MAX(start.x, rect.width - start.x), MAX(start.y, rect.height - start.y)); break; case CSS_VALUE_closest_corner: end.x = start.x < center.x ? 0 : rect.width; end.y = start.y < center.y ? 0 : rect.height; vrad = length = op_sqrt((start.x - end.x)*(start.x - end.x) + (start.y - end.y)*(start.y - end.y)); break; case CSS_VALUE_farthest_corner: end.x = start.x > center.x ? 0 : rect.width; end.y = start.y > center.y ? 0 : rect.height; vrad = length = op_sqrt((start.x - end.x)*(start.x - end.x) + (start.y - end.y)*(start.y - end.y)); break; } break; case CSS_VALUE_ellipse: switch (form.size) { case CSS_VALUE_closest_side: case CSS_VALUE_contain: length = op_fabs(MIN(start.x, rect.width - start.x)); vrad = op_fabs(MIN(start.y, rect.height - start.y)); break; case CSS_VALUE_farthest_side: length = MAX(start.x, rect.width - start.x); vrad = MAX(start.y, rect.height - start.y); break; case CSS_VALUE_closest_corner: { // Shape like for closest-side length = op_fabs(MIN(start.x, rect.width - start.x)); vrad = op_fabs(MIN(start.y, rect.height - start.y)); end.x = start.x < center.x ? 0 : rect.width; end.y = start.y < center.y ? 0 : rect.height; CalculateEllipseCorner(end); break; } case CSS_VALUE_farthest_corner: case CSS_VALUE_cover: // Shape like for farthest-side length = op_fabs(MAX(start.x, rect.width - start.x)); vrad = op_fabs(MAX(start.y, rect.height - start.y)); end.x = start.x > center.x ? 0 : rect.width; end.y = start.y > center.y ? 0 : rect.height; CalculateEllipseCorner(end); break; } break; } } // Degenerate: 0-width gradients are given infinite height and near-0 width // The 0-height case is handled in MakeVEGAGradient if (length <= 0) { vrad = VEGA_FIXTOFLT(VEGA_INFINITY); length = VEGA_FIXTOFLT(VEGA_EPSILON); } } // Serialization void CSS_LinearGradient::ToStringL(TempBuffer* buf) const { if (line.end_set) { if (line.to) buf->AppendL("to "); if (line.y != CSS_VALUE_center) buf->AppendL(CSS_GetKeywordString(line.y)); if (line.y != CSS_VALUE_center && line.x != CSS_VALUE_center) buf->AppendL(" "); if (line.x != CSS_VALUE_center) buf->AppendL(CSS_GetKeywordString(line.x)); } else if (line.angle_set) { CSS::FormatCssNumberL(line.angle, CSS_RAD, buf, FALSE); } buf->AppendL(", "); ColorStopsToStringL(buf); } void CSS_RadialGradient::ToStringL(TempBuffer* buf) const { if (form.has_explicit_size) { if(form.explicit_size[1] == -1.0) { buf->AppendL("circle"); CSS::FormatCssNumberL(form.explicit_size[0], form.explicit_size_unit[0], buf, TRUE); } else { buf->AppendL("ellipse"); CSS::FormatCssNumberL(form.explicit_size[0], form.explicit_size_unit[0], buf, TRUE); CSS::FormatCssNumberL(form.explicit_size[1], form.explicit_size_unit[1], buf, TRUE); } } else { buf->AppendL(CSS_GetKeywordString(form.shape)); buf->AppendL(' '); buf->AppendL(CSS_GetKeywordString(form.size)); } if (pos.is_set) { buf->AppendL(" at "); pos.ToStringL(buf); } else { buf->AppendL(" at center"); } buf->AppendL(", "); ColorStopsToStringL(buf); } void CSS_RadialGradient::Position::Calculate(VisualDevice* vd, const OpRect& rect, OpDoublePoint& out, CSSLengthResolver& length_resolver) const { if (is_set) { if (has_ref) { switch (ref[0]) { case CSS_VALUE_left: out.x = length_resolver.ChangePercentageBase(float(rect.width)).GetLengthInPixels(pos[0], pos_unit[0]); break; case CSS_VALUE_right: out.x = rect.width - length_resolver.ChangePercentageBase(float(rect.width)).GetLengthInPixels(pos[0], pos_unit[0]); break; default: OP_ASSERT(!"Unexpected <bg-position> keyword"); } switch (ref[1]) { case CSS_VALUE_top: out.y = length_resolver.ChangePercentageBase(float(rect.height)).GetLengthInPixels(pos[1], pos_unit[1]); break; case CSS_VALUE_bottom: out.y = rect.height - length_resolver.ChangePercentageBase(float(rect.height)).GetLengthInPixels(pos[1], pos_unit[1]); break; default: OP_ASSERT(!"Unexpected <bg-position> keyword"); } } else { out.x = length_resolver.ChangePercentageBase(float(rect.width)).GetLengthInPixels(pos[0], pos_unit[0]); out.y = length_resolver.ChangePercentageBase(float(rect.height)).GetLengthInPixels(pos[1], pos_unit[1]); } } else { // Not set is equivalent to 'center' out.x = rect.width / 2.0; out.y = rect.height / 2.0; } } void CSS_RadialGradient::Position::ToStringL(TempBuffer* buf) const { if (is_set) { if (has_ref) buf->AppendL(CSS_GetKeywordString(ref[0])); CSS::FormatCssNumberL(pos[0], pos_unit[0], buf, has_ref); buf->AppendL(' '); if (has_ref) buf->AppendL(CSS_GetKeywordString(ref[1])); CSS::FormatCssNumberL(pos[1], pos_unit[1], buf, has_ref); } } void CSS_Gradient::ColorStopsToStringL(TempBuffer* buf) const { for (int i = 0; i < stop_count; i++) { if (i > 0) buf->AppendL(", "); stops[i].ToStringL(buf); } } void CSS_Gradient::ColorStop::ToStringL(TempBuffer* buf) const { /* Ideally, the CSS::FormatCssColorL should be used. We'd need to know whether we are formatting for computed styles or style declarations though. */ if (color == CSS_COLOR_transparent) buf->AppendL("transparent"); else if (color == CSS_COLOR_current_color) buf->AppendL("currentColor"); else { COLORREF colorval = HTM_Lex::GetColValByIndex(color); CSS::FormatCssValueL((void*)(INTPTR) colorval, CSS::CSS_VALUE_TYPE_color, buf, FALSE); } if (has_length) if (length == 0) buf->AppendL(" 0px"); else CSS::FormatCssNumberL(length, unit, buf, TRUE); } // The following methods use a lot of graphics logic. Changes should be review by the GFX group. /* static */ UINT32 CSS_RadialGradient::InterpolateStop(UINT32 prev, UINT32 next, double pos) { double r, g, b, a; InterpolatePremultiplied(prev, next, pos, 1, r, g, b, a); Unpremultiply(r, g, b, a); return PackARGB(r, g, b, a); } /* static */ void CSS_Gradient::InterpolateForAverage(UINT32 prev, UINT32 next, double weight, double& r, double& g, double& b, double& a) { InterpolatePremultiplied(prev, next, 0.5, weight, r, g, b, a); } /* static */ void CSS_Gradient::InterpolatePremultiplied(UINT32 prev, UINT32 next, double pos, double weight, double& r, double& g, double& b, double& a) { const double alpha = (1 - pos) * UnpackAlpha(prev) + pos * UnpackAlpha(next); // Premultiply double r1 = UnpackRed (prev) * UnpackAlpha(prev) / 255.0; double g1 = UnpackGreen(prev) * UnpackAlpha(prev) / 255.0; double b1 = UnpackBlue (prev) * UnpackAlpha(prev) / 255.0; double r2 = UnpackRed (next) * UnpackAlpha(next) / 255.0; double g2 = UnpackGreen(next) * UnpackAlpha(next) / 255.0; double b2 = UnpackBlue (next) * UnpackAlpha(next) / 255.0; // Interpolate r = ((1 - pos) * r1 + pos * r2) * weight; g = ((1 - pos) * g1 + pos * g2) * weight; b = ((1 - pos) * b1 + pos * b2) * weight; a = (alpha) * weight; } void CSS_LinearGradient::ModifyStops() const { // For gradients too small to reproduce faithfully, use the 0-width averaging algorithm from the spec. if (repeat && VEGA_FIXTOFLT(offsets[stop_count - 1] - offsets[0]) * length < 1.0) { AveragePremultiplied(FALSE); return; } // Modification only necessary for repeating gradients if (repeat && length > 0) { double smallest = VEGA_FIXTOFLT(offsets[0]), largest = VEGA_FIXTOFLT(offsets[stop_count - 1]); OpDoublePoint line_start = start; start.x = line_start.x + smallest*length * op_cos(angle); start.y = line_start.y + smallest*length * op_sin(angle); end.x = line_start.x + largest*length * op_cos(angle); end.y = line_start.y + largest*length * op_sin(angle); double old_length = length; length = (largest - smallest) * length; NormalizeStops(old_length); } } void CSS_RadialGradient::ModifyStops() const { int last = stop_count - 1; if (!repeat && offsets[last] <= VEGA_INTTOFIX(1)) return; // Radial gradients need additional massaging if first and last color stops are not at 0 and 1 if ((offsets[0] == 0 || !repeat) && offsets[last] != VEGA_INTTOFIX(1)) { // If the first stop is still at 0, or the gradient doesn't repeat, it's relatively easy double old_length = length; length = VEGA_FIXTOFLT(offsets[last]) * length; vrad = vrad * length / old_length; NormalizeStops(old_length); } else if (offsets[0] != 0 && repeat) { // If the first stop is not at 0 and the gradient repeats, we're in for a rough ride. /* 1. Find the length of the gradient line and use it as the actual radius. */ double smallest = VEGA_FIXTOFLT(offsets[0]), largest = VEGA_FIXTOFLT(offsets[stop_count - 1]); double stop_distance = largest - smallest; /* 2. Transpose stops so that the gradient only repeats once within the new, actual radius. This is to avoid duplicating more stops than absolutely necessary. Transposition is only necessary if the specified stops are completely outside the new radius. */ if (smallest >= stop_distance || smallest < 0) { int n = int(smallest / stop_distance); if (smallest < 0 && op_fmod(smallest, stop_distance) != 0) // When transposing from below zero, add an extra step to push it past 0. // Unless smallest is divisible by stop_distance, in which case we'll end up exactly at 0. n--; for(int i = 0; i < stop_count; i++) offsets[i] -= VEGA_FLTTOFIX(n * stop_distance); } /* 3. Rotate stops */ // Find new first stop. It is the first stop whose offset is greater than the gradient length. int new_first = 0; OP_ASSERT(VEGA_FIXTOFLT(offsets[stop_count - 1]) > 0); // Loop invariant while (VEGA_FIXTOFLT(offsets[new_first]) - stop_distance < 0) new_first++; // CalculateStops() has already allocated the necessary space for actual_stop_count. actual_stop_count = stop_count + 2; /* Rotate */ // First, shift array one to the right to make room for a synthetic stop. for (int i = stop_count; i > 0; i--) { offsets[i] = offsets[i - 1]; colors [i] = colors [i - 1]; // Update offsets if (i > new_first) offsets[i] -= VEGA_FLTTOFIX(stop_distance); } // Then, start shifting the stops. for (int i = 0; i < new_first; i++) { VEGA_FIX offset_temp = offsets[i]; UINT32 color_temp = colors [i]; for (int j = 1; j < stop_count; j++) { offsets[j] = offsets[j+1]; colors [j] = colors [j+1]; } offsets[stop_count] = offset_temp; colors [stop_count] = color_temp; } /* 4. Create synthetic stops */ offsets[0] = 0; offsets[actual_stop_count - 1] = VEGA_INTTOFIX(1); double delta = VEGA_FIXTOFLT(offsets[1]) + (stop_distance - VEGA_FIXTOFLT(offsets[actual_stop_count - 2])); // A 0-size gradient should prevent ModifyStops from being called. So delta will not be 0 and divide by 0 is prevented. OP_ASSERT(delta != 0); double pos = (delta - VEGA_FIXTOFLT(offsets[1])) / delta; colors[0] = colors[actual_stop_count - 1] = InterpolateStop( colors[actual_stop_count - 2], colors[1], pos); /* 5. Adjust radius */ double old_length = length; length = stop_distance * length; vrad = vrad * length / old_length; for (int i = 1; i < actual_stop_count - 1; i++) { offsets[i] = VEGA_FLTTOFIX(VEGA_FIXTOFLT(offsets[i])*old_length/length); } } // else // If the stops are already at 0 and 1, nothing needs to be done. // Clamp vrad at VEGA_INFINITY to avoid transform trouble if (vrad > VEGA_FIXTOFLT(VEGA_INFINITY)) vrad = VEGA_FIXTOFLT(VEGA_INFINITY); if (actual_stop_count != -1) last = actual_stop_count - 1; // For gradients too small to reproduce faithfully, use the 0-width averaging algorithm from the spec. if (repeat) { // VEGA_EPSILON is used in case an exact 1.0 gets binary-rounded down or 0.0 gets rounded up // Less than or equals is used because length can be set to VEGA_EPSILON in CalculateShape if (length <= VEGA_FIXTOFLT(VEGA_EPSILON)) { // Gradient line is zero; ignore stop offsets AveragePremultiplied(FALSE); return; } // The limit for vrad is smaller because it's handled using transforms rather than pixel coordinates else if (length < 1.0 - VEGA_FIXTOFLT(VEGA_EPSILON) || VEGA_FIXTOFLT(offsets[last] - offsets[0]) * length < 1.0 - VEGA_FIXTOFLT(VEGA_EPSILON) || vrad < 0.005) { // Gradient line or vertical radius too short; average while preserving stop offsets AveragePremultiplied(TRUE); return; } } } BOOL CSS_Gradient::CalculateStops(VisualDevice* vd, COLORREF current_color) const { const int last = stop_count - 1; OP_ASSERT(stop_count >= 2); // Checked by SetGradient CSSLengthResolver length_resolver(vd); length_resolver.FillFromVisualDevice(); VEGA_FIX largest = -VEGA_INFINITY; /* This should not happen, but just in case other code is changed and starts rendering the same gradient multiple times: */ OP_DELETEA(offsets); OP_DELETEA(colors); // Allocate two extra stops, in case CSS_RadialGradient::ModifyStops needs to add and duplicate the 0 stop. colors = OP_NEWA(UINT32, stop_count + 2); offsets = OP_NEWA(VEGA_FIX, stop_count + 2); if (!colors || !offsets) return FALSE; // Stops with specified or default lengths for (int i = 0; i < stop_count; i++) { if (stops[i].has_length) { if (stops[i].unit == CSS_PERCENTAGE) { offsets[i] = VEGA_FLTTOFIX(stops[i].length)/100; } else { // Since VEGA color stops are normalized, absolute lengths must be converted. int stop_length = length_resolver.ChangePercentageBase(float(length)).GetLengthInPixels(stops[i].length, stops[i].unit); offsets[i] = VEGA_FLTTOFIX(stop_length/length); } // Rule 2: If a color-stop's position is less than any previous one, match it to the largest if (offsets[i] < largest) offsets[i] = largest; largest = offsets[i]; } // Rule 1: Default positions for first and last stops, when no length is given or inferred. else if (i == 0) largest = offsets[0] = 0; else if (i == last) if (VEGA_INTTOFIX(1) < largest) offsets[last] = largest; else offsets[last] = VEGA_INTTOFIX(1); } int next_with_length = 0, last_with_length = 0; double next_length = 0, last_length = 0; // Stops without specified lengths // Rule 3: Spread lengthless stops evenly between stops with lengths for (int i = 0; i < stop_count; i++) if (stops[i].has_length || i == 0 || i == last) { // First and last always have lengths by now // Keep track of the last specified length last_length = VEGA_FIXTOFLT(offsets[i]); last_with_length = i; } else { // No length specified if (next_with_length < i) { // Find the next stop with a length (last one always has length) next_with_length = i + 1; while (!(stops[next_with_length].has_length || next_with_length == last)) next_with_length++; next_length = VEGA_FIXTOFLT(offsets[next_with_length]); } // We're in a run of lengthless stops offsets[i] = VEGA_FLTTOFIX(last_length + (next_length - last_length) * (i - last_with_length) / (next_with_length - last_with_length)); } for (int i = 0; i < stop_count; i++) { if (stops[i].color == CSS_COLOR_transparent) colors[i] = OP_COLORREF2VEGA(OP_RGBA(0,0,0,0)); else if (stops[i].color == CSS_COLOR_current_color) colors[i] = OP_COLORREF2VEGA(HTM_Lex::GetColValByIndex(current_color)); else colors[i] = OP_COLORREF2VEGA(HTM_Lex::GetColValByIndex(stops[i].color)); } ModifyStops(); return TRUE; } void CSS_Gradient::AveragePremultiplied(BOOL preserve_offsets) const { double r = 0, g = 0, b = 0, a = 0; for (int i = 0; i < stop_count - 1; i++) // 'stop_count - 1' because the stops are evaluated in pairs { double weight; if (preserve_offsets) weight = (offsets[i + 1] - offsets[i]); else weight = 1.0 / double(stop_count - 1); double new_r, new_b, new_g, new_a; InterpolateForAverage(colors[i], colors[i + 1], weight, new_r, new_g, new_b, new_a); r += new_r; g += new_g; b += new_b; a += new_a; } UINT32 average; Unpremultiply(r, g, b, a); average = PackARGB(r, g, b, a); use_average_color = TRUE; // use_average_color is a signal that there are only two stops. for (int i = 0; i < 2; i++) colors[i] = average; } VEGAFill* CSS_LinearGradient::MakeVEGAGradient(VisualDevice* vd, VEGAOpPainter* vpainter, const OpRect& rect, COLORREF current_color, VEGATransform&) const { use_average_color = FALSE; CalculateShape(vd, rect); if (!CalculateStops(vd, current_color)) return NULL; // Handle average color if (use_average_color) return vpainter->CreateLinearGradient( 0, 0, 0, 0, 2, offsets, colors, TRUE /* premultiplied */); // Scale all rendering data to current zoom and transform start = vd->ToPainterExtentDbl(start); end = vd->ToPainterExtentDbl(end); // Create VEGAGradient VEGAFill* gradient_out = vpainter->CreateLinearGradient( VEGA_FLTTOFIX(start.x), VEGA_FLTTOFIX(start.y), VEGA_FLTTOFIX(end.x), VEGA_FLTTOFIX(end.y), stop_count, offsets, colors, TRUE /* premultiplied */); if (repeat) gradient_out->setSpread(VEGAFill::SPREAD_REPEAT); return gradient_out; } VEGAFill* CSS_RadialGradient::MakeVEGAGradient(VisualDevice* vd, VEGAOpPainter* vpainter, const OpRect& rect, COLORREF current_color, VEGATransform& radial_adjust) const { use_average_color = FALSE; CalculateShape(vd, rect); if (!CalculateStops(vd, current_color)) return NULL; // Handle average color if (use_average_color) return vpainter->CreateRadialGradient( 0, 0, 0, 0, 0, 2, offsets, colors, FALSE /* premultiplied */); // Degenerate: If the radial gradient has 0 height, draw last color stop only. // The 0-width case is handled in CalculateShape if (vrad <= 0) { return vpainter->CreateRadialGradient(0, 0, 0, 0, 0, stop_count, offsets, colors, TRUE); } // Scale all rendering data to current zoom and transform start = vd->ToPainterExtentDbl(start); length = vd->ToPainterExtentDbl(length); vrad = vd->ToPainterExtentDbl(vrad); // Create VEGAGradient VEGAFill* gradient_out = vpainter->CreateRadialGradient( VEGA_FLTTOFIX(start.x), VEGA_FLTTOFIX(start.y), VEGA_FLTTOFIX(start.x), VEGA_FLTTOFIX(start.y), VEGA_FLTTOFIX(length), actual_stop_count == -1 ? stop_count : actual_stop_count, offsets, colors, TRUE /* premultiplied */); // VEGA only does circular gradients; if elliptic, adjust with fill-transform // Inaccuracy does little harm, so epsilon is not needed if (length != vrad) { VEGATransform tx; tx.loadTranslate(VEGA_FLTTOFIX(start.x), VEGA_FLTTOFIX(start.y)); radial_adjust.multiply(tx); tx.loadScale(1, VEGA_FLTTOFIX(vrad / length)); radial_adjust.multiply(tx); tx.loadTranslate(VEGA_FLTTOFIX(-start.x), VEGA_FLTTOFIX(-start.y)); radial_adjust.multiply(tx); } if (repeat) gradient_out->setSpread(VEGAFill::SPREAD_REPEAT); return gradient_out; } void CSS_LinearGradient::NormalizeStops(double old_length) const { double smallest = VEGA_FIXTOFLT(offsets[0]); if (length != 0) for (int i = 0; i < stop_count; i++) offsets[i] = VEGA_FLTTOFIX((VEGA_FIXTOFLT(offsets[i]) - smallest) * old_length / length); else for (int i = 0; i < stop_count; i++) offsets[i] = 0; } void CSS_RadialGradient::NormalizeStops(double old_length) const { if (length != 0) for (int i = 0; i < stop_count; i++) offsets[i] = VEGA_FLTTOFIX((VEGA_FIXTOFLT(offsets[i])) * old_length / length); else for (int i = 0; i < stop_count; i++) offsets[i] = 0; } #endif // CSS_GRADIENT_SUPPORT
// // Created by heyhey on 20/03/2018. // #ifndef PLDCOMP_APPELFONCTION_H #define PLDCOMP_APPELFONCTION_H #include <ostream> #include "Expression.h" #include "Parametre.h" class AppelFonction : public Expression { public: AppelFonction(); AppelFonction(const string &nomFonction, Parametre *parametre); virtual ~AppelFonction(); private: string nomFonction; Parametre* parametre; public: const string &getNomFonction() const; void setNomFonction(const string &nomFonction); Parametre *getParametre() const; void setParametre(Parametre *parametre); friend ostream &operator<<(ostream &os, const AppelFonction &fonction); }; #endif //PLDCOMP_APPELFONCTION_H
/* Copyright 2018 Stanford * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _FLEXFLOW_CONFIG_H_ #define _FLEXFLOW_CONFIG_H_ #include <cstring> #include "legion.h" using namespace Legion; class FFConfig { public: int epochs, batchSize, numIterations, printFreq; int inputHeight, inputWidth; int numNodes, loadersPerNode, workersPerNode; float learningRate, weightDecay; size_t workSpaceSize; Context lg_ctx; Runtime* lg_hlr; FieldSpace field_space; bool syntheticInput, profiling; std::string datasetPath, strategyFile; }; #endif//_FLEXFLOW_CONFIG_H_
// internal #include <iostream> #include "physics_system.hpp" #include "world_init.hpp" // Returns the local bounding coordinates scaled by the current size of the entity vec2 get_bounding_box(const Motion& motion) { // abs is to avoid negative scale due to the facing direction. return { abs(motion.scale.x), abs(motion.scale.y) }; } // This is a SUPER APPROXIMATE check that puts a circle around the bounding boxes and sees // if the center point of either object is inside the other's bounding-box-circle. You can // surely implement a more accurate detection bool collides(const Motion& motion1, const Motion& motion2) { vec2 dp = motion1.position - motion2.position; float dist_squared = dot(dp,dp); const vec2 other_bonding_box = get_bounding_box(motion1) / 2.f; const float other_r_squared = dot(other_bonding_box, other_bonding_box); const vec2 my_bonding_box = get_bounding_box(motion2) / 2.f; const float my_r_squared = dot(my_bonding_box, my_bonding_box); const float r_squared = max(other_r_squared, my_r_squared); if (dist_squared < r_squared) return true; return false; } // This whole function has duplicated code from handleWallCollision, should be refactored. bool checkWallCollision(Entity entity, Entity wall) { Motion& entity_motion = registry.motions.get(entity); vec2 entity_bounding_box = get_bounding_box(entity_motion) / 2.0f; Motion& wall_motion = registry.motions.get(wall); vec2 wall_bounding_box = get_bounding_box(wall_motion) / 2.0f; vec2 player_min = { entity_motion.position[0] - entity_bounding_box[0], entity_motion.position[1] + entity_bounding_box[1] }; vec2 player_max = { entity_motion.position[0] + entity_bounding_box[0], entity_motion.position[1] - entity_bounding_box[1] }; vec2 wall_min = { wall_motion.position[0] - wall_bounding_box[0], wall_motion.position[1] + wall_bounding_box[1] }; vec2 wall_max = { wall_motion.position[0] + wall_bounding_box[0], wall_motion.position[1] - wall_bounding_box[1] }; if ((player_min[0] < wall_max[0]) && (wall_min[0] < player_max[0]) && (player_min[1] > wall_max[1]) && (wall_min[1] > player_min[1])) { return true; } return false; } void checkFakeCollision(Entity e, bool forAI) { ComponentContainer<Motion>& motion_container = registry.motions; Motion m = registry.motions.get(e); std::vector<Entity> entities = registry.motions.entities; for (uint i = 0; i < motion_container.components.size(); i++) { Motion& motion_i = motion_container.components[i]; if (motion_i.collision_proof == 1 || (unsigned int)entities[i] == (unsigned int)e || registry.debugComponents.has(entities[i])) { continue; } if (forAI && registry.players.has(entities[i])) { continue; } // these two if blocks are pretty clumsy, might want to refactor if (registry.walls.has(entities[i])) { if (checkWallCollision(e, entities[i])) { if (forAI && registry.AIEntities.has(entities[i])) { AIEntity& ai = registry.AIEntities.get(entities[i]); ai.coveredPositions.push_back(std::make_pair( round(m.position.x / 50.f), round(m.position.y / 50.f) )); } registry.remove_all_components_of(e); return; } else { continue; } } if (collides(motion_i, m)) { if (forAI && registry.AIEntities.has(entities[i])) { AIEntity& ai = registry.AIEntities.get(entities[i]); ai.coveredPositions.push_back(std::make_pair( round(m.position.x / 50.f), round(m.position.y / 50.f) )); } registry.remove_all_components_of(e); return; } } } std::function<void(Entity, bool)> PhysicsSystem::getCollisionFunction() { return checkFakeCollision; } void PhysicsSystem::step(float elapsed_ms, float window_width_px, float window_height_px) { // Move entity based on how much time has passed, this is to (partially) avoid // having entities move at different speed based on the machine. auto& motion_registry = registry.motions; ComponentContainer<Motion>& motion_container = registry.motions; if (registry.game.get(registry.players.entities[0]).state == GameState::PLAYING) { for (uint i = 0; i < motion_registry.size(); i++) { Motion& motion = motion_registry.components[i]; Entity entity = motion_registry.entities[i]; float step_seconds = 1.0f * (elapsed_ms / 1000.f); // Check that step does not take player out of bounds vec2 potential_pos = motion.position + (motion.velocity * step_seconds); if (potential_pos[0] > 40 && potential_pos[0] < window_width_px - 40 && potential_pos[1] > 40 && potential_pos[1] < window_height_px - 40) { motion.position = motion.position + (motion.velocity * step_seconds); } } // Check for collisions between all moving entities for (uint i = 0; i < motion_container.components.size(); i++) { Motion& motion_i = motion_container.components[i]; Entity entity_i = motion_container.entities[i]; for (uint j = 0; j < motion_container.components.size(); j++) // i+1 { if (i == j) continue; Entity entity_j = motion_container.entities[j]; Motion& motion_j = motion_container.components[j]; if (registry.players.has(entity_i) && registry.walls.has(entity_j)) { handleWallCollision(entity_i, entity_j); continue; } else if (registry.walls.has(entity_i) && registry.players.has(entity_j)) { handleWallCollision(entity_j, entity_i); continue; } if (collides(motion_i, motion_j)) { Entity entity_j = motion_container.entities[j]; // Create a collisions event // We are abusing the ECS system a bit in that we potentially insert muliple collisions for the same entity registry.collisions.emplace_with_duplicates(entity_i, entity_j); registry.collisions.emplace_with_duplicates(entity_j, entity_i); } } } } // you may need the following quantities to compute wall positions (float)window_width_px; (float)window_height_px; // debugging of bounding boxes if (debugging.in_debug_mode) { // create a red line around the wall boxes for (Entity wallBox: registry.walls.entities) { Motion& wallMotion = registry.motions.get(wallBox); createBox(wallMotion.position, wallMotion.scale); } Entity playerDoll = registry.players.entities[0]; Motion& dollMotion = registry.motions.get(playerDoll); createBox(dollMotion.position, dollMotion.scale); for (Entity enemy: registry.enemies.entities) { Motion& enemyMotion = registry.motions.get(enemy); createBox(enemyMotion.position, enemyMotion.scale); } } } void PhysicsSystem::handleWallCollision(Entity player, Entity wall) { Motion& player_motion = registry.motions.get(player); vec2 player_bounding_box = get_bounding_box(player_motion) / 2.0f; // temporary hack to account for whitespace player_bounding_box = { player_bounding_box[0] - 30, player_bounding_box[1] - 30 }; Motion& wall_motion = registry.motions.get(wall); vec2 wall_bounding_box = get_bounding_box(wall_motion) / 2.0f; vec2 player_min = { player_motion.position[0] - player_bounding_box[0], player_motion.position[1] + player_bounding_box[1] }; vec2 player_max = { player_motion.position[0] + player_bounding_box[0], player_motion.position[1] - player_bounding_box[1] }; vec2 wall_min = { wall_motion.position[0] - wall_bounding_box[0], wall_motion.position[1] + wall_bounding_box[1] }; vec2 wall_max = { wall_motion.position[0] + wall_bounding_box[0], wall_motion.position[1] - wall_bounding_box[1] }; if ((player_min[0] < wall_max[0]) && (wall_min[0] < player_max[0]) && (player_min[1] > wall_max[1]) && (wall_min[1] > player_min[1])) { if (player_motion.dir == Direction::UP) { float overlap = wall_min[1] - player_min[1]; player_motion.position[1] = player_motion.position[1] + overlap; } else if (player_motion.dir == Direction::DOWN) { float overlap = player_min[1] - wall_max[1]; player_motion.position[1] = player_motion.position[1] - overlap; } else if (player_motion.dir == Direction::LEFT) { float overlap = wall_max[0] - player_min[0]; player_motion.position[0] = player_motion.position[0] + overlap; } else if (player_motion.dir == Direction::RIGHT) { float overlap = player_max[0] - wall_min[0]; player_motion.position[0] = player_motion.position[0] - overlap; } } return; }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; char s1[3333], s2[3333], s3[3333]; int lst[33]; int nxt[1555]; int u[1555]; int Solve(char * a, int an, char * B, int bn) { int ans = 0; for (int sh = 0; sh < bn; ++sh) { char * b = B + sh; memset(lst, -1, sizeof(lst)); for (int i = an - 1; i >= 0; --i) { nxt[i] = lst[a[i] - 'a']; lst[a[i] - 'a'] = i; } int un = 0; for (int i = 0; i < bn; ++i) { int x = lst[ b[i] - 'a' ]; if (x == -1) continue; int p = lower_bound(u, u + un, x) - u; if (p == un) u[un++] = x;else u[p] = x; lst[b[i] - 'a'] = nxt[x]; } if (un > ans) ans = un; } return ans; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%s%s", s1, s2); int n1 = strlen(s1); int n2 = strlen(s2); memcpy(s2 + n2, s2, n2); strcpy(s3, s2); reverse(s3, s3 + n2 + n2); cout << max(Solve(s1, n1, s2, n2), Solve(s1, n1, s3, n2)) * 2 << endl; return 0; }
#define BOOST_TEST_LOG_LEVEL test_suite #define BOOST_TEST_MODULE test_main #include <boost/test/unit_test.hpp> #include <boost/mpl/assert.hpp> #include <thread> #include <mutex> #include <condition_variable> #include "Server.h" #include "Writers.h" using namespace boost::asio; std::mutex mtx; std::condition_variable cv; bool is_ready = false; class TestHandler : public Handler { uint count = 0; uint stop_count; public: TestHandler(int n,uint stop_count_) : Handler(n) , stop_count(stop_count_) {} void stop() override { Handler::stop(); count++; if (count == stop_count) { std::unique_lock<std::mutex> lk(mtx); is_ready = false; cv.notify_one(); } } }; auto start_server(io_service& service, std::stringstream& out, uint count) { auto thread = std::make_unique<std::thread>([&service,&out,count](){ ip::tcp::endpoint ep(ip::tcp::v4(),9000); auto handler = std::make_shared<TestHandler>(3,count); auto consoleWriter = std::make_shared<ConsoleWriter>(out); consoleWriter->subscribe(handler); Server server(service, ep, handler); { std::unique_lock<std::mutex> lk(mtx); is_ready = true; cv.notify_one(); } service.run(); }); { std::unique_lock<std::mutex> lk(mtx); cv.wait(lk,[]() { return is_ready; }); } return std::move(thread); } BOOST_AUTO_TEST_SUITE(server_test) BOOST_AUTO_TEST_CASE(one_server) { std::stringstream out; io_service service; auto server_thread = start_server(service,out,3); { ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 9000); ip::tcp::socket sock(service); sock.connect(ep); std::string command = "cmd1\n" "cmd2\n" "{\n" "cmd3\n" "cmd4\n" "}\n" "cmd5\n"; write(sock, buffer(command, command.size())); } { std::unique_lock<std::mutex> lk(mtx); cv.wait(lk,[]() { return !is_ready; }); } std::string result = "bulk: cmd1, cmd2\n" "bulk: cmd3, cmd4\n" "bulk: cmd5\n"; service.stop(); server_thread->join(); BOOST_CHECK_EQUAL(out.str(),result); } /////////////////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(two_servers) { std::stringstream out; io_service service; auto server_thread = start_server(service,out,3); { ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 9000); ip::tcp::socket sock1(service); ip::tcp::socket sock2(service); sock1.connect(ep); sock2.connect(ep); std::string command = "cmd1\n" "cmd2\n"; write(sock1, buffer(command, command.size())); command = "cmd3\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); write(sock2, buffer(command, command.size())); command = "cmd4\n"; write(sock1, buffer(command, command.size())); command = "{\n" "cmd5\n"; write(sock2, buffer(command, command.size())); command = "cmd6\n" "cmd7\n" "cmd8\n"; write(sock1, buffer(command, command.size())); command = "cmd9\n" "}\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); write(sock2, buffer(command, command.size())); command = "cmd10\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); write(sock1, buffer(command, command.size())); command = "cmd11\n"; std::this_thread::sleep_for(std::chrono::milliseconds(10)); write(sock2, buffer(command, command.size())); command = "cmd12\n" "cmd13\n"; write(sock1, buffer(command, command.size())); } { std::unique_lock<std::mutex> lk(mtx); cv.wait(lk,[]() { return !is_ready; }); } std::string result = "bulk: cmd1, cmd2, cmd3\n" "bulk: cmd4, cmd6, cmd7\n" "bulk: cmd8\n" "bulk: cmd5, cmd9\n" "bulk: cmd10, cmd11, cmd12\n" "bulk: cmd13\n"; service.stop(); server_thread->join(); BOOST_CHECK_EQUAL(out.str(),result); } BOOST_AUTO_TEST_SUITE_END()
#ifndef SPI_h #define SPI_h #include "Arduino.h" #define CFG_ENABLE (1 << 0) #define CFG_MASTER (1 << 2) #define CFG_SLAVE (0 << 2) #define CFG_LSBF (1 << 3) #define CFG_CPHA (1 << 4) #define CFG_CPOL (1 << 5) #define CFG_LOOPBACK (1 << 7) #define SPI_MODE0 ( 0 | 0 ) #define SPI_MODE1 ( 0 | CFG_CPHA) #define SPI_MODE2 (CFG_CPOL | 0 ) #define SPI_MODE3 (CFG_CPOL | CFG_CPHA) #define DLY_PREDELAY(d) ((d) << 0) #define DLY_POSTDELAY(d) ((d) << 4) #define DLY_FRAMEDELAY(d) ((d) << 8) #define DLY_INTERDELAY(d) ((d) << 12) #define STAT_RXRDY (1 << 0) #define STAT_TXRDY (1 << 1) #define STAT_RXOV (1 << 2) #define STAT_TXUR (1 << 3) #define STAT_SSA (1 << 4) #define STAT_SSD (1 << 5) #define STAT_STALLED (1 << 6) #define STAT_ENDTRANSFER (1 << 7) #define STAT_MSTIDLE (1 << 8) #define TXDATCTL_EOT (1 << 20) #define TXDATCTL_EOF (1 << 21) #define TXDATCTL_RX_IGNORE (1 << 22) #define TXDATCTL_FSIZE(s) ((s) << 24) class SPISettings { public: // Default speed set to 4MHz, SPI mode set to MODE 0 and Bit order set to MSB first SPISettings(uint32_t clock = 4000000, uint8_t bitOrder = MSBFIRST, uint8_t dataMode = SPI_MODE0, byte preDelay = 0, byte postDelay = 0, byte frameDelay = 0, byte interDelay = 0); friend class SPIClass; private: uint8_t spiBitOrder; uint8_t spiDataMode; uint8_t spiClockDivider; uint16_t spiDelay; }; class SPIClass : public SPISettings { public: SPIClass(byte ssel, byte sck, byte mosi, byte miso); void begin(); void end(); void beginTransaction(SPISettings settings); void endTransaction(void); byte transfer(uint8_t data); void transfer(void *buf, size_t length); void setHardwarePins(byte ssel, byte sck, byte mosi, byte miso); protected: byte SPI0_SSEL; byte SPI0_SCK; byte SPI0_MOSI; byte SPI0_MISO; }; extern SPIClass SPI; #endif
#include <iostream> #include "Point.h" using namespace std; int main() { Point a(1, 2), b(3, 4); PointManagement pm; double dis = pm.getDistance(a, b); cout << dis << endl; }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) typedef long long ll; vector<ll> a,f; ll n; ll binarySearch_latest(bool (*callback)(ll, ll), ll userQuery = 0) { ll ng = -1; ll ok = 10e12; while(abs(ok - ng) > 1){ ll mid = (ok + ng) / 2; if (callback(mid, userQuery)){ ok = mid; } else { ng = mid; } } return ok; } bool judge1(ll arrValue, ll user){ ll ans = 0; for (int i = 0; i < n; i++) { ll sa = a[i]*f[i] - arrValue; if (sa <= 0) continue; ll tmp = sa / f[i]; if (sa % f[i] != 0) tmp++; ans += tmp; } return ans <= user; } int main() { ll k; cin >> n >> k; rep(i, n){ int tmp; cin >> tmp; a.push_back(tmp);} rep(i, n){ int tmp; cin >> tmp; f.push_back(tmp);} sort(a.begin(), a.end(), greater<ll>()); sort(f.begin(), f.end()); cout << binarySearch_latest(judge1, k) << endl; } /* KのサイズがでかいのでオーダーにKを含めることはできない。 (K回ループを回すことはできない) Aは降順、Fは昇順にして対応するのを担当するパターンが多分最適 理想的には、1/Fに対応する比率でAが分散するのが理想。小数計算は必須か?? 答えの候補の値 0 ~ 10^12を二分探索でいけるのでは・・・? */
/* filename: moparallelitem.cpp author: Sherri Harms last modified: 8/8/01 description: Class mop_item Inherited IMPLEMENTATION file for episodes. Values of this type are a composite of episode, support, and a list of occurrences; This implementation uses a list for the occurrences and a vector for episode. ****************************************************************************** Known bugs: The constraints are all disjuctive singular events. step 5 from alg 5 generate candidatges has not been implemented input validation is not done ******************************************************************************* Local Data Structures: Local variables: ***************************************************************************** parallel moitem operations include: constructors, relational operators, parallel moitem operations used to generate parallel moitemset fa[k], fc[k] generate candicates fca[k+1], and fcc[k+1] and generate the representative episodal association rules. *******************************************************************************/ #pragma warning(disable:4786) //#include "event.h" //#include "moitem.h" #include "moitemset.h" #include "moparallelitem.h" #include <vector> #include <algorithm> #include <iostream> #include <fstream> using namespace std; /*mop_item::~mop_item() { event_set::iterator i = episode.begin(); while(i != episode.end()) { (*i).clear(); i++; } episode.clear(); support = 0; mos.clear(); }*/ void mop_item::insertepisode(const event& e) { episode.push_back(e); } void mop_item::clear() //clear the moitem & its episode & closure; { event_set::iterator i = episode.begin(); while(i != episode.end()) { (*i).clear(); i++; } episode.clear(); mos.clear(); support = 0; } bool mop_item::contains_event(const event& A) const {//finds the first occurrence of an event bool found = false; for (event_set::const_iterator event_itr = episode.begin(); event_itr != episode.end(); ++event_itr) { if (A == *event_itr ) { found = true; break; } } return found; } bool mop_item::matchB(const event_set& B) const { bool constraint = true; event_set::const_iterator i = episode.begin(); while(i != episode.end() && constraint) { if (!binary_search(B.begin(), B.end(), *i) ) { //found an event that does not meet the constraints // - remove this episode //MUST BE SORTED FIRST _ WONT WORK FOR SERIAL constraint = false; } //if ++i; }//while return constraint; } //matchB bool mop_item::matchp() const //called when generating the next generation set of candidate episodes // only for parallel injunctive episodes { bool found = false; event_set::const_iterator result; event_set::const_iterator i = episode.begin(), j; event one; while(i != episode.end() && !found) { j = i; j++; one = *i; result = find(j, episode.end(), one); if (result != episode.end()) { //found an event that is already in the episode // - do not add this episode found = true; } //if ++i; }//while return found; } //matchp bool mop_item::does_contain(const moitem* Y) const { //serial is in the specified order //parallel is in lexigraphical order bool contains = true; const mop_item *pitemptr; pitemptr = static_cast<const mop_item*>(Y); event_set::const_iterator itr = episode.begin(); event_set::const_iterator Yi = pitemptr->episode.begin(); /*//testing: cout<<"Check out, cand = "<<*pitemptr<<endl; cout<<" moitem = "<<*this<<endl; system("pause"); */ do { event_set::const_iterator in = find(itr, episode.end(), (*Yi)); if (in == episode.end()) { contains = false; } else { Yi++; itr = in; itr++; } } while (contains && itr != episode.end() && Yi != pitemptr->episode.end()); if (itr == episode.end() && Yi != pitemptr->episode.end()) contains = false; return contains; } bool mop_item::does_contain(const moitem* Y, int& with_freq) const { bool contains = false; if (does_contain(Y)) { contains = true; with_freq=support; } else with_freq=0; return contains; } /*bool mop_item::doescontainany(const moitem* Y) const {return false;} */ void mop_item::bringinnew(int t) { occur now(t,t); mos.push_back(now); support++; } moitem* mop_item::getfirstsub(int k) const { moitem * sub = new mop_item; event_set::const_iterator epi_itr = episode.begin(); for (int i = 0; i<k;i++) { event P = *epi_itr; sub->insertepisode(P); ++epi_itr; } return sub; } moitem* mop_item::getsecondsub(int k) const { moitem * sub = new mop_item; event_set::const_iterator epi_itr = episode.begin(); for (int i = 0; i<k-1;i++) { event P = *epi_itr; sub->insertepisode(P); ++epi_itr; } ++epi_itr; event P = *epi_itr; sub->insertepisode(P); return sub; } void mop_item::recordmobetween(const moitem* fcsub1, const moitem* fcsub2, bool twins) {//parallel int start, stop; const mop_item *sub1ptr; sub1ptr = static_cast<const mop_item*>(fcsub1); const mop_item *sub2ptr; sub2ptr = static_cast<const mop_item*>(fcsub2); const_occur_list_ITR sub2itr = sub2ptr->mos.begin(); const_occur_list_ITR sub1itr = sub1ptr->mos.begin(); if (twins) sub2itr++; const_occur_list_ITR first, second; bool order; if (sub2itr != sub2ptr->mos.end()) { do { //get the first starting time if ( (*sub1itr).get_start() <= (*sub2itr).get_start() ) { order = true; first = sub1itr; second = sub2itr; } else { order = false; first = sub2itr; second = sub1itr; } //find the closest stopping time bool donebig = false; while (!donebig && !twins &&(*first).get_start() <= (*second).get_start() ) { first++; if (first == sub1ptr->mos.end() && order || first == sub2ptr->mos.end() && !order ) donebig = true; } if (!twins) first--;//went one to far in the last loop start = (*first).get_start(); bool equalstart = false; if ( (*first).get_start() == (*second).get_start() ) equalstart = true; if ((*first).get_stop() <= (*second).get_stop()) { stop = (*second).get_stop(); } else { stop = (*first).get_stop(); } occur one(start,stop); mos.push_back(one); //could update support here, but I chose to do it seperately based on window size if (order) { sub1itr=first; sub1itr++; if (twins || equalstart) sub2itr++; } else { sub2itr=first; sub2itr++; if (equalstart) sub1itr++; } }while (sub1itr != sub1ptr->mos.end() && sub2itr != sub2ptr->mos.end()); }//if another item2 } moitem* mop_item::generate_parallel_candidate(const event& E) const { moitem * Z = new mop_item; for (event_set::const_iterator epi_itr = episode.begin(); epi_itr != episode.end(); ++epi_itr) { event P = *epi_itr; Z->insertepisode(P); } Z->insertepisode(E); return Z; } void mop_item::sortit() { sort(episode.begin(), episode.end()); } bool mop_item::equalitem(const moitem* Y) const { const mop_item* pitemptr = static_cast<const mop_item*>(Y); return (episode == pitemptr->episode); } bool mop_item::fast_gen_support_subs(const moitemset& f_l, int k) const { bool support = true; int y = 0,x=0; while (support && y < k-1) { moitem * beta = new mop_item; for (x =0;x<y;x++) beta->insertepisode(episode[x]); for (x = y; x<k;x++) { beta->insertepisode(episode[x+1]); } //Testing //cout<<"beta = "; //beta->output_episode(cout); //cout<<endl; if (!f_l.does_contain_parallel(beta)) { support = false; } y++; delete beta; } return support; }//end fast_gen_support_sub bool mop_item::issubsetofY(const moitem* Y) const { //return true if the current moitem is a subset of moitem Y const mop_item* pitemptr = static_cast<const mop_item*>(Y); bool subset = true; event_set::const_iterator itr = episode.begin(); event_set::const_iterator Yi = pitemptr->episode.begin(); event_set::const_iterator Yend = pitemptr->episode.end(); do { event_set::const_iterator in = find(Yi, Yend, (*itr)); if (in == pitemptr->episode.end()) { subset = false; } else { Yi = in; Yi++; itr++; } } while (subset && itr != episode.end() && Yi != pitemptr->episode.end()); if (subset && itr != episode.end() && Yi == pitemptr->episode.end()) subset = false; return subset; } event_set mop_item::get_episode() const { return episode; } event mop_item::get_first_event() const { return *episode.begin(); } event mop_item::get_last_event() const { event_set::const_iterator i = episode.end(); i--; return *i; } event mop_item::get_ith_event(int i) const //return the ith event in the moitem { return episode[i]; } int mop_item::getepisodelen() const { return episode.size(); } void mop_item::create_1_ante(moitemset& A, const event_set& T) const {//put the events in the current moitem that are in the constraint file T //as separate events into the moitemset A for (event_set::const_iterator i = episode.begin(); i != episode.end(); i++) { if ( i->matchB(T)) { moitem * current = new mop_item; current->insertepisode(*i); A.insertitem(current); } } }//create_1_ante //double mop_item::get_max_support(const fc_type& fc, int i, int k, char type) //get the max support = support of a larger episode that contains this episode if there is one, otherwise 0 double mop_item::get_max_support(const fc_type& fc) { double support = 0; /* if (i >= k) return support; else { int j = k; while (j > i) { double levelsupport; levelsupport = fc[j].computelevelsupport(this); if (levelsupport > support) support = levelsupport; j--; } }*/ return support; }//get_max_support mop_item::mop_item( ) :moitem() { event empty; episode.push_back(empty); episode.clear(); } void mop_item::output_episode(ostream& outs) const { outs<<"{"; event_set::const_iterator e = episode.begin(); if (e != episode.end()) { outs<<*e; ++e; } while (e != episode.end()) { outs<<", "; outs<<*e; ++e; } outs<<"}"; } //output_episode void mop_item::output(ostream& outs) const { output_episode(outs); /* outs<<" occurs at: "; occur_list::const_iterator e = mos.begin(); if (e != mos.end()) { outs<<*e; ++e; } while (e != mos.end()) { outs<<", "; outs<<*e; ++e; } */ outs<<" support: "<<support<<endl; } bool mop_item::matchs() const {return false;} t_stamp_vec mop_item::get_episode(int ignore) const { t_stamp_vec temp; return temp; } time_stamp mop_item::get_ith_time_stamp(int i) const { time_stamp temp; return temp; } void mop_item::insertepisode(const time_stamp& t) {} time_stamp mop_item::get_last_time_stamp() const //return the last timestamp in the moitem { time_stamp temp; return temp; } time_stamp mop_item::get_first_time_stamp() const { time_stamp temp; return temp; } moitem* mop_item::generate_serial_candidate(const moitem* E) const { moitem * ptr = new mop_item; return ptr; } moitem* mop_item::generate_serial_rule_candidate(const moitem* E) const //generate an moitem candidate in the rule cand generation phase - has no closures anymore! { moitem * ptr = new mop_item; return ptr; } moitem* mop_item::get_last_episode() const { moitem* ptr = new mop_item; return ptr; } /*moitem* mop_item::get_last_split_episode() const //return the last timestamp episode as a new moitem ptr //used in generating serial rules { moitem* ptr = new mop_item; return ptr; }*/ int mop_item::getnumberofevents() const {return 0;} moitem* mop_item::getsub1withintimestamp(int k) const { moitem* p = new mop_item; return p; } moitem* mop_item::getsub2withintimestamp(int k) const { moitem* p = new mop_item; return p; } void mop_item::recordtimestamps(const moitem* fcsub1, const moitem* fcsub2){} //calculate the timestamps for this item (where the events occur together)
class Solution { public: int maxResult(vector<int>& nums, int k) { long curr=0; deque<int> dq; for(int i=nums.size()-1;i>=0;i--) { curr=nums[i]+(dq.empty()?0:nums[dq.front()]); while(!dq.empty()&&curr>nums[dq.back()]) dq.pop_back(); dq.push_back(i); if(dq.front()>=i+k) dq.pop_front(); nums[i]=curr; } return curr; } };
class ParachuteBase; class ParachuteWest: ParachuteBase { model = "\z\addons\dayz_epoch_v\vehicles\chute\PARA.p3d"; };
#ifndef RANDOMNUMBERGENERATOR_H #define RANDOMNUMBERGENERATOR_H #include "boost/random.hpp" #include "boost/generator_iterator.hpp" class RandomNumberGenerator { private: boost::mt19937 _rng; public: int GenerateRandomNumber(int bottonLimit, int upLimit); }; #endif
#include <iostream> #include <vector> #include <string> using namespace std; vector<char> stLeft; vector<char> stRight; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); string input; cin >> input; for(int i = 0; i < input.size(); i++){ stLeft.push_back(input.at(i)); } int n; cin >> n; while(n--){ char cmd; cin >> cmd; char tp; switch(cmd){ case'L': if(!stLeft.empty()){ tp = stLeft.back(); stLeft.pop_back(); stRight.push_back(tp); } break; case'D': if(!stRight.empty()){ tp = stRight.back(); stRight.pop_back(); stLeft.push_back(tp); } break; case'B': if(!stLeft.empty()){ stLeft.pop_back(); } break; case'P': cin >> tp; stLeft.push_back(tp); break; default: break; } } for(char ch : stLeft){ cout << ch; } while(!stRight.empty()){ cout << stRight.back(); stRight.pop_back(); } return 0; }
#pragma once #include <string> #include <vector> #include "bass.h" class Audio { public: static void init(); Audio(); Audio(std::string_view filepath); void loadFromFile(std::string_view filepath); void play(); void restart(); void pause(); void stop(); bool isPlaying() const; void setVolume(float percent); float getVolume() const; void setPosition(float percent); float getPosition(); double getLength(); const std::vector<float>& getFFT(); static const unsigned int s_SamplingRate; static const std::vector<const char*> s_AvailablePatterns; private: std::vector<float> m_FFT; long m_Length; bool m_IsPlaying; unsigned long m_Channel; };
// // CubeMap.cpp // Odin.MacOSX // // Created by Daniel on 27/10/15. // Copyright (c) 2015 DG. All rights reserved. // #include "CubeMap.h" #include "LogManager.h" #include "DebugIL.h" #include <IL/il.h> #if defined ODIN_DEBUG #include <IL/ilu.h> #endif #include <memory> namespace odin { namespace resource { Cubemap::Cubemap() { } Cubemap::~Cubemap() { // Delete a texture if (m_texture) { render::lib::deleteTextures(1, &m_texture); } } bool Cubemap::loadFromFile(const std::string& filenamePX, const std::string& filenameNX, const std::string& filenamePY, const std::string& filenameNY, const std::string& filenamePZ, const std::string& filenameNZ, I32 filter, I32 wrapMode, bool mipmap) { std::string files[6]; files[0] = filenamePX; files[1] = filenameNX; files[2] = filenamePY; files[3] = filenameNY; files[4] = filenamePZ; files[5] = filenameNZ; UI8* data[6]; // pointers to the 6 textures data UI32 images[6]; // image handles ILDEBUG(ilGenImages(6, images)); ILDEBUG(ilOriginFunc(IL_ORIGIN_UPPER_LEFT)); UI8 defaultData[] = {255,0,255,255}; // default texture data (in case of failure) bool success = true; UI32 width = 0; UI32 height = 0; for(UI32 i = 0; i < 6; ++i) { // Load Image ILDEBUG(ilBindImage(images[i])); bool loaded = ILDEBUG(ilLoadImage(files[i].c_str())); if (loaded) { m_names[i] = files[i]; // Check if the textures have the same size if (i == 0) { m_width = ILDEBUG(ilGetInteger(IL_IMAGE_WIDTH)); m_height = ILDEBUG(ilGetInteger(IL_IMAGE_HEIGHT)); } else { width = ILDEBUG(ilGetInteger(IL_IMAGE_WIDTH)); height = ILDEBUG(ilGetInteger(IL_IMAGE_HEIGHT)); if (m_width != width && m_height != height) { LOG_ERROR("Cubemap textures must have the same size. Switching to default texture"); success = false; } } ILDEBUG(ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE)); data[i] = ILDEBUG(ilGetData()); // Print texture info UI32 bytesPerPixel = ILDEBUG(ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL)); std::string imageFormat; UI32 imgFormat = ILDEBUG(ilGetInteger(IL_IMAGE_FORMAT)); switch(imgFormat) { case IL_COLOR_INDEX : imageFormat = "IL_COLOR_INDEX"; break; case IL_ALPHA : imageFormat = "IL_ALPHA"; break; case IL_RGB : imageFormat = "IL_RGB"; break; case IL_RGBA : imageFormat = "IL_RGBA"; break; case IL_BGR : imageFormat = "IL_BGR"; break; case IL_BGRA : imageFormat = "IL_BGRA"; break; case IL_LUMINANCE : imageFormat = "IL_LUMINANCE"; break; case IL_LUMINANCE_ALPHA : imageFormat = "IL_LUMINANCE_ALPHA"; break; } std::string imageType; UI32 imgType = ILDEBUG(ilGetInteger(IL_IMAGE_TYPE)); switch(imgType) { case IL_BYTE : imageType = "IL_BYTE"; break; case IL_UNSIGNED_BYTE : imageType = "IL_UNSIGNED_BYTE"; break; case IL_SHORT : imageType = "IL_SHORT"; break; case IL_UNSIGNED_SHORT : imageType = "IL_UNSIGNED_SHORT"; break; case IL_INT : imageType = "IL_INT"; break; case IL_UNSIGNED_INT : imageType = "IL_UNSIGNED_INT"; break; case IL_FLOAT : imageType = "IL_FLOAT"; break; case IL_DOUBLE : imageType = "IL_DOUBLE"; break; case IL_HALF : imageType = "IL_HALF"; break; } LOG_INFO("DEVIL: Image texture successfully loaded: %s\n" "Width: %d, Height: %d, Bytes per Pixel: %d\n" "Format: %s, Data type: %s" , files[i].c_str(), m_width, m_height, bytesPerPixel, imageFormat.c_str(), imageType.c_str()); } else { LOG_ERROR("Could not load cubemap file: %s. Switching to default texture", files[i].c_str()); success = false; } if (!success) break; } if (success) { I32 minFilter = filter; if (filter == ODIN_LINEAR && mipmap) { minFilter = ODIN_LINEAR_MIPMAP_LINEAR; } else if (filter == ODIN_NEAREST && mipmap) { minFilter = ODIN_NEAREST_MIPMAP_LINEAR; } success = loadFromMemory(width, height, data[0], data[1], data[2], data[3], data[4], data[5], ODIN_RGBA, ODIN_RGBA, ODIN_UNSIGNED_BYTE, minFilter, filter, wrapMode, mipmap); } else { success = loadFromMemory(1, 1, defaultData, defaultData, defaultData, defaultData, defaultData, defaultData); } ILDEBUG(ilDeleteImages(6, images)); return success; } bool Cubemap::loadFromMemory(UI32 width, UI32 height, const void* dataPX, const void* dataNX, const void* dataPY, const void* dataNY, const void* dataPZ, const void* dataNZ, I32 internalFormat, UI32 pixelFormat, UI32 pixelType, I32 minFilter, I32 magFilter, I32 wrapMode, bool mipmap) { m_width = width; m_height = height; const void* data[6] = { dataPX, dataNX, dataPY, dataNY, dataPZ, dataNZ }; render::lib::genTextures(1, &m_texture); if (m_texture) { setFiltering(minFilter, magFilter); setWrapMode(wrapMode); bind(); for (UI32 i = 0; i < 6; ++i) { render::lib::texImage2D(ODIN_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat, m_width, m_height, 0, pixelFormat, pixelType, data[i]); } unbind(); if (mipmap) generateMipmaps(); return true; } else return false; } UI32 Cubemap::getWidth() const { return m_width; } UI32 Cubemap::getHeight() const { return m_height; } void Cubemap::bind() const { render::lib::bindTexture(ODIN_TEXTURE_CUBE_MAP, m_texture); } void Cubemap::unbind() const { render::lib::bindTexture(ODIN_TEXTURE_CUBE_MAP, 0); } void Cubemap::generateMipmaps() const { bind(); render::lib::generateMipmap(ODIN_TEXTURE_CUBE_MAP); unbind(); } void Cubemap::setWrapMode(I32 mode) const { bind(); render::lib::texParameteri(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_WRAP_S, mode); render::lib::texParameteri(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_WRAP_T, mode); render::lib::texParameteri(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_WRAP_R, mode); unbind(); } void Cubemap::setBorderColor(const math::vec4& borderColor) const { bind(); float borderCol[] = { borderColor.x, borderColor.y, borderColor.z, borderColor.w }; render::lib::texParameterfv(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_BORDER_COLOR, borderCol); unbind(); } void Cubemap::setFiltering(I32 mode) const { bind(); render::lib::texParameteri(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_MIN_FILTER, mode); render::lib::texParameteri(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_MAG_FILTER, mode); unbind(); } void Cubemap::setFiltering(I32 min, I32 mag) const { bind(); render::lib::texParameteri(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_MIN_FILTER, min); render::lib::texParameteri(ODIN_TEXTURE_CUBE_MAP, ODIN_TEXTURE_MAG_FILTER, mag); unbind(); } } }
#pragma once #define MAKE_KEY(a,b) {#a,b}, namespace input { struct { char* name; int value; } keys[] = { MAKE_KEY(KEY_ESCAPE , 0x01) MAKE_KEY(KEY_1 , 0x02) MAKE_KEY(KEY_2 , 0x03) MAKE_KEY(KEY_3 , 0x04) MAKE_KEY(KEY_4 , 0x05) MAKE_KEY(KEY_5 , 0x06) MAKE_KEY(KEY_6 , 0x07) MAKE_KEY(KEY_7 , 0x08) MAKE_KEY(KEY_8 , 0x09) MAKE_KEY(KEY_9 , 0x0A) MAKE_KEY(KEY_0 , 0x0B) MAKE_KEY(KEY_MINUS , 0x0C) MAKE_KEY(KEY_EQUALS , 0x0D) MAKE_KEY(KEY_BACK , 0x0E) MAKE_KEY(KEY_TAB , 0x0F) MAKE_KEY(KEY_Q , 0x10) MAKE_KEY(KEY_W , 0x11) MAKE_KEY(KEY_E , 0x12) MAKE_KEY(KEY_R , 0x13) MAKE_KEY(KEY_T , 0x14) MAKE_KEY(KEY_Y , 0x15) MAKE_KEY(KEY_U , 0x16) MAKE_KEY(KEY_I , 0x17) MAKE_KEY(KEY_O , 0x18) MAKE_KEY(KEY_P , 0x19) MAKE_KEY(KEY_LBRACKET , 0x1A) MAKE_KEY(KEY_RBRACKET , 0x1B) MAKE_KEY(KEY_RETURN , 0x1C) MAKE_KEY(KEY_LCONTROL , 0x1D) MAKE_KEY(KEY_A , 0x1E) MAKE_KEY(KEY_S , 0x1F) MAKE_KEY(KEY_D , 0x20) MAKE_KEY(KEY_F , 0x21) MAKE_KEY(KEY_G , 0x22) MAKE_KEY(KEY_H , 0x23) MAKE_KEY(KEY_J , 0x24) MAKE_KEY(KEY_K , 0x25) MAKE_KEY(KEY_L , 0x26) MAKE_KEY(KEY_SEMICOLON, 0x27) MAKE_KEY(KEY_APOSTROPHE , 0x28) MAKE_KEY(KEY_GRAVE , 0x29) MAKE_KEY(KEY_LSHIFT , 0x2A) MAKE_KEY(KEY_BACKSLASH , 0x2B) MAKE_KEY(KEY_Z , 0x2C) MAKE_KEY(KEY_X , 0x2D) MAKE_KEY(KEY_C , 0x2E) MAKE_KEY(KEY_V , 0x2F) MAKE_KEY(KEY_B , 0x30) MAKE_KEY(KEY_N , 0x31) MAKE_KEY(KEY_M , 0x32) MAKE_KEY(KEY_COMMA , 0x33) MAKE_KEY(KEY_PERIOD , 0x34) MAKE_KEY(KEY_SLASH , 0x35) MAKE_KEY(KEY_RSHIFT , 0x36) MAKE_KEY(KEY_MULTIPLY , 0x37) MAKE_KEY(KEY_LMENU , 0x38) MAKE_KEY(KEY_SPACE , 0x39) MAKE_KEY(KEY_CAPITAL , 0x3A) MAKE_KEY(KEY_F1 , 0x3B) MAKE_KEY(KEY_F2 , 0x3C) MAKE_KEY(KEY_F3 , 0x3D) MAKE_KEY(KEY_F4 , 0x3E) MAKE_KEY(KEY_F5 , 0x3F) MAKE_KEY(KEY_F6 , 0x40) MAKE_KEY(KEY_F7 , 0x41) MAKE_KEY(KEY_F8 , 0x42) MAKE_KEY(KEY_F9 , 0x43) MAKE_KEY(KEY_F10 , 0x44) MAKE_KEY(KEY_NUMLOCK , 0x45) MAKE_KEY(KEY_SCROLL , 0x46) MAKE_KEY(KEY_NUMPAD7 , 0x47) MAKE_KEY(KEY_NUMPAD8 , 0x48) MAKE_KEY(KEY_NUMPAD9 , 0x49) MAKE_KEY(KEY_SUBTRACT , 0x4A) MAKE_KEY(KEY_NUMPAD4 , 0x4B) MAKE_KEY(KEY_NUMPAD5 , 0x4C) MAKE_KEY(KEY_NUMPAD6 , 0x4D) MAKE_KEY(KEY_ADD , 0x4E) MAKE_KEY(KEY_NUMPAD1 , 0x4F) MAKE_KEY(KEY_NUMPAD2 , 0x50) MAKE_KEY(KEY_NUMPAD3 , 0x51) MAKE_KEY(KEY_NUMPAD0 , 0x52) MAKE_KEY(KEY_DECIMAL , 0x53) MAKE_KEY(KEY_OEM_102 , 0x56) MAKE_KEY(KEY_F11 , 0x57) MAKE_KEY(KEY_F12 , 0x58) MAKE_KEY(KEY_F13 , 0x64) MAKE_KEY(KEY_F14 , 0x65) MAKE_KEY(KEY_F15 , 0x66) MAKE_KEY(KEY_KANA , 0x70) MAKE_KEY(KEY_ABNT_C1 , 0x73) MAKE_KEY(KEY_CONVERT , 0x79) MAKE_KEY(KEY_NOCONVERT , 0x7B) MAKE_KEY(KEY_YEN , 0x7D) MAKE_KEY(KEY_ABNT_C2 , 0x7E) MAKE_KEY(KEY_NUMPADEQUALS , 0x8D) MAKE_KEY(KEY_PREVTRACK , 0x90) MAKE_KEY(KEY_AT , 0x91) MAKE_KEY(KEY_COLON , 0x92) MAKE_KEY(KEY_UNDERLINE , 0x93) MAKE_KEY(KEY_KANJI , 0x94) MAKE_KEY(KEY_STOP , 0x95) MAKE_KEY(KEY_AX , 0x96) MAKE_KEY(KEY_UNLABELED , 0x97) MAKE_KEY(KEY_NEXTTRACK , 0x99) MAKE_KEY(KEY_NUMPADENTER , 0x9C) MAKE_KEY(KEY_RCONTROL , 0x9D) MAKE_KEY(KEY_MUTE , 0xA0) MAKE_KEY(KEY_CALCULATOR , 0xA1) MAKE_KEY(KEY_PLAYPAUSE , 0xA2) MAKE_KEY(KEY_MEDIASTOP , 0xA4) MAKE_KEY(KEY_VOLUMEDOWN , 0xAE) MAKE_KEY(KEY_VOLUMEUP , 0xB0) MAKE_KEY(KEY_WEBHOME , 0xB2) MAKE_KEY(KEY_NUMPADCOMMA , 0xB3) /* , on numeric keypad (NEC PC98) */ MAKE_KEY(KEY_DIVIDE , 0xB5) /* / on numeric keypad */ MAKE_KEY(KEY_SYSRQ , 0xB7) MAKE_KEY(KEY_RMENU , 0xB8) /* right Alt */ MAKE_KEY(KEY_PAUSE , 0xC5) /* Pause */ MAKE_KEY(KEY_HOME , 0xC7) /* Home on arrow keypad */ MAKE_KEY(KEY_UP , 0xC8) /* UpArrow on arrow keypad */ MAKE_KEY(KEY_PRIOR , 0xC9) /* PgUp on arrow keypad */ MAKE_KEY(KEY_LEFT , 0xCB) /* LeftArrow on arrow keypad */ MAKE_KEY(KEY_RIGHT , 0xCD) /* RightArrow on arrow keypad */ MAKE_KEY(KEY_END , 0xCF) /* End on arrow keypad */ MAKE_KEY(KEY_DOWN , 0xD0) /* DownArrow on arrow keypad */ MAKE_KEY(KEY_NEXT , 0xD1) /* PgDn on arrow keypad */ MAKE_KEY(KEY_INSERT , 0xD2) /* Insert on arrow keypad */ MAKE_KEY(KEY_DELETE , 0xD3) /* Delete on arrow keypad */ MAKE_KEY(KEY_LWIN , 0xDB) /* Left Windows key */ MAKE_KEY(KEY_RWIN , 0xDC) /* Right Windows key */ MAKE_KEY(KEY_APPS , 0xDD) /* AppMenu key */ MAKE_KEY(KEY_POWER , 0xDE) /* System Power */ MAKE_KEY(KEY_SLEEP , 0xDF) /* System Sleep */ MAKE_KEY(KEY_WAKE , 0xE3) /* System Wake */ MAKE_KEY(KEY_WEBSEARCH , 0xE5) /* Web Search */ MAKE_KEY(KEY_WEBFAVORITES, 0xE6) /* Web Favorites */ MAKE_KEY(KEY_WEBREFRESH , 0xE7) /* Web Refresh */ MAKE_KEY(KEY_WEBSTOP , 0xE8) /* Web Stop */ MAKE_KEY(KEY_WEBFORWARD , 0xE9) /* Web Forward */ MAKE_KEY(KEY_WEBBACK , 0xEA) /* Web Back */ MAKE_KEY(KEY_MYCOMPUTER , 0xEB) /* My Computer */ MAKE_KEY(KEY_MAIL , 0xEC) /* Mail */ MAKE_KEY(KEY_MEDIASELECT , 0xED) /* Media Select */ MAKE_KEY(BUTTON_0 , 0xF0) /* Mouse Button 0 */ MAKE_KEY(BUTTON_1 , 0xF1) /* Mouse Button 1 */ MAKE_KEY(BUTTON_2 , 0xF2) /* Mouse Button 2 */ MAKE_KEY(BUTTON_3 , 0xF3) /* Mouse Button 3 */ MAKE_KEY(KEY_MWHEELUP , 0xF4) /* Mouse Wheel Up */ MAKE_KEY(KEY_MWHEELDN , 0xF5) /* Mouse Wheel Down */ /* * Alternate names for keys, to facilitate transition from DOS. */ MAKE_KEY(KEY_BACKSPACE , DIK_BACK) /* backspace */ MAKE_KEY(KEY_NUMPADSTAR , DIK_MULTIPLY) /* * on numeric keypad */ MAKE_KEY(KEY_LALT , DIK_LMENU) /* left Alt */ MAKE_KEY(KEY_CAPSLOCK , DIK_CAPITAL) /* CapsLock */ MAKE_KEY(KEY_NUMPADMINUS , DIK_SUBTRACT) /* - on numeric keypad */ MAKE_KEY(KEY_NUMPADPLUS , DIK_ADD) /* + on numeric keypad */ MAKE_KEY(KEY_NUMPADPERIOD , DIK_DECIMAL) /* . on numeric keypad */ MAKE_KEY(KEY_NUMPADSLASH , DIK_DIVIDE) /* / on numeric keypad */ MAKE_KEY(KEY_RALT , DIK_RMENU) /* right Alt */ MAKE_KEY(KEY_UPARROW , DIK_UP) /* UpArrow on arrow keypad */ MAKE_KEY(KEY_PGUP , DIK_PRIOR) /* PgUp on arrow keypad */ MAKE_KEY(KEY_LEFTARROW , DIK_LEFT) /* LeftArrow on arrow keypad */ MAKE_KEY(KEY_RIGHTARROW , DIK_RIGHT) /* RightArrow on arrow keypad */ MAKE_KEY(KEY_DOWNARROW , DIK_DOWN) /* DownArrow on arrow keypad */ MAKE_KEY(KEY_PGDN , DIK_NEXT) /* PgDn on arrow keypad */ { NULL, -1 } }; }
// // Created by user24 on 2019/10/17. // #define LIST_NUM 8 <<<<<<< HEAD ======= >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 typedef int ElemType; #include <cstring> #include "SeqList.h" <<<<<<< HEAD #include "SeqList.cpp" using std::to_string; void clear() { #ifdef _WIN32 system("cls"); #else system("clear"); #endif ======= using std::to_string; using std::cin; using std::cout; using std::endl; using std::exception; void clear() { #ifdef _WIN32 // on Windows Command Line system("cls"); #else // on Unix and Unix-like shell system("clear"); #endif >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 } template<typename T> void displayMenu(SeqList<T> *seqLists[], int index) { <<<<<<< HEAD printf("----------------------------------------\n"); printf("** Current Index is %d **\n", index); if (seqLists[index] == nullptr) { ======= // Rewrite menu display function with printf. printf("----------------------------------------\n"); printf("** Current Index is %d **\n", index); if (seqLists[index] == nullptr ) { >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 printf("%-20s%-20s\n", "1. InitList", "20. ChangeIndex"); } else { printf("%-20s%-20s\n", "1. InitList", "10. ListInsert"); printf("%-20s%-20s\n", "2. DestroyList", "11. ListDelete"); printf("%-20s%-20s\n", "3. ClearList", "12. ListTraverse"); printf("%-20s%-20s\n", "4. ListEmpty", "13. Push"); printf("%-20s%-20s\n", "5. ListLength", "14. Pop"); printf("%-20s%-20s\n", "6. GetElem", "15. Save"); printf("%-20s%-20s\n", "7. LocateElem", "16. Load"); printf("%-20s%-20s\n", "8. PriorElem", "20. ChangeIndex"); printf("%-20s%-20s\n", "9. NextElem", ""); } } int main() { <<<<<<< HEAD ======= // Initialize a pointer array for multi-list management. >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 SeqList<ElemType> *seqLists[LIST_NUM]; memset(seqLists, 0, sizeof(seqLists)); int option = 1; int index = 0; clear(); while (option) { try { displayMenu(seqLists, index); <<<<<<< HEAD cin >> option; clear(); if (seqLists[index] == nullptr && (option != 1 && option != 20 && option != 0)) { ======= cin >> option; // accept keyboard input as option clear(); if (seqLists[index] == nullptr && (option != 1 && option != 20 && option != 0)) { // To avoid nullptr being operated. >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 cout << "Exception: " << "List Not Initialized!" << endl; continue; } switch (option) { case 0: { break; } case 1: { clear(); cout << "InitList" << endl; seqLists[index] = new SeqList<ElemType>(); break; } case 2: { clear(); cout << "DestroyList" << endl; <<<<<<< HEAD SeqList<ElemType>::destroy(&seqLists[index]); ======= SeqList<ElemType>::destroy(*seqLists[index]); // Free space seqLists[index]= nullptr; // Assign nullptr >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 break; } case 3: { clear(); cout << "ClearList" << endl; seqLists[index]->clear(); break; } case 4: { clear(); cout << "ListEmpty" << endl; cout << (seqLists[index]->isEmpty() ? "True" : "False") << endl; break; } case 5: { clear(); cout << "ListLength" << endl; cout << seqLists[index]->getLength() << endl; break; } case 6: { clear(); cout << "GetElem" << endl; int i = 0; cin >> i; cout << seqLists[index]->get(i) << endl; break; } case 7: { clear(); cout << "LocateElem" << endl; ElemType i = 0; cin >> i; cout << seqLists[index]->locate( i, <<<<<<< HEAD ======= // Lambda expression introduced in C++11; >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 [](ElemType &a, ElemType &b) -> bool { return a > b; }) << endl; break; } case 8: { clear(); cout << "PriorElem" << endl; ElemType i = 0; cin >> i; cout << seqLists[index]->prior(i) << endl; break; } case 9: { clear(); cout << "NextElem" << endl; ElemType i = 0; cin >> i; cout << seqLists[index]->next(i) << endl; break; } case 10: { clear(); cout << "ListInsert" << endl; int i = 0; ElemType v = 0; cin >> i; cin >> v; seqLists[index]->insertBefore(i, v); break; } case 11: { clear(); cout << "ListDelete" << endl; int i = 0; cin >> i; <<<<<<< HEAD cout<<seqLists[index]->remove(i) <<endl; ======= cout << seqLists[index]->remove(i) << endl; >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 break; } case 12: { clear(); cout << "ListTraverse" << endl; seqLists[index] ->forEach([](ElemType &v) -> void { <<<<<<< HEAD cout << v << " "; ======= cout << v << " "; // Lambda expression introduced in C++11; >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 }); cout << endl; break; } case 13: { clear(); cout << "Push" << endl; ElemType v; cin >> v; seqLists[index]->push(v); break; } case 14: { clear(); cout << "Pop" << endl; ElemType v = seqLists[index]->pop(); cout << v << endl; break; } case 15: { clear(); cout << "Save" << endl; seqLists[index]->save(to_string(index) + ".sav"); break; } case 16: { clear(); cout << "Load" << endl; seqLists[index]->load(to_string(index) + ".sav"); break; } case 20 : { clear(); cout << "ChangeIndex" << endl; <<<<<<< HEAD cin >> index; continue; } default: { ======= int i; cin >> i; if (i>0 && i<LIST_NUM) { index = i; // Avoid overstepping. } else { cout << "Invalid index" << endl; } continue; } default: { break; >>>>>>> 6f64abf56672e2083b6d811935c95993048fedb0 } } } catch (exception &e) { cout << "RuntimeException: " << e.what() << endl; } } }
// core.hpp // // Copyright 2010 Kevin Pors <krpors@users.sf.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA. #ifndef CORE_HPP #define CORE_HPP #include <SFML/Window.hpp> #include <iostream> #include <math.h> #include <algorithm> #include <vector> #include <GL/gl.h> namespace ogle { /** * Color class. */ class Color { private: /// Red component, clamped to [0.0f, 1.0f] GLclampf m_r; /// Green component, clamped to [0.0f, 1.0f] GLclampf m_g; /// Blue component, clamped to [0.0f, 1.0f] GLclampf m_b; /// Alpha component, clamped to [0.0f, 1.0f] GLclampf m_a; public: /** * Creates a color instance. * * @param r The red component (clamped). Default value is 0.0f. * @param g The green component (clamped). Default value is 0.0f. * @param b The blue component (clamped). Default value is 0.0f. * @param a The alpha component (clamped). Default value is 1.0f (fully opaque). */ Color(const GLclampf& r = 0.0f, const GLclampf& g = 0.0f, const GLclampf& b = 0.0f, const GLclampf& a = 1.0f); ~Color(); /** * Sets the red component. * * @param r The red component (clamped). */ void setR(const GLclampf& r); /** * Sets the green component. * * @param r The green component (clamped). */ void setG(const GLclampf& g); /** * Sets the blue component. * * @param r The blue component (clamped). */ void setB(const GLclampf& b); /** * Sets the alpha component. * * @param r The alpha component (clamped). */ void setA(const GLclampf& a); /** * Gets the red component. * * @return The red component, clamped. */ GLclampf getR() const; /** * Gets the red component. * * @return The red component, clamped. */ GLclampf getG() const; /** * Gets the red component. * * @return The red component, clamped. */ GLclampf getB() const; /** * Gets the red component. * * @return The red component, clamped. */ GLclampf getA() const; // Predefined colors: /// Color black. static const Color BLACK; /// Color red. static const Color RED; /// Color green. static const Color GREEN; /// Color blue. static const Color BLUE; /// Color orange. static const Color ORANGE; /// Color yellow. static const Color YELLOW; }; //============================================================================== /** * Rectangle class, which represents a quad in two-dimensional space. It's built * up using four numbers: (x, y) - (w, h). */ class Rect { public: /** * Creates this rect. */ Rect(const GLfloat& x = 0.0f, const GLfloat& y = 0.0f, const GLfloat& w = 0.0f, const GLfloat& h = 0.0f); /** * KKND. */ ~Rect(); /// First x coordinate, ideally something like bottom-left. GLfloat x; /// First y coordinate, ideally something like bottom-left. GLfloat y; /// Width of the rectangle. GLfloat w; /// Height of the rectangle. GLfloat h; /** * This function checks if the current rectangle is intersecting another * rectangle, i.e. if it's colliding. * * @param other The other rectangle to test with. Returns true if they * intersect - or collide -, and returns false if they do not. */ bool intersects(const Rect& other) const; }; //============================================================================== /** * Base object for anything (2D) renderable in Ogle. */ class Object { protected: /// The x coordinate of this object. GLfloat m_x; /// The y coordinate of this object. GLfloat m_y; /// The z coordinate of this object. GLfloat m_z; /// Width of this object. GLfloat m_width; /// Height of this object. GLfloat m_height; /// Whether this object should react on collisions or not. bool m_collisionEligible; /// The object's boundary box. Rect m_boundaryBox; public: /** * Constructs a brand new Object, with the specified coordinates. * * @param x The x coordinate, or 0.0f when not specified. * @param y The y coordinate, or 0.0f when not specified. * @param z The z coordinate, or 0.0f when not specified. */ Object(const GLfloat& x = 0.0f, const GLfloat& y = 0.0f, const GLfloat& z = 0.0f); /** * Destroys this object. */ virtual ~Object(); /** * Sets the position using a single call. * * @param x The x coordinate, or 0.0f when not specified. * @param y The y coordinate, or 0.0f when not specified. * @param z The z coordinate, or 0.0f when not specified. */ void setPosition(const GLfloat& x = 0.0f, const GLfloat& y = 0.0f, const GLfloat& z = 0.0f); /** * Sets the x position of this object. * * @param x the x position. */ void setX(const GLfloat& x); /** * Sets the y position of this object. * * @param y the y position. */ void setY(const GLfloat& y); /** * Sets the z position of this object. * * @param z the z position. */ void setZ(const GLfloat& z); /** * Sets the width. May or may not be applicable, depending on the subclass. * * @param w The width. */ void setWidth(const GLfloat& w); /** * Sets the width. May or may not be applicable, depending on the subclass. * * @param h The height. */ void setHeight(const GLfloat& h); /** * Sets whether this object is eligible for collision detection. * @param eligible True when this object is suitable for collision detection, * or false if not. */ void setCollisionEligible(bool eligible); const GLfloat& getX() const; const GLfloat& getY() const; const GLfloat& getZ() const; const GLfloat& getWidth() const; const GLfloat& getHeight() const; bool isCollisionEligible() const; /** * Gets the boundary of this object as a rectangle. This can be used for * simple boundary box collision detection. The boundary of this object * is 'calculated' each time this function is called. The object reference * remains the same, so only the properties of the returned Rect are changed, * not the Rect object itself. * * @return The boundary of this single object as a Rect object. */ virtual const Rect& getBoundary(); /** * Pure abstract method to render an object. This must be overridden by a * subclass. */ virtual void render() = 0; }; //============================================================================== /** * Class to draw a simple boxed object, like a cube, or 'rectangular' boxed * object. */ class Box : public Object { private: /// Box depth (over the z axis). GLfloat m_depth; public: Box(); ~Box(); virtual void render(); }; //============================================================================== /** * Displays a simple axis for rendering help. */ class Axis : public Object { private: /// Distance to draw this axis. GLfloat m_max; public: /** * Ctor. */ Axis(const GLfloat& max = 100); /** * Dtor. */ ~Axis(); /** * Renders this axis. */ void render(); }; //============================================================================== /** * Default reference implementation of a Particle. This class can be subclassed * and extended with custom properties. The render() method can be, so custom * particle rendering can be done. It's not needed though, for a particle generator * can render a particle solely based on the Particle's properties. */ class Particle : public Object { private: static const GLfloat SIZE = 1.0f; /// Whether this particle is active (should be rendered) or not. bool m_active; /// Lifetime this particle. If <= 0, should not be rendered. GLfloat m_life; /// Velocity on the x-axis. Negative = left, positive = right. GLfloat m_xv; /// Velocity on the y-axis. Negative = down, positive = up. GLfloat m_yv; /// Velocity on the z-axis. Negative = away?, positive = towards?. GLfloat m_zv; /// Color of the particle. Color m_color; /// Particle gravity. GLfloat m_gravity; /// Speed of 'fading', i.e. decrementing of the TTL. GLfloat m_fadespeed; public: /** * Creates a particle object. */ Particle(); /** * Destroys this particle. */ virtual ~Particle(); // Setters /** * Sets this particle to active (rendered) or not (not rendered). The 'life' * is unaffected after using this setter. * * @param active true when active or false if otherwise. */ void setActive(bool active); /** * Sets the life of this particle to a certain value. Ideally, when it * reached <= 0.0f, the particle shouldn't be alive anymore. * * @param life The life of this particle. */ void setLife(const GLfloat& life); /** * Sets the velocity of this particle on the x-axis. Negative will go left, * positive will go right, and 0.0f will let the particle remain stationary. * * @param xv The velocity of this particle on the x-axis. */ void setXv(const GLfloat& xv); /** * Sets the velocity of this particle on the y-axis. Negative will go down, * positive will go up, and 0.0f will let the particle remain stationary. * * @param yv The velocity of this particle on the y-axis. */ void setYv(const GLfloat& yv); /** * Sets the velocity of this particle on the z-axis. Negative will go to the back, * positive will go to the front, and 0.0f will let the particle remain stationary. * * @param zv The velocity of this particle on the z-axis. */ void setZv(const GLfloat& zv); /** * Sets the color of this particle. * * @param color The color. */ void setColor(const Color& color); /** * Sets the gravity factor of this particle. The gravity has an influence on * the particle's velocity: every iteration, this gravity number is added to * the current velocity, mimicking gravity. Negative gravity will allow the * particle to fall, while positive gravity will allow the particle to rise. * * @param gravity The gravity. */ void setGravity(const GLfloat& gravity); /** * Sets the fade speed of this particle, i.e. the amount of life decremented. * * @param fadeSpeed the speed of fading. */ void setFadeSpeed(const GLfloat& fadeSpeed); // Getters /** * Queries whether this particle is alive or not. * * @return true if active, false if not. */ bool isActive() const; /** * Gets the current life of the particle. * * @return The life. */ GLfloat getLife() const; /** * Gets the X velocity for this particle. * * @return The x velocity. */ GLfloat getXv() const; /** * Gets the Y velocity for this particle. * * @return The y velocity. */ GLfloat getYv() const; /** * Gets the Z velocity for this particle. * * @return The z velocity. */ GLfloat getZv() const; /** * Gets the current color of the particle. * * @return the current color. */ Color getColor() const; /** * Gets the current gravity factor. * * @return The gravity factor. */ GLfloat getGravity() const; /** * Gets the current fadespeed of this particle. The time to live can be * subtracted with this number to let a particle 'die'. * * @return the fading speed of this particle. */ GLfloat getFadeSpeed() const; /** * Renders this particle. It is not relaly necessary to override this method * in any subclasses to render a particle. It can however be good to separate * it, but your mileage may vary. */ virtual void render(); }; //============================================================================== /** * This is a default 'reference' implementation of a ParticleGenerator. It can * be used as a base class for other types of ParticleGenerators, with different * implementation specifics. Just override the render() method (and others), and * draw your particles using OpenGL like you want. * * This ParticleGenerator only generates a finite amount of particles (until the * maximum specified is reached). */ class ParticleGenerator : public Object { private: /// Array with fluffy particles. Particle* m_particles; /// Maximum amount of particles. GLuint m_max; /// Original particle life. Used to determine a percentage of lifetime of a particle. GLfloat m_particleLife; /// The (randomized) spread of the particles to generate on the x axis. The higher, the bigger the spread. GLfloat m_spread_x[2]; /// The (randomized) spread of the particles to generate on the y axis. The higher, the bigger the spread. GLfloat m_spread_y[2]; /// The (randomized) spread of the particles to generate on the z axis. The higher, the bigger the spread. GLfloat m_spread_z[2]; /// The (randomized) spread of the gravity. GLfloat m_spread_gravity[2]; /// The spread of fadespeed, i.e. decreasement of lifetime per particle. GLfloat m_spread_fade[2]; public: /** * Constructor. * * @param x The x coordinate origin of this generator. * @param y The y coordinate origin of this generator. */ ParticleGenerator(const GLfloat& x = 0.0f, const GLfloat& y = 0.0f); /** * Destroys this particle generator, by deleting the particles. */ virtual ~ParticleGenerator(); /** * Initializes the particle generator and its particles. Always call this * after you've set properties using the setter functions. This will iterate * over the particle array, and call initParticle for each single particle * instance. */ virtual void initialize(); /** * Initializes a single particle to the defaults for this generator. * * @param p The particle reference to initialize. */ virtual void initParticle(Particle& p); /** * Sets the maximum amount of particles this generator should create. * * @param max The maximum amount of particles to make. */ void setMaxParticles(const GLuint& max); void setSpreadX(const GLfloat& min, const GLfloat& max); void setSpreadY(const GLfloat& min, const GLfloat& max); void setSpreadZ(const GLfloat& min, const GLfloat& max); void setSpreadGravity(const GLfloat& min, const GLfloat& max); void setSpreadFade(const GLfloat& min, const GLfloat& max); void setParticleLife(const GLfloat& particleLife); const GLfloat& getParticleLife() const; /** * Returns the maximum amount of particles to be generated by this generator. * * @return The max particles. */ const GLuint& getMaxParticles() const; /** * Gets the particle array. The pointer cannot be changed, the values in it * can be changed however. getMaxParticles() can be used to iterate over the * array. * * @return The current array of particles. */ Particle* const getParticles() const; /** * Renders this particle generator and subsequently all its particles. Can * be overridden by subclasses to provide their own rendering. */ virtual void render(); }; } #endif // CORE_HPP
#pragma once #include <ostream> #include <string> #include <utility> namespace dot_pp { class SerializationPolicy { public: using AttributeName = std::string; using AttributeValue = std::string; using Attribute = std::pair<AttributeName, AttributeValue>; SerializationPolicy(std::ostream& stream); void createGraph(const std::string& name = ""); void createDigraph(const std::string& name = ""); void createVertex(const std::string& name); void createVertex(const std::string& name, const std::string& attributeName, const std::string& value); void createEdge(const std::string& vertex1, const std::string& vertex2); void createEdge(const std::string& vertex1, const std::string& vertex2, const std::string& attributeName, const std::string& value); void applyGraphAttribute(const std::string& attributeName, const std::string& value); template<typename... AttributeList> void defaultVertexAttributes(AttributeList&&... attributes) { stream_ << "\t" << "node ["; printAttributes(std::forward<AttributeList>(attributes)...); stream_ << "];\n"; } template<typename... AttributeList> void defaultEdgeAttributes(AttributeList&&... attributes) { stream_ << "\t" << "edge ["; printAttributes(std::forward<AttributeList>(attributes)...); stream_ << "];\n"; } template<typename... AttributeList> void applyVertexAttributes(const std::string& vertex, AttributeList&&... attributes) { stream_ << "\t" << vertex << " ["; printAttributes(std::forward<AttributeList>(attributes)...); stream_ << "];\n"; } template<typename... AttributeList> void applyEdgeAttributes(const std::string& vertex1, const std::string& vertex2, AttributeList&&... attributes) { stream_ << "\t" << vertex1 << " " << edgeStyle_ << " " << vertex2 << " ["; printAttributes(std::forward<AttributeList>(attributes)...); stream_ << "];\n"; } void blankLine(); void finalize(); private: void printAttribute(const Attribute& attribute); template<typename T> void printAttributes(const T& attribute) { printAttribute(attribute); } template<typename T, typename... AttributeList> void printAttributes(const T& attribute, AttributeList&&... attributes) { printAttribute(attribute); printAttributes(std::forward<AttributeList>(attributes)...); } private: std::ostream& stream_; std::string edgeStyle_; }; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> #include <numeric> #define INF (1<<28) using namespace std; class LotteryTicket { public: string buy(int price, int b1, int b2, int b3, int b4) { vector<int> b; b.push_back(b1); b.push_back(b2); b.push_back(b3); b.push_back(b4); for (int i=1; i<16; i++) { int ret = 0; for (int j=0; j<4; ++j) { if ((i>>j)&1) { ret += b[j]; } } if (ret == price) { return "POSSIBLE"; } } return "IMPOSSIBLE"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 10; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(0, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_1() { int Arg0 = 15; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(1, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_2() { int Arg0 = 65; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(2, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_3() { int Arg0 = 66; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(3, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_4() { int Arg0 = 1000; int Arg1 = 999; int Arg2 = 998; int Arg3 = 997; int Arg4 = 996; string Arg5 = "IMPOSSIBLE"; verify_case(4, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_5() { int Arg0 = 20; int Arg1 = 5; int Arg2 = 5; int Arg3 = 5; int Arg4 = 5; string Arg5 = "POSSIBLE"; verify_case(5, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_6() { int Arg0 = 668; int Arg1 = 913; int Arg2 = 668; int Arg3 = 300; int Arg4 = 36; string Arg5 = "POSSIBLE"; verify_case(6, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } // END CUT HERE }; // BEGIN CUT HERE int main() { LotteryTicket ___test; ___test.run_test(-1); } // END CUT HERE
#ifndef SPHEREMODELCLASS_H #define SPHEREMODELCLASS_H // INCLUDES // #include <fstream> #include <D3DX10.h> using namespace std; class SphereModelClass { public: struct SphereModelType { D3DXVECTOR3 position; D3DXVECTOR2 texture; D3DXVECTOR3 normal; D3DXVECTOR3 tangent; D3DXVECTOR3 binormal; }; struct TempVertexType { D3DXVECTOR3 position; D3DXVECTOR2 texture; D3DXVECTOR3 normal; }; public: SphereModelClass(); SphereModelClass(const SphereModelClass&); ~SphereModelClass(); bool Initialize(ID3D10Device *device); void Shutdown(); D3DXVECTOR3 GetModelCenter(); D3DXVECTOR3 GetModelSize(); unsigned long GetVerticesCount(); ID3D10Buffer* GetVertexBufferPtr(); ID3D10Buffer* GetIndexBufferPtr(); SphereModelType *m_Model; private: // Methods bool LoadModelFromTXT(char*); bool InitializeBuffers(ID3D10Device*); void CalculateModelVectors(); void CalculateTangentBinormal(TempVertexType, TempVertexType, TempVertexType, D3DXVECTOR3&, D3DXVECTOR3&); void CalculateNormal(D3DXVECTOR3, D3DXVECTOR3, D3DXVECTOR3&); void CalculateModelSize(); // Members unsigned long m_VertexCount, m_IndexCount; D3DXVECTOR3 m_ModelCenter, m_ModelSize; ID3D10Buffer *m_VertexBuffer, *m_IndexBuffer; }; #endif
#include "Maestro.h" #include <sstream> using std::stringstream; Maestro::Maestro(){ } Maestro::Maestro(string n, string na, int e, string s, Elemento* el, Poder* p){ nombre=n; nacion=na; edad=e; sexo=s; elemento=el; poder=p; } Poder* Maestro::getPoder(){ return poder; } string Maestro::toString(){ stringstream retorno; string r; retorno<<Persona::toString(); retorno<<"Poder: "<<poder->toString()<<"\n"; r=retorno.str(); return r; } Maestro::~ Maestro(){ delete elemento; delete poder; }
#pragma once #include "dice.h" dice::dice(int val) { value = val; int vl; vl = val; model = models[vl - 1]; } void dice::change_value(double val) { value = val; int vl; vl = val; model = models[vl - 1]; }
// Author: Kirill Gavrilov // Copyright (c) 2015-2019 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Image_Texture_HeaderFile #define _Image_Texture_HeaderFile #include <NCollection_Buffer.hxx> #include <TCollection_AsciiString.hxx> class Image_CompressedPixMap; class Image_SupportedFormats; class Image_PixMap; //! Texture image definition. //! The image can be stored as path to image file, as file path with the given offset and as a data buffer of encoded image. class Image_Texture : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Image_Texture, Standard_Transient) public: //! Constructor pointing to file location. Standard_EXPORT explicit Image_Texture (const TCollection_AsciiString& theFileName); //! Constructor pointing to file part. Standard_EXPORT explicit Image_Texture (const TCollection_AsciiString& theFileName, int64_t theOffset, int64_t theLength); //! Constructor pointing to buffer. Standard_EXPORT explicit Image_Texture (const Handle(NCollection_Buffer)& theBuffer, const TCollection_AsciiString& theId); //! Return generated texture id. const TCollection_AsciiString& TextureId() const { return myTextureId; } //! Return image file path. const TCollection_AsciiString& FilePath() const { return myImagePath; } //! Return offset within file. int64_t FileOffset() const { return myOffset; } //! Return length of image data within the file after offset. int64_t FileLength() const { return myLength; } //! Return buffer holding encoded image content. const Handle(NCollection_Buffer)& DataBuffer() const { return myBuffer; } //! Return mime-type of image file based on ProbeImageFileFormat(). Standard_EXPORT TCollection_AsciiString MimeType() const; //! Return image file format. Standard_EXPORT TCollection_AsciiString ProbeImageFileFormat() const; //! Image reader without decoding data for formats supported natively by GPUs. Standard_EXPORT virtual Handle(Image_CompressedPixMap) ReadCompressedImage (const Handle(Image_SupportedFormats)& theSupported) const; //! Image reader. Standard_EXPORT virtual Handle(Image_PixMap) ReadImage (const Handle(Image_SupportedFormats)& theSupported) const; //! Write image to specified file without decoding data. Standard_EXPORT virtual Standard_Boolean WriteImage (const TCollection_AsciiString& theFile); //! Write image to specified stream without decoding data. Standard_EXPORT virtual Standard_Boolean WriteImage (std::ostream& theStream, const TCollection_AsciiString& theFile); public: //! @name hasher interface //! Hash value, for Map interface. static int HashCode (const Handle(Image_Texture)& theTexture, const int theUpper) { return !theTexture.IsNull() ? TCollection_AsciiString::HashCode (theTexture->myTextureId, theUpper) : 0; } //! Matching two instances, for Map interface. static Standard_Boolean IsEqual (const Handle(Image_Texture)& theTex1, const Handle(Image_Texture)& theTex2) { if (theTex1.IsNull() != theTex2.IsNull()) { return Standard_False; } else if (theTex1.IsNull()) { return Standard_True; } return theTex1->myTextureId.IsEqual (theTex2->myTextureId); } //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; protected: //! Read image from normal image file. Standard_EXPORT virtual Handle(Image_PixMap) loadImageFile (const TCollection_AsciiString& thePath) const; //! Read image from file with some offset. Standard_EXPORT virtual Handle(Image_PixMap) loadImageOffset (const TCollection_AsciiString& thePath, int64_t theOffset, int64_t theLength) const; //! Read image from buffer. Standard_EXPORT virtual Handle(Image_PixMap) loadImageBuffer (const Handle(NCollection_Buffer)& theBuffer, const TCollection_AsciiString& theId) const; protected: TCollection_AsciiString myTextureId; //!< generated texture id TCollection_AsciiString myImagePath; //!< image file path Handle(NCollection_Buffer) myBuffer; //!< image buffer int64_t myOffset; //!< offset within file int64_t myLength; //!< length within file }; #endif // _Image_Texture_HeaderFile
#ifndef DISTANCES_H #define DISTANCES_H typedef std::vector<double> dataPoint; double rmsd(const dataPoint&, const dataPoint&); #endif
/****************************************************************************** * * * Copyright 2018 Jan Henrik Weinstock * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #include <sys/mman.h> #include "vcml/models/generic/memory.h" namespace vcml { namespace generic { struct image_info { string file; u64 offset; }; static vector<image_info> images_from_string(string s) { vector<image_info> images; s.erase(std::remove_if(s.begin(), s.end(), [] (unsigned char c) { return isspace(c); }), s.end()); vector<string> token = split(s, ';'); for (string cur : token) { if (cur.empty()) continue; vector<string> vec = split(cur, '@'); if (vec.empty()) continue; string file = vec[0]; u64 off = vec.size() > 1 ? strtoull(vec[1].c_str(), NULL, 0) : 0; images.push_back({file, off}); } return images; } bool memory::cmd_load(const vector<string>& args, ostream& os) { string binary = args[0]; u64 offset = 0ull; if (args.size() > 1) offset = strtoull(args[1].c_str(), NULL, 0); load(binary, offset); return true; } bool memory::cmd_show(const vector<string>& args, ostream& os) { u64 start = strtoull(args[0].c_str(), NULL, 0); u64 end = strtoull(args[1].c_str(), NULL, 0); if ((end <= start) || (end >= size)) return false; #define HEX(x, w) std::setfill('0') << std::setw(w) << \ std::hex << x << std::dec os << "showing range 0x" << HEX(start, 8) << " .. 0x" << HEX(end, 8); u64 addr = start & ~0xf; while (addr < end) { if ((addr % 16) == 0) os << "\n" << HEX(addr, 8) << ":"; if ((addr % 4) == 0) os << " "; if (addr >= start) os << HEX((unsigned int)m_memory[addr], 2) << " "; else os << " "; addr++; } #undef HEX return true; } memory::memory(const sc_module_name& nm, u64 sz, bool read_only, unsigned int rlat, unsigned int wlat): peripheral(nm, host_endian(), rlat, wlat), m_memory(nullptr), size("size", sz), readonly("readonly", false), images("images", ""), poison("poison", 0x00), IN("IN") { VCML_ERROR_ON(size == 0u, "memory size cannot be 0"); int perms = PROT_READ | PROT_WRITE; int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE; void* p = mmap(0, size, perms, flags, -1, 0); VCML_ERROR_ON(p == MAP_FAILED, "mmap failed: %s", strerror(errno)); m_memory = (unsigned char*)p; map_dmi(m_memory, 0, size - 1, readonly ? VCML_ACCESS_READ : VCML_ACCESS_READ_WRITE); if (poison > 0) memset(m_memory, poison, size); register_command("load", 1, this, &memory::cmd_load, "Load <binary> [off] to load the contents of file <binary> to " \ "relative offset [off] in memory (offset is zero if unspecified)."); register_command("show", 2, this, &memory::cmd_show, "Show memory contents between addresses [start] and [end]. " \ "Usage: show [start] [end]"); vector<image_info> imagevec = images_from_string(images); for (auto ii : imagevec) { log_debug("loading '%s' to 0x%08llx", ii.file.c_str(), ii.offset); load(ii.file, ii.offset); } } memory::~memory() { if (m_memory) munmap(m_memory, size); } void memory::reset() { memset(m_memory, poison, size); } void memory::load(const string& binary, u64 offset) { ifstream file(binary.c_str(), std::ios::binary | std::ios::ate); if (!file.is_open()) { log_warn("cannot open file '%s'", binary.c_str()); return; } if (offset >= size) { log_warn("offset %llu exceeds memsize %llu", offset, size.get()); return; } u64 nbytes = file.tellg(); if (nbytes > size - offset) { nbytes = size - offset; log_warn("image file '%s' to big, truncating after %llu bytes", nbytes, binary.c_str()); } file.seekg(0, std::ios::beg); file.read((char*)(m_memory + offset), nbytes); } tlm_response_status memory::read(const range& addr, void* data, const sideband& info) { if (addr.end >= size) return TLM_ADDRESS_ERROR_RESPONSE; memcpy(data, m_memory + addr.start, addr.length()); return TLM_OK_RESPONSE; } tlm_response_status memory::write(const range& addr, const void* data, const sideband& info) { if (addr.end >= size) return TLM_ADDRESS_ERROR_RESPONSE; if (readonly && !info.is_debug) return TLM_COMMAND_ERROR_RESPONSE; memcpy(m_memory + addr.start, data, addr.length()); return TLM_OK_RESPONSE; } }}
#include "Enes100.h" // Global vars float theta; // tank angle in rad float xPos; //tank x coord float yPos; //tank y coord //float theta_desired = PI / 12; // Enter the target angle in the space here int minMotorValue = 140; // minimum input value which will produce a turning movement in the tank int leftD = 4; int leftS = 5; int rightS = 6; int rightD = 7; int dist; // read distance to obstacle /* Create a new Enes100 object Parameters: string teamName int teamType int markerId int rxPin int txPin */ #include <dfr_tank.h> Enes100 enes("JEDIARMS", WATER, 5, 8, 9); DFRTank tank; void setup() { tank.init(); // Retrieve the destination while (!enes.retrieveDestination()) { enes.println("Unable to retrieve location"); } enes.print("My destination is at "); enes.print(enes.destination.x); enes.print(","); enes.println(enes.destination.y); } void loop() { // Update the OSV's current location if (enes.updateLocation()) { enes.println("Huzzah! Location updated!"); enes.print("My x coordinate is "); enes.println(enes.location.x); enes.print("My y coordinate is "); enes.println(enes.location.y); enes.print("My theta is "); enes.println(enes.location.theta); } else { enes.println("Sad trombone... I couldn't update my location"); } //turn towards y direction of destination if yCoord(); xCoord(); obstacle(); } void driveUntil void yCoord() { //Get to correct y coordinate if (enes.location.y > enes.destination.y) { turnTo(3 * PI / 2); //turn to negative y axis while (enes.location.y > enes.destination.y) { enes.updateLocation(); tank.setLeftMotorPWM(255); tank.setRightMotorPWM(255); delay(500); if (enes.location.y <= enes.destination.y) { tank.setLeftMotorPWM(0); tank.setRightMotorPWM(0); turnTo(0);//turn 90 degrees to be parallel to x axis } } } else if (enes.location.y < enes.destination.y) { turnTo(PI / 2); //turn to positive y axis while (enes.location.y < enes.destination.y) { enes.updateLocation(); tank.setLeftMotorPWM(255); tank.setRightMotorPWM(255); delay(500); if (enes.location.y >= enes.destination.y) { tank.setLeftMotorPWM(0); tank.setRightMotorPWM(0); turnTo(0);//turn 90 degrees to be parallel to x axis } } } else { turnTo(0);//turn 90 degrees to be parallel to x axis } } void xCoord() { //Navigate to x coordinate while (dist < 400) { dist = analogRead(6); enes.updateLocation(); while (enes.location.x < enes.destination.x) { enes.updateLocation(); tank.setLeftMotorPWM(255); tank.setRightMotorPWM(255); delay(500); if (enes.location.x >= enes.destination.x) { tank.setLeftMotorPWM(0); tank.setRightMotorPWM(0); } } } } //Detect obstacle, stop, and turn upwards void obstacle() { dist = analogRead(6); if (dist >= 400 && enes.location.y < 3) { tank.setLeftMotorPWM(0); tank.setRightMotorPWM(0); turnTo(PI / 2); //turn 90 degrees towards positive y axis tank.setLeftMotorPWM(255); tank.setRightMotorPWM(255); delay(500); tank.setLeftMotorPWM(0); tank.setRightMotorPWM(0); turnTo(0);//rotate back towards positive x axis obstacle(); } else if (dist >= 400 && enes.location.y > 3) { tank.setLeftMotorPWM(0); tank.setRightMotorPWM(0); turnTo(3 * PI / 2); //turn 90 degrees towards negative y axis tank.setLeftMotorPWM(255); tank.setRightMotorPWM(255); delay(500); tank.setLeftMotorPWM(0); tank.setRightMotorPWM(0); turnTo(0);//rotate back towards positive x axis obstacle(); } else { xCoord(); yCoord(); } } /*if (enes.location.x == enes.destination.x && enes.location.y == enes.location.y) { enes.navigated(); } */ /* turns tank to desired angle theta */ void turnTo(float theta_desired) { float k = (255 - minMotorValue) / PI; // proportional controller for turning speed (“gain”) float errTheta; // variable to hold the error int motorRate = 0; //variable for turning rate of motor if ((theta - theta_desired <= PI) && (theta - theta_desired >= 0)) { errTheta = (theta - theta_desired); // compute error TURN RIGHT (POSITIVE) } else if (theta - theta_desired > PI) { errTheta = -((2 * PI - theta) + theta_desired); // compute error TURN LEFT (NEGATIVE) } else if ((theta - theta_desired >= -PI) && (theta - theta_desired < 0)) { errTheta = (theta - theta_desired); // compute error TURN LEFT (NEGATIVE) } else if (theta - theta_desired < -PI) { errTheta = ((2 * PI - theta_desired) + theta); // compute error TURN RIGHT (POSITIVE) } /* turns tank to desired angle theta */ if (errTheta > 0.05 || errTheta < -0.05) // only compute if not converged { if (abs(errTheta) < .1) { motorRate = minMotorValue; } else { motorRate = minMotorValue + abs(errTheta) * k; } if (errTheta < 0) { digitalWrite(leftD, LOW); digitalWrite(rightD, HIGH); } else { digitalWrite(leftD, HIGH); digitalWrite(rightD, LOW); } analogWrite(leftS, motorRate); analogWrite(rightS, motorRate); } else { analogWrite(rightS, 0); analogWrite(leftS, 0); } delay(250); analogWrite(rightS, 0); analogWrite(leftS, 0); delay(250); enes.updateLocation(); theta = enes.location.theta;// update theta }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Peter Karlsson */ #ifndef PREFSENTRYINTERNAL_H #define PREFSENTRYINTERNAL_H #include "modules/prefsfile/prefssection.h" // To get PREFSMAP_USE_HASH #include "modules/prefsfile/prefsentry.h" /** * Implementation of the PrefsEntry class. Represents an entry in a set of * preferences. * * This API is internal to the prefsfile module, but is also referenced * by the prefs module. */ class PrefsEntryInternal : public PrefsEntry { public: /** * A constructor for the class. */ PrefsEntryInternal(); /** * Second phase constructor for the class. * @param name The key name of the entry * @param value The value of the entry. Default to NULL * @return Status of the operation */ inline void ConstructL(const uni_char *name, const uni_char *value = NULL) { PrefsEntry::ConstructL(name, value); } /** * Set the associated value. * * @param value The new value * @return Status of the operation */ void SetL(const uni_char *value); #ifndef PREFSMAP_USE_HASH /** * Compares the name of the keys. The key name must be converted to * lower case, unless PREFSMAP_USE_CASE_SENSITIVE is defined. * * @return true if it is the same key * @param lowercase_key The name of the key you are searching for, * in lowercase */ inline BOOL IsSameAs(const uni_char *lowercase_key) const { if ((m_key == NULL) || (lowercase_key == NULL)) return FALSE; # ifdef PREFSMAP_USE_CASE_SENSITIVE return (uni_strcmp(m_key, lowercase_key) == 0); # else return (uni_strcmp(m_lkey, lowercase_key) == 0); # endif } #endif #ifdef PREFSMAP_USE_HASH /** * Enter this entry into the specified hash table. */ void IntoHashL(OpHashTable *); /** * Remove this entry from the specified hash table. */ void OutOfHash(OpHashTable *); #endif /** * Return the next entry in the list. */ inline PrefsEntryInternal *Suc() const { return static_cast<PrefsEntryInternal *>(Link::Suc()); } }; #endif
#pragma once #include "point.h" #include "controller.h" #include "drawManager.h" #include "toolbarControl.h" #include <functional> #include "appConsts.h" class Button : public ToolbarControl { private: const ButtonTheme *buttonTheme; Point<float> pos, size; std::string label; std::function<void(void)> eventHandler; public: Button(Point<float> pos, Point<float> size, std::string label, const ButtonTheme *buttonTheme); void setOnClickHandler(std::function<void(void)> eventHandler); virtual void draw(DrawManager *drawManager); virtual void update(Controller *controller); };
/***************************************************************************************** * * * owl * * * * Copyright (c) 2014 Jonas Strandstedt * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <owl/network/tcpclient.h> #include <owl/logging/logmanager.h> namespace { std::string _loggerCat = "TCPClient"; } namespace owl { TCPClient::TCPClient() { } TCPClient::~TCPClient() { } bool TCPClient::connect(const std::string& hostname, int port) { if (port < 0) { return false; } #ifdef __WIN32__ return false; #else struct sockaddr_in serv_addr; struct hostent *server; _socket = socket(AF_INET, SOCK_STREAM, 0); if (_socket < 0){ LERROR("Could not open socket"); return false; } server = gethostbyname(hostname.c_str()); if (server == NULL) { LERROR("No such host: " << hostname); return false; } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(port); if (::connect(_socket,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) { LERROR("Could not connect"); return false; } #endif return true; } bool TCPClient::connectLocalhost(int port) { return connect("127.0.0.1", port); } bool TCPClient::connect(int p1, int p2, int p3, int p4, int port) { if (p1 < 0 || p2 < 0 || p3 < 0 || p4 < 0) return false; if (p1 > 255 || p2 > 255 || p3 > 255 || p4 > 255) return false; if (port < 0) return false; const size_t bufferSize = 30; char buffer[bufferSize]; #ifdef __WIN32__ return false; #else snprintf(buffer, bufferSize, "%i.%i.%i.%i", p1, p2, p3, p4); #endif return connect(buffer, port); } void TCPClient::disconnect() { #ifdef __WIN32__ #else ::close(_socket); #endif } void TCPClient::listen(ClientReadCallback_t callback, ClientCloseCallback_t closeCallback) { _callback = callback; _closeCallback = closeCallback; _listenerThread = std::thread(listener, this); _listenerThread.detach(); } void TCPClient::write(int length, const char* data) { #ifdef __WIN32__ #else int n = ::write(_socket,data,length); if (n < 0) LERROR("Could not write to socket"); #endif } void TCPClient::write(const std::string& data) { write(data.size(), data.c_str()); } bool TCPClient::read(int& length, char* data[]) { int n; SocketData_t buffer[MAX_DATA_SIZE]; #ifdef __WIN32__ return false; #else n = ::read(_socket, buffer, MAX_DATA_SIZE-1); if (n<=0) { return false; } length = n; // TODO replace bcopy with memcpy bcopy(buffer, *data,length); #endif return true; } void TCPClient::listener(TCPClient* client) { int length; char* buffer = new char[TCPClient::MAX_DATA_SIZE]; while (client->read(length, &buffer)) { client->_callback(length, buffer); } delete[] buffer; if(client->_closeCallback) client->_closeCallback(client); } }
#pragma once namespace Hourglass { enum FileArchiveOpenMode { kFileOpenMode_Read, kFileOpenMode_Write }; class FileArchive { public: ~FileArchive(); // Open file for read or write bool Open(const char* filename, FileArchiveOpenMode mode); // Close file void Close(); // Is file open for operation bool IsOpen() const; // Is file open for reading bool IsReading() const; // Make sure file contains a header // Read Mode: return false if file doesn't contain the header // Write Mode: write header into file stream bool EnsureHeader(const char* header, UINT size); // Serialize a vector template<typename T> void Serialize( T& data ) { if (m_OpenMode == kFileOpenMode_Write) { m_FileStream.write( (char*)&data, sizeof( data ) ); } else { assert( !m_FileStream.eof() ); m_FileStream.read( (char*)&data, sizeof( data ) ); } } // Serialize a string template<> void Serialize<std::string>( std::string& str ) { if (m_OpenMode == kFileOpenMode_Write) { unsigned int size = unsigned int( str.size() ); m_FileStream.write( (char*)&size, sizeof( size ) ); m_FileStream.write( str.c_str(), str.size() ); } else { unsigned int size; char buffer[255]; assert( !m_FileStream.eof() ); m_FileStream.read( (char*)&size, sizeof( size ) ); m_FileStream.read( buffer, size ); str = buffer; } } // Serialize a vector template<typename T> void Serialize(std::vector<T>& vec) { if (m_OpenMode == kFileOpenMode_Write) { UINT size = (UINT)vec.size(); m_FileStream.write((char*)&size, sizeof(size)); if (size) m_FileStream.write((char*)vec.data(), sizeof(T) * size); } else { assert(!m_FileStream.eof()); UINT size; m_FileStream.read((char*)&size, sizeof(size)); vec.resize(size); if (size) m_FileStream.read((char*)vec.data(), sizeof(T) * size); } } private: std::fstream m_FileStream; FileArchiveOpenMode m_OpenMode; }; }
#include <cstdio> #include "hello/public/World.h" void world() { printf("world\n"); }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "KeysStorage.h" #include "WalletLegacy/WalletLegacySerialization.h" #include "Serialization/ISerializer.h" #include "Serialization/SerializationOverloads.h" #include "CryptoNoteCore/CryptoNoteSerialization.h" namespace cn { void KeysStorage::serialize(ISerializer& serializer, const std::string& name) { serializer.beginObject(name); serializer(creationTimestamp, "creation_timestamp"); serializer(spendPublicKey, "spend_public_key"); serializer(spendSecretKey, "spend_secret_key"); serializer(viewPublicKey, "view_public_key"); serializer(viewSecretKey, "view_secret_key"); serializer.endObject(); } }
//hung.nguyen@student.tut.fi - student id: 272585 //sanghun.2.lee@student.tut.fi - student id: 272571 #include <vector> #include <string> #include <iostream> #include "splitter.hh" using namespace std; /*split input file line into seperate string and store them into *a vector which is returned by the function. */ vector<string> split(const string& stringToSplit_,char regex){ vector<string> fields; string::size_type strCount=0; string::size_type mark1=0; string::size_type mark2=0; while(1){ mark2 = stringToSplit_.find(regex,mark1); if(mark2 == string::npos){ fields.push_back(stringToSplit_.substr(mark1)); break; } strCount = mark2 - mark1; if(strCount !=0){ fields.push_back(stringToSplit_.substr(mark1,strCount)); } while(stringToSplit_.at(mark2) == regex){ if(mark2==stringToSplit_.size() -1){ break; } mark2++; } if(mark2==stringToSplit_.size() -1){ if(stringToSplit_.at(mark2) == regex) break; fields.push_back(stringToSplit_.substr(mark2,1)); break; } mark1 = mark2; } return fields; }
/* * @Fichier : main.ino * @Auteur : Adam Martineau, Félix Thibault-Giguère * @Date : 20/oct/2018 * @Bref : Attaquant pour le défi de l'octogone * @Environnement : Visual Studio Code, PlatformIO * @Compilateur : C++ * @Matériel : Arduino mega 2560 * @Revision : 1 */ //--- LISTE DES #INCLUDES ---// #include <LibRobus.h> // Essentielle pour utiliser RobUS /* * @Nom : move * @Brief : fonction qui utilise un pid pour déplacé le robot * @Entré : double vitesse, double distance * @Sortie : void */ void move(double vitesse) { double KPB=0.2; double multiplicateur=1; double erreur=(ENCODER_Read(0)-ENCODER_Read(1))/50; multiplicateur+=(KPB*erreur); MOTOR_SetSpeed(1,vitesse*multiplicateur); MOTOR_SetSpeed(0,vitesse); delay(50); } void moveBack(double vitesse, double distance){ double KPB=0.2; double KIB=0.02; double erreurTot=0; ENCODER_Reset(0); ENCODER_Reset(1); if (vitesse > 0) { while(ENCODER_Read(0)*0.075594573<distance*0.1) { MOTOR_SetSpeed(1,0.13+vitesse*((ENCODER_Read(0)*0.075594573)/(distance*0.1))); MOTOR_SetSpeed(0,0.13+vitesse*((ENCODER_Read(0)*0.075594573)/(distance*0.1))); } MOTOR_SetSpeed(0,vitesse); MOTOR_SetSpeed(1,vitesse); ENCODER_Reset(0); ENCODER_Reset(1); while(distance*0.8>ENCODER_Read(0)*0.075594573&&distance*0.8>ENCODER_Read(1)*0.075594573) { double multiplicateur=1; double erreur=(ENCODER_Read(0)-ENCODER_Read(1))/50; erreurTot+=erreur; multiplicateur+=(KPB*erreur+KIB*erreurTot); MOTOR_SetSpeed(1,vitesse*multiplicateur); delay(50); } ENCODER_Reset(0); ENCODER_Reset(1); while(ENCODER_Read(0)*0.075594573<distance*0.1) { MOTOR_SetSpeed(1,0.13+vitesse-vitesse*((ENCODER_Read(0)*0.075594573)/(distance*0.1))); MOTOR_SetSpeed(0,0.13+vitesse-vitesse*((ENCODER_Read(0)*0.075594573)/(distance*0.1))); } MOTOR_SetSpeed(0,0); MOTOR_SetSpeed(1,0); } else { while(ENCODER_Read(0)*0.075594573>-distance*0.1) { MOTOR_SetSpeed(1,-0.13+vitesse*((ENCODER_Read(0)*0.075594573)/(-distance*0.1))); MOTOR_SetSpeed(0,-0.13+vitesse*((ENCODER_Read(0)*0.075594573)/(-distance*0.1))); } MOTOR_SetSpeed(0,vitesse); MOTOR_SetSpeed(1,vitesse); ENCODER_Reset(0); ENCODER_Reset(1); while(-distance*0.8<ENCODER_Read(0)*0.075594573&&-distance*0.8<ENCODER_Read(1)*0.075594573) { double multiplicateur=1; double erreur=-1*(ENCODER_Read(0)-ENCODER_Read(1))/50; erreurTot+=erreur; multiplicateur+=(KPB*erreur+KIB*erreurTot); MOTOR_SetSpeed(1,vitesse*multiplicateur); delay(50); } ENCODER_Reset(0); ENCODER_Reset(1); while(ENCODER_Read(0)*0.075594573>-distance*0.1) { MOTOR_SetSpeed(1,(-0.13+vitesse-vitesse*((ENCODER_Read(0)*0.075594573)/(-distance*0.1)))); MOTOR_SetSpeed(0,(-0.13+vitesse-vitesse*((ENCODER_Read(0)*0.075594573)/(-distance*0.1)))); } MOTOR_SetSpeed(0,0); MOTOR_SetSpeed(1,0); } } /* * Pour les deux fonctions suivantes: * empatement = 18.8 cm * 3.281218894 mm/deg * 0.023038563 deg/pulse * * @Nom : turn_R() * @Brief : on déplace le robot vers la droite * @Entré : double vitesse , double angle * @Sortie : void */ void turn_R(double vitesse , double angle) { ENCODER_Reset(0); ENCODER_Reset(1); while(angle>ENCODER_Read(0)*0.023038563) { MOTOR_SetSpeed(0,vitesse); MOTOR_SetSpeed(1,0); } } /* * @Nom : turn_L() * @Brief : on déplace le robot vers la gauche * @Entré : double vitesse , double angle * @Sortie : void */ void turn_L(double vitesse , double angle) { ENCODER_Reset(0); ENCODER_Reset(1); while(angle>ENCODER_Read(1)*0.023038563) { MOTOR_SetSpeed(1,vitesse); MOTOR_SetSpeed(0,0); } } /* * @Nom : turn_180() * @Brief : on fait faire un 180 au robot * @Entré : double vitesse * @Sortie : void */ void turn_180(double vitesse) { ENCODER_Reset(1); ENCODER_Reset(0); while(87>ENCODER_Read(1)*0.023038563||-87<ENCODER_Read(0)*0.023038563) { if(87>ENCODER_Read(1)*0.023038563) { MOTOR_SetSpeed(1,vitesse); } else MOTOR_SetSpeed(1,0); if(-87<ENCODER_Read(0)*0.023038563) { MOTOR_SetSpeed(0,-vitesse); } else MOTOR_SetSpeed(0,0); } } int get_distance(int pin) { int adc = analogRead(pin); //on transforme la valeur de l'adc (de 0 a 1023) en volt (de 0 a 5) float analog = adc * (5.0 / 1023.0); } /* * @Nom : get_line() * @Brief : va chercher l'état des capteurs de ligne, on dispose de * 3 capteurs un à côté de l'autre, on retourne un int qui * représante un nombre binaire a 3 bites. * @Entré : void * @Sortie : on retourne un int qui représante un nombre binaire a * 3 bites, chaque bite représante un capteur, EX: 2 * (010 en binaire) = la ligne est détecté au centre. */ int get_line() { int adc = analogRead(A4); int output = 0; //on transforme la valeur de l'adc (de 0 a 1023) en volt (de 0 a 5) float analog = adc * (5.0 / 1023.0); /* on doit convertire notre valeur de tention * en int (pour pouvoir l'analyser comme un byte), * la valeur du 1er bit est 0.7v, le 2eim 1.4v * et le 3eim 2.7v. */ //3eim bit if (analog - 2.7 >= 0) { output += 4; analog -= 2.7; } //2eim bit if(analog - 1.4 >= 0) { output += 2; analog -= 1.4; } //1er bit if(analog - 0.7 >= -0.5) { output += 1; analog -= 0.7; } Serial.print("\n\r Valeur retourne par get_line() : "); Serial.print(output); return output; } /* * @Nom : detect_line() * @Brief : fonction pour detecté quand on croise une ligne sur le * parcoure * @Entré : void * @Sortie : void */ bool detect_line() { if(get_line() != 0) return true; else return false; } /* * @Nom : move_on_line() * @Brief : une fois un ligne détecté on bouge le robot sur la ligne * @Entré : void * @Sortie : void */ void move_on_line() { if(get_line() != 2) { if(get_line() == 1) turn_L(0.3, 1); else turn_R(0.3, 1); } } /* * @Nom : setup() * @Brief : fonction d'initialisation, appeler avant la fonction loop() * @Entré : void * @Sortie : void */ void setup(){ Serial.begin(9600); BoardInit(); } /* * @Nom : loop() * @Brief : Boucle principal, le Main de l'Arduino * @Entré : void * @Sortie : void */ void loop() { ENCODER_Reset(0); ENCODER_Reset(1); move(0.1); int adc = analogRead(A3); //on transforme la valeur de l'adc (de 0 a 1023) en volt (de 0 a 5) float v1 = adc * (5.0 / 1023.0); adc = analogRead(A2); //on transforme la valeur de l'adc (de 0 a 1023) en volt (de 0 a 5) float v2 = adc * (5.0 / 1023.0); if (v2 >= 2.5) { int angle = rand() % (270 + 1 + 90) - 90; moveBack(-0.3, 200); turn_L(0.3, angle); Serial.print("\n\r Numero de la decision prise: "); Serial.print(angle); ENCODER_Reset(0); ENCODER_Reset(1); } else if(v1 >= 2.5) { Serial.print("\n\r Ballon detecte "); turn_180(0.8); } // SOFT_TIMER_Update(); // A decommenter pour utiliser des compteurs logiciels delay(100);// Delais pour décharger le CPU }
// Copyright (c) 2007-2017 Hartmut Kaiser // Copyright (c) 2017 Shoshana Jakobovits // Copyright (c) 2010-2011 Phillip LeBlanc, Dylan Stark // Copyright (c) 2011 Bryce Lelbach // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <pika/config.hpp> #include <pika/assert.hpp> #include <pika/debugging/backtrace.hpp> #include <pika/modules/errors.hpp> #include <pika/modules/logging.hpp> #include <pika/modules/thread_manager.hpp> #include <pika/runtime/config_entry.hpp> #include <pika/runtime/custom_exception_info.hpp> #include <pika/runtime/debugging.hpp> #include <pika/runtime/runtime.hpp> #include <pika/runtime/runtime_handlers.hpp> #include <pika/threading_base/thread_data.hpp> #include <pika/threading_base/thread_pool_base.hpp> #include <cstddef> #include <iostream> #include <sstream> #include <string> namespace pika::detail { [[noreturn]] void assertion_handler( pika::detail::source_location const& loc, const char* expr, std::string const& msg) { static thread_local bool handling_assertion = false; if (handling_assertion) { std::ostringstream strm; strm << "Trying to handle failed assertion while handling another failed assertion!" << std::endl; strm << "Assertion '" << expr << "' failed"; if (!msg.empty()) { strm << " (" << msg << ")"; } strm << std::endl; strm << "{file}: " << loc.file_name << std::endl; strm << "{line}: " << loc.line_number << std::endl; strm << "{function}: " << loc.function_name << std::endl; std::cerr << strm.str(); std::abort(); } handling_assertion = true; std::ostringstream strm; strm << "Assertion '" << expr << "' failed"; if (!msg.empty()) { strm << " (" << msg << ")"; } pika::exception e(pika::error::assertion_failure, strm.str()); std::cerr << pika::diagnostic_information(pika::detail::get_exception( e, loc.function_name, loc.file_name, loc.line_number)) << std::endl; pika::util::may_attach_debugger("exception"); std::abort(); } #if defined(PIKA_HAVE_APEX) bool enable_parent_task_handler() { return !pika::is_networking_enabled(); } #endif #if defined(PIKA_HAVE_VERIFY_LOCKS) void registered_locks_error_handler() { std::string back_trace = pika::debug::detail::trace(std::size_t(128)); // throw or log, depending on config options if (get_config_entry("pika.throw_on_held_lock", "1") == "0") { if (back_trace.empty()) { LERR_(debug).format("suspending thread while at least one lock is being held " "(stack backtrace was disabled at compile time)"); } else { LERR_(debug).format( "suspending thread while at least one lock is being held, stack backtrace: {}", back_trace); } } else { if (back_trace.empty()) { PIKA_THROW_EXCEPTION(pika::error::invalid_status, "verify_no_locks", "suspending thread while at least one lock is being held (stack backtrace was " "disabled at compile time)"); } else { PIKA_THROW_EXCEPTION(pika::error::invalid_status, "verify_no_locks", "suspending thread while at least one lock is being held, stack backtrace: {}", back_trace); } } } bool register_locks_predicate() { return threads::detail::get_self_ptr() != nullptr; } #endif threads::detail::thread_pool_base* get_default_pool() { pika::runtime* rt = get_runtime_ptr(); if (rt == nullptr) { PIKA_THROW_EXCEPTION(pika::error::invalid_status, "pika::detail::get_default_pool", "The runtime system is not active"); } return &rt->get_thread_manager().default_pool(); } threads::detail::mask_cref_type get_pu_mask( threads::detail::topology& /* topo */, std::size_t thread_num) { auto& rp = pika::resource::get_partitioner(); return rp.get_pu_mask(thread_num); } } // namespace pika::detail
#include "Poly.h" #include <Gizmos.h> #define DEBUG true #define SHOW_NORMALS true Poly::Poly(vector<vec2> const & vertices, vec2 position, vec2 velocity, float rotation, float fAngVel, float mass, float elasticity, float fFricCoStatic, float fFricCoDynamic, float fDrag, float fAngDrag, glm::vec4 colour) : RigidBody::RigidBody(ShapeID::Poly, position, velocity, rotation, fAngVel, mass, elasticity, fFricCoStatic, fFricCoDynamic, fDrag, fAngDrag) { m_Colour = colour; m_Vertices = vertices; Transform pos = Transform(); pos.SetPosition(position); Transform rot = Transform(); rot.SetRotate2D(rotation); m_GlobalTransform.LocalTransform(pos.GetTransform(), rot.GetTransform(), Transform::Identity()); CreateSNorms(); CreateBroadColl(); } Poly::~Poly() { delete m_pBroadColl; } void Poly::fixedUpdate(vec2 const& gravity, float timeStep) { RigidBody::fixedUpdate(gravity, timeStep); m_pBroadColl->setPosition(m_position); Transform pos = Transform(); pos.SetPosition(m_position); Transform rot = Transform(); rot.SetRotate2D(m_rotation); m_GlobalTransform.LocalTransform(pos.GetTransform(), rot.GetTransform(), Transform::Identity()); } void Poly::makeGizmo() { if (DEBUG) m_pBroadColl->makeGizmo(); vec2 start; vec2 end; uint count = m_Vertices.size(); for (uint i = 0; i < count; ++i) { uint j = i + 1; if (j >= count) j = 0; start = GetRotatedVert(i) + m_position; end = GetRotatedVert(j) + m_position; if (m_bIsFilled) aie::Gizmos::add2DTri(start, m_position, end, m_Colour); else aie::Gizmos::add2DLine(start, end, m_Colour); } if (SHOW_NORMALS) { uint normalCount = m_SNorms.size(); for (uint i = 0; i < normalCount; ++i) { uint j = i + 1; if (j >= count) j = 0; start = GetRotatedVert(i); end = GetRotatedVert(j); vec2 mid = ((start + end) * 0.5f) + m_position; vec2 norm = GetRotatedSNorm(i); aie::Gizmos::add2DLine(mid, norm + mid, {1, 0, 0, 1}); } } } void Poly::Move(Transform const& parentTransform, Transform const& localTransform) { m_GlobalTransform.GlobalTransform(parentTransform.GetTransform(), localTransform.GetTransform()); m_position = m_GlobalTransform.GetPosition(); m_pBroadColl->setPosition(m_position); } vec2 Poly::GetRotatedVert(int index) const { if (index >= m_Vertices.size()) assert(!"m_Vertices index OUT OF BOUNDS"); mat3 temp = m_GlobalTransform.GetTransform(); mat2 rotMat; rotMat[0][0] = temp[0][0]; rotMat[0][1] = temp[0][1]; rotMat[1][0] = temp[1][0]; rotMat[1][1] = temp[1][1]; vec2 result = rotMat * m_Vertices[index]; return result; } vec2 Poly::GetRotatedSNorm(int index) const { if (index >= m_SNorms.size()) assert(!"m_SNorms index OUT OF BOUNDS"); mat3 temp = m_GlobalTransform.GetTransform(); mat2 rotMat; rotMat[0][0] = temp[0][0]; rotMat[0][1] = temp[0][1]; rotMat[1][0] = temp[1][0]; rotMat[1][1] = temp[1][1]; vec2 result = rotMat * m_SNorms[index].norm; return result; } void Poly::Project(vec2 const & axis, float & min, float & max) { min = dot(axis, GetRotatedVert(0) + m_position); max = min; for (int i = 1; i < GetVerticeCount(); ++i) { float temp = dot(axis, GetRotatedVert(i) + m_position); if (temp < min) { min = temp; } else if (temp > max) { max = temp; } } } void Poly::CreateBroadColl() { float radius = 0; for each (vec2 vert in m_Vertices) { float temp = length(vert); if (radius < temp) radius = temp; } radius += 0.1f; if (m_pBroadColl) delete m_pBroadColl; vec4 colour = { 1,1,1,1 }; colour -= m_Colour; colour.a = 0.5f; m_pBroadColl = new Sphere(m_position, { 0,0 }, 0, m_mass, m_elasticity, 1.0f, 1.0f, 0, 0, radius, colour); m_pBroadColl->HideDirLine(); } void Poly::CreateSNorms() { m_SNorms.clear(); for (int i = 0; i < GetVerticeCount(); ++i) { int j = i + 1; if (j >= GetVerticeCount()) j = 0; vec2 vec = m_Vertices[i] - m_Vertices[j]; vec2 norm; norm.x = vec.y; norm.y = -vec.x; norm = normalize(norm); SurfaceNorm sNorm; sNorm.norm = norm; m_SNorms.push_back(sNorm); } // Parallel check for (int i = 0; i < (m_SNorms.size() - 1); ++i) { for (int j = i + 1; j < m_SNorms.size(); ++j) { vec2 lhs = m_SNorms[i].norm; vec2 rhs = m_SNorms[j].norm; float check = dot(lhs, rhs); if (abs(check) >= 1 - FLT_EPSILON) { m_SNorms[j].hasParallel = true; } } } }
#pragma once #include <iberbar/RHI/D3D11/Headers.h> #include <iberbar/RHI/RenderState.h> namespace iberbar { namespace RHI { namespace D3D11 { class CDevice; class CBlendState : public IBlendState { public: CBlendState( const UBlendDesc& Desc ) : IBlendState( Desc ) , m_pD3DBlendState( nullptr ) { } CResult Create( CDevice* pDevice ); FORCEINLINE ID3D11BlendState* GetD3DBlendState() { return m_pD3DBlendState.Get(); } protected: ComPtr<ID3D11BlendState> m_pD3DBlendState; }; class CDepthStencilState : public IDepthStencilState { public: CDepthStencilState(const UDepthStencilDesc& Desc) : IDepthStencilState( Desc ) , m_pD3DDepthStencilState( nullptr ) { } CResult Create( CDevice* pDevice ); FORCEINLINE ID3D11DepthStencilState* GetD3DDepthStencilState() { return m_pD3DDepthStencilState.Get(); } protected: ComPtr<ID3D11DepthStencilState> m_pD3DDepthStencilState; }; class CSamplerState : public ISamplerState { public: CSamplerState( const UTextureSamplerState& SamplerDesc ) : ISamplerState( SamplerDesc ) , m_pD3DSamplerState( nullptr ) { } CResult Create( CDevice* pDevice ); FORCEINLINE ID3D11SamplerState* GetD3DSamplerState() { return m_pD3DSamplerState.Get(); } protected: ComPtr<ID3D11SamplerState> m_pD3DSamplerState; }; } } }
#include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #include "../Weapon.h" #define BLASTER_SPARM_CHARGEGLOW 6 class rvWeaponBlaster : public rvWeapon { public: CLASS_PROTOTYPE( rvWeaponBlaster ); rvWeaponBlaster ( void ); virtual void Spawn ( void ); void Save ( idSaveGame *savefile ) const; void Restore ( idRestoreGame *savefile ); void PreSave ( void ); void PostSave ( void ); protected: bool UpdateAttack ( void ); bool UpdateFlashlight ( void ); void Flashlight ( bool on ); private: int chargeTime; int chargeDelay; idVec2 chargeGlow; bool fireForced; int fireHeldTime; stateResult_t State_Raise ( const stateParms_t& parms ); stateResult_t State_Lower ( const stateParms_t& parms ); stateResult_t State_Idle ( const stateParms_t& parms ); stateResult_t State_Charge ( const stateParms_t& parms ); stateResult_t State_Charged ( const stateParms_t& parms ); stateResult_t State_Fire ( const stateParms_t& parms ); stateResult_t State_Flashlight ( const stateParms_t& parms ); CLASS_STATES_PROTOTYPE ( rvWeaponBlaster ); }; CLASS_DECLARATION( rvWeapon, rvWeaponBlaster ) END_CLASS /* ================ rvWeaponBlaster::rvWeaponBlaster ================ */ rvWeaponBlaster::rvWeaponBlaster ( void ) { } /* ================ rvWeaponBlaster::UpdateFlashlight ================ */ bool rvWeaponBlaster::UpdateFlashlight ( void ) { if ( !wsfl.flashlight ) { return false; } SetState ( "Flashlight", 0 ); return true; } /* ================ rvWeaponBlaster::Flashlight ================ */ void rvWeaponBlaster::Flashlight ( bool on ) { owner->Flashlight ( on ); if ( on ) { worldModel->ShowSurface ( "models/weapons/blaster/flare" ); viewModel->ShowSurface ( "models/weapons/blaster/flare" ); } else { worldModel->HideSurface ( "models/weapons/blaster/flare" ); viewModel->HideSurface ( "models/weapons/blaster/flare" ); } } /* ================ rvWeaponBlaster::UpdateAttack ================ */ bool rvWeaponBlaster::UpdateAttack ( void ) { // Clear fire forced if ( fireForced ) { if ( !wsfl.attack ) { fireForced = false; } else { return false; } } // If the player is pressing the fire button and they have enough ammo for a shot // then start the shooting process. if ( wsfl.attack && gameLocal.time >= nextAttackTime ) { // Save the time which the fire button was pressed if ( fireHeldTime == 0 ) { nextAttackTime = gameLocal.time + (fireRate * owner->PowerUpModifier ( PMOD_FIRERATE )); fireHeldTime = gameLocal.time; viewModel->SetShaderParm ( BLASTER_SPARM_CHARGEGLOW, chargeGlow[0] ); } } // If they have the charge mod and they have overcome the initial charge // delay then transition to the charge state. if ( fireHeldTime != 0 ) { if ( gameLocal.time - fireHeldTime > chargeDelay ) { SetState ( "Charge", 4 ); return true; } // If the fire button was let go but was pressed at one point then // release the shot. if ( !wsfl.attack ) { idPlayer * player = gameLocal.GetLocalPlayer(); if( player ) { if( player->GuiActive()) { //make sure the player isn't looking at a gui first SetState ( "Lower", 0 ); } else { SetState ( "Fire", 0 ); } } return true; } } return false; } /* ================ rvWeaponBlaster::Spawn ================ */ void rvWeaponBlaster::Spawn ( void ) { viewModel->SetShaderParm ( BLASTER_SPARM_CHARGEGLOW, 0 ); SetState ( "Raise", 0 ); chargeGlow = spawnArgs.GetVec2 ( "chargeGlow" ); chargeTime = SEC2MS ( spawnArgs.GetFloat ( "chargeTime" ) ); chargeDelay = SEC2MS ( spawnArgs.GetFloat ( "chargeDelay" ) ); fireHeldTime = 0; fireForced = false; Flashlight ( owner->IsFlashlightOn() ); } /* ================ rvWeaponBlaster::Save ================ */ void rvWeaponBlaster::Save ( idSaveGame *savefile ) const { savefile->WriteInt ( chargeTime ); savefile->WriteInt ( chargeDelay ); savefile->WriteVec2 ( chargeGlow ); savefile->WriteBool ( fireForced ); savefile->WriteInt ( fireHeldTime ); } /* ================ rvWeaponBlaster::Restore ================ */ void rvWeaponBlaster::Restore ( idRestoreGame *savefile ) { savefile->ReadInt ( chargeTime ); savefile->ReadInt ( chargeDelay ); savefile->ReadVec2 ( chargeGlow ); savefile->ReadBool ( fireForced ); savefile->ReadInt ( fireHeldTime ); } /* ================ rvWeaponBlaster::PreSave ================ */ void rvWeaponBlaster::PreSave ( void ) { SetState ( "Idle", 4 ); StopSound( SND_CHANNEL_WEAPON, 0); StopSound( SND_CHANNEL_BODY, 0); StopSound( SND_CHANNEL_ITEM, 0); StopSound( SND_CHANNEL_ANY, false ); } /* ================ rvWeaponBlaster::PostSave ================ */ void rvWeaponBlaster::PostSave ( void ) { } /* =============================================================================== States =============================================================================== */ CLASS_STATES_DECLARATION ( rvWeaponBlaster ) STATE ( "Raise", rvWeaponBlaster::State_Raise ) STATE ( "Lower", rvWeaponBlaster::State_Lower ) STATE ( "Idle", rvWeaponBlaster::State_Idle) STATE ( "Charge", rvWeaponBlaster::State_Charge ) STATE ( "Charged", rvWeaponBlaster::State_Charged ) STATE ( "Fire", rvWeaponBlaster::State_Fire ) STATE ( "Flashlight", rvWeaponBlaster::State_Flashlight ) END_CLASS_STATES /* ================ rvWeaponBlaster::State_Raise ================ */ stateResult_t rvWeaponBlaster::State_Raise( const stateParms_t& parms ) { enum { RAISE_INIT, RAISE_WAIT, }; switch ( parms.stage ) { case RAISE_INIT: SetStatus ( WP_RISING ); PlayAnim( ANIMCHANNEL_ALL, "raise", parms.blendFrames ); return SRESULT_STAGE(RAISE_WAIT); case RAISE_WAIT: if ( AnimDone ( ANIMCHANNEL_ALL, 4 ) ) { SetState ( "Idle", 4 ); return SRESULT_DONE; } if ( wsfl.lowerWeapon ) { SetState ( "Lower", 4 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponBlaster::State_Lower ================ */ stateResult_t rvWeaponBlaster::State_Lower ( const stateParms_t& parms ) { enum { LOWER_INIT, LOWER_WAIT, LOWER_WAITRAISE }; switch ( parms.stage ) { case LOWER_INIT: SetStatus ( WP_LOWERING ); PlayAnim( ANIMCHANNEL_ALL, "putaway", parms.blendFrames ); return SRESULT_STAGE(LOWER_WAIT); case LOWER_WAIT: if ( AnimDone ( ANIMCHANNEL_ALL, 0 ) ) { SetStatus ( WP_HOLSTERED ); return SRESULT_STAGE(LOWER_WAITRAISE); } return SRESULT_WAIT; case LOWER_WAITRAISE: if ( wsfl.raiseWeapon ) { SetState ( "Raise", 0 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponBlaster::State_Idle ================ */ stateResult_t rvWeaponBlaster::State_Idle ( const stateParms_t& parms ) { enum { IDLE_INIT, IDLE_WAIT, }; switch ( parms.stage ) { case IDLE_INIT: SetStatus ( WP_READY ); PlayCycle( ANIMCHANNEL_ALL, "idle", parms.blendFrames ); return SRESULT_STAGE ( IDLE_WAIT ); case IDLE_WAIT: if ( wsfl.lowerWeapon ) { SetState ( "Lower", 4 ); return SRESULT_DONE; } if ( UpdateFlashlight ( ) ) { return SRESULT_DONE; } if ( UpdateAttack ( ) ) { return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponBlaster::State_Charge ================ */ stateResult_t rvWeaponBlaster::State_Charge ( const stateParms_t& parms ) { enum { CHARGE_INIT, CHARGE_WAIT, }; switch ( parms.stage ) { case CHARGE_INIT: viewModel->SetShaderParm ( BLASTER_SPARM_CHARGEGLOW, chargeGlow[0] ); StartSound ( "snd_charge", SND_CHANNEL_ITEM, 0, false, NULL ); PlayCycle( ANIMCHANNEL_ALL, "charging", parms.blendFrames ); return SRESULT_STAGE ( CHARGE_WAIT ); case CHARGE_WAIT: if ( gameLocal.time - fireHeldTime < chargeTime ) { float f; f = (float)(gameLocal.time - fireHeldTime) / (float)chargeTime; f = chargeGlow[0] + f * (chargeGlow[1] - chargeGlow[0]); f = idMath::ClampFloat ( chargeGlow[0], chargeGlow[1], f ); viewModel->SetShaderParm ( BLASTER_SPARM_CHARGEGLOW, f ); if ( !wsfl.attack ) { SetState ( "Fire", 0 ); return SRESULT_DONE; } return SRESULT_WAIT; } SetState ( "Charged", 4 ); return SRESULT_DONE; } return SRESULT_ERROR; } /* ================ rvWeaponBlaster::State_Charged ================ */ stateResult_t rvWeaponBlaster::State_Charged ( const stateParms_t& parms ) { enum { CHARGED_INIT, CHARGED_WAIT, }; switch ( parms.stage ) { case CHARGED_INIT: viewModel->SetShaderParm ( BLASTER_SPARM_CHARGEGLOW, 1.0f ); StopSound ( SND_CHANNEL_ITEM, false ); StartSound ( "snd_charge_loop", SND_CHANNEL_ITEM, 0, false, NULL ); StartSound ( "snd_charge_click", SND_CHANNEL_BODY, 0, false, NULL ); return SRESULT_STAGE(CHARGED_WAIT); case CHARGED_WAIT: if ( !wsfl.attack ) { fireForced = true; SetState ( "Fire", 0 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponBlaster::State_Fire ================ */ stateResult_t rvWeaponBlaster::State_Fire ( const stateParms_t& parms ) { enum { FIRE_INIT, FIRE_WAIT, }; switch ( parms.stage ) { case FIRE_INIT: StopSound ( SND_CHANNEL_ITEM, false ); viewModel->SetShaderParm ( BLASTER_SPARM_CHARGEGLOW, 0 ); //don't fire if we're targeting a gui. idPlayer* player; player = gameLocal.GetLocalPlayer(); //make sure the player isn't looking at a gui first if( player && player->GuiActive() ) { fireHeldTime = 0; SetState ( "Lower", 0 ); return SRESULT_DONE; } if( player && !player->CanFire() ) { fireHeldTime = 0; SetState ( "Idle", 4 ); return SRESULT_DONE; } if ( gameLocal.time - fireHeldTime > chargeTime ) { Attack ( true, 1, spread, 0, 1.0f ); PlayEffect ( "fx_chargedflash", barrelJointView, false ); PlayAnim( ANIMCHANNEL_ALL, "chargedfire", parms.blendFrames ); } else { Attack ( false, 1, spread, 0, 1.0f ); PlayEffect ( "fx_normalflash", barrelJointView, false ); PlayAnim( ANIMCHANNEL_ALL, "fire", parms.blendFrames ); } fireHeldTime = 0; return SRESULT_STAGE(FIRE_WAIT); case FIRE_WAIT: if ( AnimDone ( ANIMCHANNEL_ALL, 4 ) ) { SetState ( "Idle", 4 ); return SRESULT_DONE; } if ( UpdateFlashlight ( ) || UpdateAttack ( ) ) { return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponBlaster::State_Flashlight ================ */ stateResult_t rvWeaponBlaster::State_Flashlight ( const stateParms_t& parms ) { enum { FLASHLIGHT_INIT, FLASHLIGHT_WAIT, }; switch ( parms.stage ) { case FLASHLIGHT_INIT: SetStatus ( WP_FLASHLIGHT ); // Wait for the flashlight anim to play PlayAnim( ANIMCHANNEL_ALL, "flashlight", 0 ); return SRESULT_STAGE ( FLASHLIGHT_WAIT ); case FLASHLIGHT_WAIT: if ( !AnimDone ( ANIMCHANNEL_ALL, 4 ) ) { return SRESULT_WAIT; } if ( owner->IsFlashlightOn() ) { Flashlight ( false ); } else { Flashlight ( true ); } SetState ( "Idle", 4 ); return SRESULT_DONE; } return SRESULT_ERROR; }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef XPATH_SUPPORT #include "modules/xpath/src/xpstringset.h" XPath_StringSet::~XPath_StringSet () { Clear (); } BOOL XPath_StringSet::AddL (const uni_char *string) { uni_char *copy; if (string && *string) { unsigned count = uni_strlen (string) + 1; copy = OP_NEWA_L (uni_char, count); uni_strcpy (copy, string); } else copy = const_cast<uni_char *> (UNI_L ("")); OP_STATUS status = OpGenericStringHashTable::Add (copy, copy); if (status == OpStatus::OK) return TRUE; else { if (*copy) OP_DELETEA (copy); if (status != OpStatus::ERR) LEAVE (status); return FALSE; } } BOOL XPath_StringSet::Contains (const uni_char *string) { return OpGenericStringHashTable::Contains (string ? string : UNI_L ("")); } void XPath_StringSet_DeleteString (const void *key, void *data) { /* Empty strings are stored unallocated, so we shouldn't delete them. */ uni_char *string = static_cast<uni_char *> (data); if (*string) OP_DELETEA (string); } void XPath_StringSet::Clear () { OpGenericStringHashTable::ForEach (XPath_StringSet_DeleteString); OpGenericStringHashTable::RemoveAll (); } #endif // XPATH_SUPPORT
#pragma once #include "Cube.h" #define CUBE_DIMENSION 3 #define CUBE_COUNT 27 /** * @brief 以前面的那一层开始,左上角方块记号0,横向扫描,左边记号3,左下记号6 * 再中间层,左上角9,最后层,左上角18 */ class MagicCube { // 魔方的中心 TOOL_CREATE_GET(Point*, center, Center); // 魔方的每个方块的边长 TOOL_CREATE_GET(GLfloat, eachSide, EachSide); // 魔方的相邻方块之间的间距 TOOL_CREATE_GET(GLfloat, betweenGap, BetweenGap); /** * @brief 旋转方向 * @enmu IDLE,CLOCKWISE,ANTI_CLOCKWISE中的一个 */ TOOL_CREATE_GET(GLint, orientation, Orientation); /** * @biref 旋转的面 * @enmu ROTATE_FRONT, ROTATE_LEFT, ROTATE_BOTTOM * ROTATE_RIGHT, ROTATE_TOP, ROTATE_BACK */ TOOL_CREATE_GET(GLint, rotateSurface, RotateSurface); private: Cube* cubes[CUBE_COUNT]; // 已经转了多少角度 GLdouble angle; // 旋转开始的时间 INT64 startMilliTime; void init(Point center, GLfloat eachSide, GLfloat betweenGap); protected: /** * @brief 实际绘图函数 */ void onDraw(); void rotateFront(); void rotateLeft(); void rotateBottom(); void rotateRight(); void rotateTop(); void rotateBack(); public: static const long ANIMATION_DURATION = 800; // 毫秒 static const GLint IDLE = 0; static const GLint CLOCKWISE = 1; static const GLint ANTI_CLOCKWISE = 2; static const GLint ROTATE_FRONT = 0; static const GLint ROTATE_LEFT = 1; static const GLint ROTATE_BOTTOM = 2; static const GLint ROTATE_RIGHT = 3; static const GLint ROTATE_TOP = 4; static const GLint ROTATE_BACK = 5; static const GLint SURFACE_FRONT[CUBE_DIMENSION*CUBE_DIMENSION]; static const GLint SURFACE_LEFT[CUBE_DIMENSION*CUBE_DIMENSION]; static const GLint SURFACE_BOTTOM[CUBE_DIMENSION*CUBE_DIMENSION]; static const GLint SURFACE_RIGHT[CUBE_DIMENSION*CUBE_DIMENSION]; static const GLint SURFACE_TOP[CUBE_DIMENSION*CUBE_DIMENSION]; static const GLint SURFACE_BACK[CUBE_DIMENSION*CUBE_DIMENSION]; static const GLint SWAP_CLOCKWISE[CUBE_DIMENSION*CUBE_DIMENSION]; static const GLint SWAP_ANTI_CLOCKWISE[CUBE_DIMENSION*CUBE_DIMENSION]; MagicCube(); MagicCube(GLfloat eachSide); // 中心位于(0,0,0),betweenGap=0 MagicCube(GLfloat eachSide, GLfloat betweenGap); // 中心位于(0,0,0) MagicCube(Point center, GLfloat eachSide); // betweenGap=0 MagicCube(Point center, GLfloat eachSide, GLfloat betweenGap); ~MagicCube(); /** * @brief 传递绘图,调用onDraw() */ void dispatchDraw(); /** * @brief 启动一个旋转 */ void startRotate(GLint orientation, GLint rotateSurface); /** * @brief 计算旋转之后的变化 */ void calulateRotate(); /** * @brief 是否需要重新设定旋转 * @note main.cpp 中的idle()中调用 */ GLboolean isNeedRefresh(); };
/* -*- C++ -*- */ // Time-stamp: <03/16/2009 10:42:25 星期一 by (>>>USER_NAME<<<)> /** * @file (>>>FILE<<<) * @author (>>>USER_NAME<<<) */ #include "(>>>FILE_SANS<<<).h" (>>>POINT<<<)
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/dom/src/domclonehandler.h" #include "modules/dom/src/canvas/domcontext2d.h" #include "modules/dom/src/opera/domformdata.h" #include "modules/dom/src/domfile/domblob.h" /* virtual */ OP_STATUS DOM_CloneHandler::Clone(EcmaScript_Object *source_object, ES_Runtime *target_runtime, EcmaScript_Object *&target_object) { #ifdef CANVAS_SUPPORT if (source_object->IsA(DOM_TYPE_CANVASIMAGEDATA)) { DOMCanvasImageData *target; RETURN_IF_ERROR(DOMCanvasImageData::Clone(static_cast<DOMCanvasImageData *>(source_object), target_runtime, target)); target_object = target; return OpStatus::OK; } #endif // CANVAS_SUPPORT #ifdef DOM_HTTP_SUPPORT if (source_object->IsA(DOM_TYPE_FORMDATA)) { DOM_FormData *target; RETURN_IF_ERROR(DOM_FormData::Clone(static_cast<DOM_FormData *>(source_object), target_runtime, target)); target_object = target; return OpStatus::OK; } #endif // DOM_HTTP_SUPPORT if (source_object->IsA(DOM_TYPE_BLOB)) { DOM_Blob *target; RETURN_IF_ERROR(DOM_Blob::Clone(static_cast<DOM_Blob *>(source_object), target_runtime, target)); target_object = target; return OpStatus::OK; } return OpStatus::ERR; } #ifdef ES_PERSISTENT_SUPPORT /* virtual */ OP_STATUS DOM_CloneHandler::Clone(EcmaScript_Object *source_object, ES_PersistentItem *&target_item) { #ifdef CANVAS_SUPPORT if (source_object->IsA(DOM_TYPE_CANVASIMAGEDATA)) { RETURN_IF_ERROR(DOMCanvasImageData::Clone(static_cast<DOMCanvasImageData *>(source_object), target_item)); return OpStatus::OK; } #endif // CANVAS_SUPPORT #ifdef DOM_HTTP_SUPPORT if (source_object->IsA(DOM_TYPE_FORMDATA)) { RETURN_IF_ERROR(DOM_FormData::Clone(static_cast<DOM_FormData *>(source_object), target_item)); return OpStatus::OK; } #endif // DOM_HTTP_SUPPORT if (source_object->IsA(DOM_TYPE_BLOB)) { RETURN_IF_ERROR(DOM_Blob::Clone(static_cast<DOM_Blob *>(source_object), target_item)); return OpStatus::OK; } return OpStatus::ERR; } /* virtual */ OP_STATUS DOM_CloneHandler::Clone(ES_PersistentItem *&source_item, ES_Runtime *target_runtime, EcmaScript_Object *&target_object) { #ifdef CANVAS_SUPPORT if (source_item->IsA(DOM_TYPE_CANVASIMAGEDATA)) { DOMCanvasImageData *target; RETURN_IF_ERROR(DOMCanvasImageData::Clone(source_item, target_runtime, target)); target_object = target; return OpStatus::OK; } #endif // CANVAS_SUPPORT #ifdef DOM_HTTP_SUPPORT if (source_item->IsA(DOM_TYPE_FORMDATA)) { DOM_FormData *target; RETURN_IF_ERROR(DOM_FormData::Clone(source_item, target_runtime, target)); target_object = target; return OpStatus::OK; } #endif // DOM_HTTP_SUPPORT if (source_item->IsA(DOM_TYPE_BLOB)) { DOM_Blob *target; RETURN_IF_ERROR(DOM_Blob::Clone(source_item, target_runtime, target)); target_object = target; return OpStatus::OK; } return OpStatus::ERR; } #endif // ES_PERSISTENT_SUPPORT
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QtGui> #include <QLabel> #include <QMessageBox> #include <QThread> #include "ui_mainwindow.h" #include "chemcontroller.h" #include <formreacsettings.h> #include <formtstatconfig.h> #include <config.h> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); void Connect(); void Disconnect(); void TurnOnTemp(); void TurnOffTemp(); void ReacSettings(); void TStatConfig(); public slots: private slots: void on_set_tempbox_valueChanged(double arg1); void on_ModeCH1_currentIndexChanged(int index); void on_Range1_currentIndexChanged(int index); void on_SpeedCode1_valueChanged(int arg1); void on_Pressure1_valueChanged(double arg1); void on_ModeCH2_currentIndexChanged(int index); void on_Range2_currentIndexChanged(int index); void on_SpeedCode2_valueChanged(int arg1); void on_Pressure2_valueChanged(double arg1); void on_ModeCH3_currentIndexChanged(int index); void on_Range3_currentIndexChanged(int index); void on_SpeedCode3_valueChanged(int arg1); void on_Pressure3_valueChanged(double arg1); void on_ModeCH4_currentIndexChanged(int index); void on_Range4_currentIndexChanged(int index); void on_SpeedCode4_valueChanged(int arg1); void on_Pressure4_valueChanged(double arg1); private: Ui::MainWindow *ui; // Статусы в StatusBar QLabel *lblStatus; QLabel *StatusTStat; QLabel *StatusReac; ChemController *_chemcontroller; SysConfig *_sysconfig; DevSettings *_devsettings; // Экземпляры окон FormReacSettings *_reacSettings; FormTStatConfig * _tStatConfig; QString DevSettingsFile = "E:\\ChemControllerGUI\\ChemControllerGUI\\Settings.cnf"; QString DevConfigFile = "E:\\ChemControllerGUI\\ChemControllerGUI\\Config.cnf"; // Таймер для обновления данных QTimer *_TimerRefreshInfo; int *PSC_CHx; void ErrorMessage(QString err); void Refresh(); // void PressDisp(int ch, QLabel *label); void TemperDisplay(int ch, QLabel *label); void PowerDisp(QLabel *label); void ReacDispMode(int ch, QComboBox *cmb); void ReacDispRange(int ch, QComboBox *cmbRange, int R1, int R2, int R3); void ReacDispVelCode(int ch, QSpinBox *numVelCode); void ReacDispPress(int ch, QDoubleSpinBox *numPress); void ChXModeAuto(QComboBox *cmbRange, QSpinBox *VelCode, QDoubleSpinBox *Set); void ChXModeManual(QComboBox *cmbRange, QSpinBox *VelCode, QDoubleSpinBox *Set); void SyrRangeDisp(QLabel *label, QComboBox *combo, int Psc, int ReacCHx_Len, qreal ReacCHx_Vol, int ReacCHx_MicroStep, int RefFreq); void SyrVelocityDisp(QLabel *label, QComboBox *combo, int VelCode, int Psc, int ReacCHx_Len, qreal ReacCHx_Vol, int ReacCHx_MicroStep, int RefFreq); void SyrVolDisp(int ch, QLabel *label, int ReacCHx_Len, qreal ReacCHx_Vol, int ReacCHx_MicroStep); // void StatusConnected(); void StatusDisconnected(); void StatusTStatEnable(); void StatusTStatDisable(); void StatusReacEnable(); void StatusReacDisable(); // void UploadConfig(); void UploadReacConfig(); void UploadTStatPID(); void UploadTStatCoeff(); void SafeConfig(); void SettingsDefault(); void ConfigDefault(); void LoadConfig(); void ReacRecalibration(); void ReacStart(); void ReacStop(); void ReacSetSyrMode(int ch, int mode); void ReacSetRange(int ch, int Psc); void ReacSetVelCode(int ch, int val); void ReacSetPress_(int ch, qreal val); void ReacSetPID(); qreal SyrCode2Vol(int c, int ReacCHx_Len, qreal ReacCHx_Vol, int ReacCHx_MicroStep); qreal SyrVelocity(int VelCode, int Psc, int ReacCHx_Len, qreal ReacCHx_Vol, int ReacCHx_MicroStep, int RefFreq); void TStatSetTemper(double val); }; #endif // MAINWINDOW_H
#include <FHandle.h> #include <stdio.h> // To judge if a double number is a interge. bool isInt(const double& x) { return ( x == (int)x ); } // Get the sign of a double number. int sgn(const double& x) { if(x > 0) { return 1; } else if(x < 0) { return -1; } else // if(x == 0) { return -1; } } // Convert string to a double number. double string2double(const string& str) { double result; stringstream ss; ss << str; ss >> result; return result; } vector<double> varargin2vector() { return vector<double>(1, 0.); } // Delete spaces in a string. string delete_space(string str) { for(string::iterator it = str.begin(); it != str.end(); it++) { if(*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r') { str.erase(it); it--; } } return str; } // Element's constructors without initial value Element::Element() { type = 0; identify = 0; data = 0; } // Element's constructors with initial value Element::Element(int t, int i, double d) { type = t; identify = i; data = d; } // Element's copy constructor Element::Element(const Element& X) { type = X.type; identify = X.identify; data = X.data; } // Reload the operator "=" of class Element Element& Element::operator =(const Element& X) { type = X.type; identify = X.identify; data = X.data; return *this; } // Reload the operator "==" of class Element bool Element::operator ==(const Element& X) { return (type == X.type && identify == X.identify && data == X.data); } // Reload the operator "!=" of class Element bool Element::operator !=(const Element& X) { return !(*this == X); } // Define the cout format of class Element ostream& operator <<(ostream& o, const Element& X) { switch(X.type) { case 1: { if(X.identify == 0) { o << X.data; } else { o << "x" << X.identify; } break; } case 0: { switch(X.identify) { case 0 : o << "#"; break; case 1 : o << "+"; break; case 2 : o << "-"; break; case 3 : o << "*"; break; case 4 : o << "/"; break; case 5 : o << "^"; break; case 6 : o << "("; break; case 7 : o << ")"; break; case 8 : o << "sin"; break; case 9 : o << "cos"; break; case 10: o << "tan"; break; case 11: o << "csc"; break; case 12: o << "sec"; break; case 13: o << "cot"; break; case 14: o << "asin"; break; case 15: o << "acos"; break; case 16: o << "atan"; break; case 17: o << "acsc"; break; case 18: o << "asec"; break; case 19: o << "acot"; break; case 20: o << "sinh"; break; case 21: o << "cosh"; break; case 22: o << "tanh"; break; case 23: o << "csch"; break; case 24: o << "sech"; break; case 25: o << "coth"; break; case 26: o << "asinh"; break; case 27: o << "acosh"; break; case 28: o << "atanh"; break; case 29: o << "acsch"; break; case 30: o << "asech"; break; case 31: o << "acoth"; break; case 32: o << "exp"; break; case 33: o << "log"; break; case 34: o << "lg"; break; case 35: o << "ln"; break; case 36: o << "sqrt"; break; case 37: o << "abs"; break; default: o << "WRONG"; break; } } default: o << "WRONG"; break; } return o; } // FHandle's constructor without initial value FHandle::FHandle() { if(!empty()) { clear(); } variable_system = 0; n_variables = 0; } // FHandle's copy constructor FHandle::FHandle(const FHandle& g) { if(!empty()) { clear(); } variable_system = g.variable_system; n_variables = g.n_variables; Postfix = g.Postfix; f_str = g.f_str; } // Function: FHandle::FHandle(const string&); // // Description: FHandle's constructor with given std::string. // // Calls: string delete_space(const string&); // // Defined in current file. // // void FHandle::set_postfix_from_infix_string(string); // // Declared in "./FHandle.h". // // Defined in "./infix2postfix.cpp". // // Input Parameter: const string& str: expression string be waited to convert to FHandle. // // Output Parameter: Nothing. // // Return: void. FHandle::FHandle(const string& str) { if(!empty()) { clear(); } variable_system = 0; n_variables = 0; string empty_str; f_str = delete_space(str); set_postfix_from_infix_string(str); check(); } // FHandle's constructor with given char* FHandle::FHandle(const char* c_str) { if(!empty()) { clear(); } variable_system = 0; n_variables = 0; string str(c_str); f_str = delete_space(str); set_postfix_from_infix_string(str); check(); } FHandle::FHandle(const double& k) { if(!empty()) { clear(); } variable_system = 0; n_variables = 0; f_str = cout2str(k); Postfix.clear(); vector<Element>().swap(Postfix); Postfix.push_back(Element(1, 0, k)); } FHandle::FHandle(const int& k) { if(!empty()) { clear(); } variable_system = 0; n_variables = 0; f_str = cout2str(k); Postfix.clear(); vector<Element>().swap(Postfix); Postfix.push_back(Element(1, 0, (double)k)); } // Function: FHandle& FHandle::operator =(const FHandle&); // // Description: Reload of FHandle's operator "=". // Make it possible to clone a FHandle to another by using "=". // // Calls: Nothing. // // Input Parameter: const FHandle& f: FHandle on the right of "=" // // Output Parameter: Nothing. // // Return: the reference of FHandle on the right of "=". FHandle& FHandle::operator =(const FHandle& f) { if(!empty()) { clear(); } variable_system = f.variable_system; n_variables = f.n_variables; Postfix = f.Postfix; f_str = f.f_str; return *this; } // Function: FHandle& FHandle::operator =(const string&); // // Description: Reload of FHandle's operator "=". // Make it possible to convert from string to FHandle by using "=". // // Calls: FHandle::FHandle(const string&); // // Declared in "./FHandle.h". // // Defined in current file. // // Input Parameter: const string& str: string on the right of "=". // // Output Parameter: Nothing. // // Return: the reference of FHandle after "=". FHandle& FHandle::operator =(const string& str) { *this = FHandle(str); return *this; } // Function: FHandle& FHandle::operator =(const char*); // // Description: Reload of FHandle's operator "=". // Make it possible to convert from string to FHandle by using "=". // // Input Parameter: const char* c_str: C style string on the right of "=". // // Output Parameter: Nothing. // // Return: the reference of FHandle after "=". FHandle& FHandle::operator =(const char* c_str) { *this = FHandle(c_str); return *this; } void FHandle::check() { if( Postfix.empty() ) { return; } stack<double> Object; Element element; for(vector<Element>::const_iterator it = Postfix.begin(); it != Postfix.end(); it++) { element = *it; switch(element.type) { case 1://ele_temp is number or "PI" or variables { Object.push(0); break; } case 0://ele_temp is operator { if(Object.empty()) { clear(); return; } if(element.identify >= 1 && element.identify <= 5) { Object.pop(); if(Object.empty()) { clear(); return; } } else if(element.identify == 6 || element.identify == 7 || element.identify >= 38) { clear(); return; } break; } default: { clear(); return; } } } if(Object.size() != 1) { clear(); return; } } // Define the cout format of class FHandle ostream& operator <<(ostream& o, const FHandle& f) { o << f.f_str; return o; } // Define the cin method of class FHandle. // Firstly get a string from the screen. // Then convert string into FHandle. istream& operator >>(istream& i, FHandle& f) { string str; getline(cin, str); f = str; f.check(); return i; } FHandle& FHandle::input(const string& str_promt) { string str; cout << str_promt; getline(cin, str); *this = str; check(); return *this; } // Function: void FHandle::clear(); // // Description: Clear FHandle's memory. // // Calls: FHandle::~FHandle() // // Declared in ./FHandle.h // // Defined in current file. // // Input Parameter: Nothing // // Output Parameter: Nothing // // Return: void. void FHandle::clear() { variable_system = 0; n_variables = 0; Postfix.clear(); vector<Element>().swap(Postfix); f_str.clear(); string().swap(f_str); } // Function: bool FHandle::empty()const; // // Description: To judge a FHandle is empty or not. // // Calls: Nothing. // // Input Parameter: Nothing // // Output Parameter: Nothing // // Return: "true" when FHandle is empty. bool FHandle::empty()const { return Postfix.empty(); } typedef struct IndexValue { int index; double value; }IndexValue; bool LessSort(IndexValue X, IndexValue Y) { return X.index < Y.index; } double getNumberData(const string& str, int i) { int i0 = i; while( isNumber(str[i]) ) { i++; } return string2double( str.substr(i0, i-i0) ); } FHandle FHandle::fix_variable(const vector<int>& indexs, const vector<double>& values) { int n = indexs.size(); if(n != (int)values.size()) { cout << "Error in fix_variable! index length and values length are not equal!" << endl; exit(-1); } IndexValue Empty_IndexValue; vector<IndexValue> IndexValue_vector(n, Empty_IndexValue); vector<int>::const_iterator it_index = indexs.begin(); vector<double>::const_iterator it_value = values.begin(); for(vector<IndexValue>::iterator it = IndexValue_vector.begin(); it != IndexValue_vector.end(); it++) { it->index = *it_index; it->value = *it_value; it_index++; it_value++; } sort(IndexValue_vector.begin(), IndexValue_vector.end(), LessSort); for(vector<IndexValue>::iterator it = IndexValue_vector.begin(); it != IndexValue_vector.end(); it++) { if(it->index == (it+1)->index) { IndexValue_vector.erase(it); it--; } } FHandle fnew = *this; for(vector<IndexValue>::iterator it = IndexValue_vector.begin(); it != IndexValue_vector.end(); it++) { fnew = fnew.fix_variable(it->index, it->value); } return fnew; } void replace_all_variable(string& str, const string& str_old, const string& str_new) { int start_position = 0; int old_str_position = str.find(str_old, start_position); while(old_str_position != -1) { if(str_old == "x") { if(!isNumber(str[old_str_position+1]) && str[old_str_position+1] != 'p') { str.replace(old_str_position, str_old.size(), str_new); } } else { str.replace(old_str_position, str_old.size(), str_new); } start_position = old_str_position + 1; old_str_position = str.find(str_old, start_position); } } FHandle FHandle::fix_variable(int index, double value) { index = abs(index); if(index == 0) { return *this; } FHandle fnew = *this; int start_position = 0; int variable_position = fnew.f_str.find('x', start_position); while(variable_position != -1) { if( isNumber(fnew.f_str[variable_position+1]) ) { int old_index = (int)getNumberData(fnew.f_str, variable_position+1); string str_old_index = cout2str(old_index); if(old_index > index) { int new_index = old_index-1; string str_new_index = cout2str(new_index); fnew.f_str.replace(variable_position+1, str_old_index.size(), str_new_index); } else if(old_index == index) { fnew.f_str.replace(variable_position, str_old_index.size()+1, "("+cout2str(value)+")"); } } start_position = variable_position + 1; variable_position = fnew.f_str.find('x', start_position); } if(index == 1 || index == 2 || index == 3) { start_position = 0; switch(index) { case 1: { replace_all_variable(fnew.f_str, "x", "("+cout2str(value)+")"); replace_all_variable(fnew.f_str, "y", "x"); replace_all_variable(fnew.f_str, "z", "y"); break; } case 2: { replace_all_variable(fnew.f_str, "y", "("+cout2str(value)+")"); replace_all_variable(fnew.f_str, "z", "y"); break; } case 3: { replace_all_variable(fnew.f_str, "z", "("+cout2str(value)+")"); break; } } } bool flag = false; for(vector<Element>::iterator it = fnew.Postfix.begin(); it != fnew.Postfix.end(); it++) { if(it->type == 1 && it->identify == index) { flag = true; *it = Element(1, 0, value); } if(it->type == 1 && it->identify > index) { flag = true; it->identify--; } } if(flag) { n_variables--; } return fnew; } FHandle operator +(const FHandle& f1 , const FHandle& f2) { FHandle f_result; if(f1.empty() || f2.empty() || f1.variable_system != f2.variable_system) { return f_result; } string str = "(" + f1.f_str + ") + (" + f2.f_str + ")"; f_result = str; return f_result; } FHandle operator +(const FHandle& f1, const double& k) { return f1 + FHandle(k); } FHandle operator +(const double& k, const FHandle& f2) { return FHandle(k) + f2; } FHandle operator -(const FHandle& f1 , const FHandle& f2) { FHandle f_result; if(f1.empty() || f2.empty() || f1.variable_system != f2.variable_system) { return f_result; } string str = "(" + f1.f_str + ") - (" + f2.f_str + ")"; f_result = str; return f_result; } FHandle operator -(const FHandle& f1, const double& k) { return f1 - FHandle(k); } FHandle operator -(const double& k, const FHandle& f2) { return FHandle(k) - f2; } FHandle operator *(const FHandle& f1 , const FHandle& f2) { FHandle f_result; if(f1.empty() || f2.empty() || f1.variable_system != f2.variable_system) { return f_result; } string str = "(" + f1.f_str + ") * (" + f2.f_str + ")"; f_result = str; return f_result; } FHandle operator *(const FHandle& f1, const double& k) { return f1 * FHandle(k); } FHandle operator *(const double& k, const FHandle& f2) { return FHandle(k) * f2; } FHandle operator /(const FHandle& f1 , const FHandle& f2) { FHandle f_result; if(f1.empty() || f2.empty() || f1.variable_system != f2.variable_system) { return f_result; } string str = "(" + f1.f_str + ") / (" + f2.f_str + ")"; f_result = str; return f_result; } FHandle operator /(const FHandle& f1, const double& k) { FHandle empty_func; if(k == 0) { return empty_func; } return f1 / FHandle(k); } FHandle operator /(const double& k, const FHandle& f2) { return FHandle(k) / f2; } FHandle operator ^(const FHandle& f1 , const FHandle& f2) { FHandle f_result; if(f1.empty() || f2.empty() || f1.variable_system != f2.variable_system) { return f_result; } string str = "(" + f1.f_str + ") ^ (" + f2.f_str + ")"; f_result = str; return f_result; } FHandle operator ^(const FHandle& f1, const double& k) { return f1 ^ FHandle(k); } FHandle operator ^(const double& k, const FHandle& f2) { return FHandle(k) ^ f2; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #if defined(_JPG_SUPPORT_) && defined(USE_JAYPEG) #include "modules/jaypeg/src/jaystream.h" JayStream::JayStream() : buffer(NULL), bufferlen(0) {} void JayStream::initData(const unsigned char *buf, unsigned int len) { buffer = buf; bufferlen = len; } #endif
#include <lwr4p_bhand_test/utils.h> using namespace as64_; int main(int argc, char **argv) { ros::init(argc, argv, "lwr4p_robot_test"); ros::NodeHandle nh("~"); bool run = true; // give some time to other nodes (rviz) to start as well std::this_thread::sleep_for(std::chrono::milliseconds(1500)); // ============================================ // =========== Parse values ================== // ============================================ std::string robot_desc; if (!nh.getParam("robot_description_name",robot_desc)) throw std::ios_base::failure("Failed to read parameter \"robot_description_name\"."); std::vector<double> q_vec; // =========== lwr args ================== std::string lwr_base_link; std::string lwr_tool_link; double lwr_ctrl_cycle; arma::vec lwr_q1; arma::vec lwr_q2; double lwr_time_duration; // sec bool lwr_use_sim; if (!nh.getParam("lwr_base_link",lwr_base_link)) throw std::ios_base::failure("Failed to read parameter \"lwr_base_link\"."); if (!nh.getParam("lwr_tool_link",lwr_tool_link)) throw std::ios_base::failure("Failed to read parameter \"lwr_tool_link\"."); if (!nh.getParam("lwr_ctrl_cycle",lwr_ctrl_cycle)) throw std::ios_base::failure("Failed to read parameter \"lwr_ctrl_cycle\"."); if (!nh.getParam("lwr_q1",q_vec)) throw std::ios_base::failure("Failed to read parameter \"lwr_q1\"."); lwr_q1 = q_vec; if (!nh.getParam("lwr_q2",q_vec)) throw std::ios_base::failure("Failed to read parameter \"lwr_q2\"."); lwr_q2 = q_vec; if (!nh.getParam("lwr_time_duration",lwr_time_duration)) throw std::ios_base::failure("Failed to read parameter \"lwr_time_duration\"."); if (!nh.getParam("lwr_use_sim",lwr_use_sim)) throw std::ios_base::failure("Failed to read parameter \"lwr_use_sim\"."); // =========== bhand args ================== std::string bh_base_link; std::vector<std::string> bh_tool_link; double bh_ctrl_cycle; arma::vec bh_q1; arma::vec bh_q2; double bh_time_duration; // sec bool bh_use_sim; if (!nh.getParam("bh_base_link",bh_base_link)) throw std::ios_base::failure("Failed to read parameter \"bh_base_link\"."); if (!nh.getParam("bh_tool_link",bh_tool_link)) throw std::ios_base::failure("Failed to read parameter \"bh_tool_link\"."); if (!nh.getParam("bh_ctrl_cycle",bh_ctrl_cycle)) throw std::ios_base::failure("Failed to read parameter \"bh_ctrl_cycle\"."); if (!nh.getParam("bh_q1",q_vec)) throw std::ios_base::failure("Failed to read parameter \"bh_q1\"."); bh_q1 = q_vec; if (!nh.getParam("bh_q2",q_vec)) throw std::ios_base::failure("Failed to read parameter \"bh_q2\"."); bh_q2 = q_vec; if (!nh.getParam("bh_time_duration",bh_time_duration)) throw std::ios_base::failure("Failed to read parameter \"bh_time_duration\"."); if (!nh.getParam("bh_use_sim",bh_use_sim)) throw std::ios_base::failure("Failed to read parameter \"bh_use_sim\"."); // ======================================== // =========== initialize robot =========== // ======================================== // =========== init lwr4p robot =========== std::shared_ptr<lwr4p_::RobotArm> lwr4p_robot; if (lwr_use_sim) lwr4p_robot.reset(new lwr4p_::SimRobot(robot_desc,lwr_base_link,lwr_tool_link,lwr_ctrl_cycle)); else lwr4p_robot.reset(new lwr4p_::Robot(robot_desc,lwr_base_link,lwr_tool_link,lwr_ctrl_cycle)); lwr4p_robot->setJointLimitCheck(true); lwr4p_robot->setSingularityCheck(true); // lwr4p_robot->setSingularityThreshold(8e-3); // lwr4p_robot->readWrenchFromTopic("/wrench"); // or // lwr4p_robot->setGetExternalWrenchFun(/*some function pointer*/); // =========== init bh282 robot =========== std::shared_ptr<bhand_::RobotHand> bhand_robot; if (bh_use_sim) bhand_robot.reset(new bhand_::Bh282SimRobot(robot_desc,bh_base_link,bh_tool_link,bh_ctrl_cycle)); else bhand_robot.reset(new bhand_::Bh282Robot(robot_desc,bh_base_link,bh_tool_link,bh_ctrl_cycle)); bhand_robot->setJointLimitCheck(true); // ======================================================== // =========== initialize joint state publisher =========== // ======================================================== as64_::misc_::JointStatePublisher jState_pub; jState_pub.setPublishCycle(0.0333); // 30 Hz std::string publish_states_topic; nh.getParam("publish_states_topic",publish_states_topic); jState_pub.setPublishTopic(publish_states_topic); // jState_pub.setPublishTopic("/robot_joint_states"); jState_pub.addFun(&lwr4p_::RobotArm::addJointState, lwr4p_robot.get()); jState_pub.addFun(&bhand_::RobotHand::addJointState, bhand_robot.get()); jState_pub.start(); // launches joint states publisher thread // ================================================= // =========== Start robot execution =============== // ================================================= // =========== Start lwr robot execution =============== std::thread lwr_thread; LwrExecArgs lwr_args(lwr_q1, lwr_q2, lwr_time_duration, lwr4p_robot.get(), &run); lwr_thread = std::thread(lwrRobotRun, &lwr_args); // =========== Start bh robot execution =============== std::thread bh_thread; BhExecArgs bh_args(bh_q1, bh_q2, bh_time_duration, bhand_robot.get(), &run); bh_thread = std::thread(bhRobotRun, &bh_args); // =========== join threads ================= while (ros::ok()); run = false; lwr_thread.join(); bh_thread.join(); return 0; }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2017, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "opencv2/core/hal/intrin.hpp" namespace cv { namespace dnn { CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN void fastConv( const float* weights, size_t wstep, const float* bias, const float* rowbuf, float* output, const int* outShape, int blockSize, int vecsize, int vecsize_aligned, const float* relu, bool initOutput ); void fastGEMM1T( const float* vec, const float* weights, size_t wstep, const float* bias, float* dst, int nvecs, int vecsize ); void fastGEMM( const float* aptr, size_t astep, const float* bptr, size_t bstep, float* cptr, size_t cstep, int ma, int na, int nb ); #if !defined(CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY) && CV_AVX #if !CV_FMA // AVX workaround #undef _mm256_fmadd_ps #define _mm256_fmadd_ps(a, b, c) _mm256_add_ps(c, _mm256_mul_ps(a, b)) #endif void fastConv( const float* weights, size_t wstep, const float* bias, const float* rowbuf, float* output, const int* outShape, int blockSize, int vecsize, int vecsize_aligned, const float* relu, bool initOutput ) { int outCn = outShape[1]; size_t outPlaneSize = outShape[2]*outShape[3]; float r0 = 1.f, r1 = 1.f, r2 = 1.f; __m256 vr0 = _mm256_set1_ps(1.f), vr1 = vr0, vr2 = vr0, z = _mm256_setzero_ps(); // now compute dot product of the weights // and im2row-transformed part of the tensor for( int i = 0; i < outCn; i += 3 ) { const float* wptr0 = weights + i*wstep; const float* wptr1 = wptr0 + wstep; const float* wptr2 = wptr1 + wstep; float* outptr0 = output + i*outPlaneSize; float* outptr1 = outptr0 + outPlaneSize; float* outptr2 = outptr1 + outPlaneSize; float bias0 = bias[i], bias1 = bias[i+1], bias2 = bias[i+2]; if( i+2 >= outCn ) { wptr2 = wptr1; outptr2 = outptr1; bias2 = bias1; if( i+1 >= outCn ) { wptr2 = wptr1 = wptr0; outptr2 = outptr1 = outptr0; bias2 = bias1 = bias0; } } if( relu ) { r0 = relu[i]; r1 = relu[i+1]; r2 = relu[i+2]; vr0 = _mm256_set1_ps(r0); vr1 = _mm256_set1_ps(r1); vr2 = _mm256_set1_ps(r2); } int j = 0; for( ; j <= blockSize - 4; j += 4 ) { const float* rptr = rowbuf + j*vecsize_aligned; __m256 vs00 = _mm256_setzero_ps(), vs01 = _mm256_setzero_ps(), vs02 = _mm256_setzero_ps(), vs03 = _mm256_setzero_ps(), vs10 = _mm256_setzero_ps(), vs11 = _mm256_setzero_ps(), vs12 = _mm256_setzero_ps(), vs13 = _mm256_setzero_ps(), vs20 = _mm256_setzero_ps(), vs21 = _mm256_setzero_ps(), vs22 = _mm256_setzero_ps(), vs23 = _mm256_setzero_ps(); for( int k = 0; k < vecsize; k += 8, rptr += 8 ) { __m256 w0 = _mm256_load_ps(wptr0 + k); __m256 w1 = _mm256_load_ps(wptr1 + k); __m256 w2 = _mm256_load_ps(wptr2 + k); __m256 r0 = _mm256_load_ps(rptr); vs00 = _mm256_fmadd_ps(w0, r0, vs00); vs10 = _mm256_fmadd_ps(w1, r0, vs10); vs20 = _mm256_fmadd_ps(w2, r0, vs20); r0 = _mm256_load_ps(rptr + vecsize_aligned); vs01 = _mm256_fmadd_ps(w0, r0, vs01); vs11 = _mm256_fmadd_ps(w1, r0, vs11); vs21 = _mm256_fmadd_ps(w2, r0, vs21); r0 = _mm256_load_ps(rptr + vecsize_aligned*2); vs02 = _mm256_fmadd_ps(w0, r0, vs02); vs12 = _mm256_fmadd_ps(w1, r0, vs12); vs22 = _mm256_fmadd_ps(w2, r0, vs22); r0 = _mm256_load_ps(rptr + vecsize_aligned*3); vs03 = _mm256_fmadd_ps(w0, r0, vs03); vs13 = _mm256_fmadd_ps(w1, r0, vs13); vs23 = _mm256_fmadd_ps(w2, r0, vs23); } __m256 t0 = _mm256_hadd_ps(_mm256_hadd_ps(vs00, vs01), _mm256_hadd_ps(vs02, vs03)); __m256 t1 = _mm256_hadd_ps(_mm256_hadd_ps(vs10, vs11), _mm256_hadd_ps(vs12, vs13)); __m256 t2 = _mm256_hadd_ps(_mm256_hadd_ps(vs20, vs21), _mm256_hadd_ps(vs22, vs23)); t0 = _mm256_add_ps(t0, _mm256_permute2f128_ps(t0, t0, 1)); t1 = _mm256_add_ps(t1, _mm256_permute2f128_ps(t1, t1, 1)); t2 = _mm256_add_ps(t2, _mm256_permute2f128_ps(t2, t2, 1)); __m256 s0, s1, s2; if( initOutput ) { s0 = _mm256_set1_ps(bias0); s1 = _mm256_set1_ps(bias1); s2 = _mm256_set1_ps(bias2); } else { s0 = _mm256_castps128_ps256(_mm_loadu_ps(outptr0 + j)); s1 = _mm256_castps128_ps256(_mm_loadu_ps(outptr1 + j)); s2 = _mm256_castps128_ps256(_mm_loadu_ps(outptr2 + j)); } s0 = _mm256_add_ps(s0, t0); s1 = _mm256_add_ps(s1, t1); s2 = _mm256_add_ps(s2, t2); if( relu ) { __m256 m0 = _mm256_cmp_ps(s0, z, _CMP_GT_OS); __m256 m1 = _mm256_cmp_ps(s1, z, _CMP_GT_OS); __m256 m2 = _mm256_cmp_ps(s2, z, _CMP_GT_OS); s0 = _mm256_xor_ps(s0, _mm256_andnot_ps(m0, _mm256_xor_ps(_mm256_mul_ps(s0, vr0), s0))); s1 = _mm256_xor_ps(s1, _mm256_andnot_ps(m1, _mm256_xor_ps(_mm256_mul_ps(s1, vr1), s1))); s2 = _mm256_xor_ps(s2, _mm256_andnot_ps(m2, _mm256_xor_ps(_mm256_mul_ps(s2, vr2), s2))); } _mm_storeu_ps(outptr0 + j, _mm256_castps256_ps128(s0)); _mm_storeu_ps(outptr1 + j, _mm256_castps256_ps128(s1)); _mm_storeu_ps(outptr2 + j, _mm256_castps256_ps128(s2)); } for( ; j < blockSize; j++ ) { const float* rptr = rowbuf + j*vecsize_aligned; float s00, s10, s20; if( initOutput ) { s00 = bias0; s10 = bias1; s20 = bias2; } else { s00 = outptr0[j]; s10 = outptr1[j]; s20 = outptr2[j]; } for( int k = 0; k < vecsize; k++ ) { float r0 = rptr[k]; s00 += wptr0[k]*r0; s10 += wptr1[k]*r0; s20 += wptr2[k]*r0; } if( relu ) { s00 = s00 > 0.f ? s00 : s00*r0; s10 = s10 > 0.f ? s10 : s10*r1; s20 = s20 > 0.f ? s20 : s20*r2; } outptr0[j] = s00; outptr1[j] = s10; outptr2[j] = s20; } } _mm256_zeroupper(); } // dst = vec * weights^t + bias void fastGEMM1T( const float* vec, const float* weights, size_t wstep, const float* bias, float* dst, int nvecs, int vecsize ) { int i = 0; for( ; i <= nvecs - 8; i += 8 ) { const float* wptr = weights + i*wstep; __m256 vs0 = _mm256_setzero_ps(), vs1 = _mm256_setzero_ps(), vs2 = _mm256_setzero_ps(), vs3 = _mm256_setzero_ps(), vs4 = _mm256_setzero_ps(), vs5 = _mm256_setzero_ps(), vs6 = _mm256_setzero_ps(), vs7 = _mm256_setzero_ps(); for( int k = 0; k < vecsize; k += 8, wptr += 8 ) { __m256 v = _mm256_load_ps(vec + k); vs0 = _mm256_fmadd_ps(_mm256_load_ps(wptr), v, vs0); vs1 = _mm256_fmadd_ps(_mm256_load_ps(wptr + wstep), v, vs1); vs2 = _mm256_fmadd_ps(_mm256_load_ps(wptr + wstep*2), v, vs2); vs3 = _mm256_fmadd_ps(_mm256_load_ps(wptr + wstep*3), v, vs3); vs4 = _mm256_fmadd_ps(_mm256_load_ps(wptr + wstep*4), v, vs4); vs5 = _mm256_fmadd_ps(_mm256_load_ps(wptr + wstep*5), v, vs5); vs6 = _mm256_fmadd_ps(_mm256_load_ps(wptr + wstep*6), v, vs6); vs7 = _mm256_fmadd_ps(_mm256_load_ps(wptr + wstep*7), v, vs7); } __m256 s0 = _mm256_hadd_ps(_mm256_hadd_ps(vs0, vs1), _mm256_hadd_ps(vs2, vs3)); __m256 s1 = _mm256_hadd_ps(_mm256_hadd_ps(vs4, vs5), _mm256_hadd_ps(vs6, vs7)); s0 = _mm256_add_ps(s0, _mm256_permute2f128_ps(s0, s0, 1)); s1 = _mm256_add_ps(s1, _mm256_permute2f128_ps(s1, s1, 1)); s0 = _mm256_add_ps(s0, _mm256_castps128_ps256(_mm_loadu_ps(bias + i))); s1 = _mm256_add_ps(s1, _mm256_castps128_ps256(_mm_loadu_ps(bias + i + 4))); _mm_storeu_ps(dst + i, _mm256_castps256_ps128(s0)); _mm_storeu_ps(dst + i + 4, _mm256_castps256_ps128(s1)); } float temp = 0.f; for( ; i < nvecs; i++ ) { const float* wptr = weights + i*wstep; __m256 vs0 = _mm256_setzero_ps(); for( int k = 0; k < vecsize; k += 8, wptr += 8 ) { __m256 v = _mm256_load_ps(vec + k); vs0 = _mm256_fmadd_ps(_mm256_load_ps(wptr), v, vs0); } __m256 s0 = _mm256_hadd_ps(_mm256_hadd_ps(vs0, vs0), vs0); s0 = _mm256_add_ps(s0, _mm256_permute2f128_ps(s0, s0, 1)); _mm_store_ss(&temp, _mm256_castps256_ps128(s0)); dst[i] = temp + bias[i]; } _mm256_zeroupper(); } void fastGEMM( const float* aptr, size_t astep, const float* bptr, size_t bstep, float* cptr, size_t cstep, int ma, int na, int nb ) { int n = 0; for( ; n <= nb - 16; n += 16 ) { for( int m = 0; m < ma; m += 4 ) { const float* aptr0 = aptr + astep*m; const float* aptr1 = aptr + astep*std::min(m+1, ma-1); const float* aptr2 = aptr + astep*std::min(m+2, ma-1); const float* aptr3 = aptr + astep*std::min(m+3, ma-1); float* cptr0 = cptr + cstep*m; float* cptr1 = cptr + cstep*std::min(m+1, ma-1); float* cptr2 = cptr + cstep*std::min(m+2, ma-1); float* cptr3 = cptr + cstep*std::min(m+3, ma-1); __m256 d00 = _mm256_setzero_ps(), d01 = _mm256_setzero_ps(); __m256 d10 = _mm256_setzero_ps(), d11 = _mm256_setzero_ps(); __m256 d20 = _mm256_setzero_ps(), d21 = _mm256_setzero_ps(); __m256 d30 = _mm256_setzero_ps(), d31 = _mm256_setzero_ps(); for( int k = 0; k < na; k++ ) { __m256 a0 = _mm256_set1_ps(aptr0[k]); __m256 a1 = _mm256_set1_ps(aptr1[k]); __m256 a2 = _mm256_set1_ps(aptr2[k]); __m256 a3 = _mm256_set1_ps(aptr3[k]); __m256 b0 = _mm256_loadu_ps(bptr + k*bstep + n); __m256 b1 = _mm256_loadu_ps(bptr + k*bstep + n + 8); d00 = _mm256_fmadd_ps(a0, b0, d00); d01 = _mm256_fmadd_ps(a0, b1, d01); d10 = _mm256_fmadd_ps(a1, b0, d10); d11 = _mm256_fmadd_ps(a1, b1, d11); d20 = _mm256_fmadd_ps(a2, b0, d20); d21 = _mm256_fmadd_ps(a2, b1, d21); d30 = _mm256_fmadd_ps(a3, b0, d30); d31 = _mm256_fmadd_ps(a3, b1, d31); } _mm256_storeu_ps(cptr0 + n, d00); _mm256_storeu_ps(cptr0 + n + 8, d01); _mm256_storeu_ps(cptr1 + n, d10); _mm256_storeu_ps(cptr1 + n + 8, d11); _mm256_storeu_ps(cptr2 + n, d20); _mm256_storeu_ps(cptr2 + n + 8, d21); _mm256_storeu_ps(cptr3 + n, d30); _mm256_storeu_ps(cptr3 + n + 8, d31); } } for( ; n < nb; n++ ) { for( int m = 0; m < ma; m++ ) { const float* aptr0 = aptr + astep*m; float* cptr0 = cptr + cstep*m; float d0 = 0.f; for( int k = 0; k < na; k++ ) d0 += aptr0[k]*bptr[k*bstep + n]; cptr0[n] = d0; } } _mm256_zeroupper(); } #endif // CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY CV_CPU_OPTIMIZATION_NAMESPACE_END }} // namespace
#include "GetIdleTableProc.h" #include "ClientHandler.h" #include "Logger.h" #include "Configure.h" #include "Player.h" #include "GameServerConnect.h" #include "PlayerManager.h" #include "HallHandler.h" #include "SvrConfig.h" #include "RobotRedis.h" #include "Util.h" #include <json/json.h> #include <string> #include "Robot/RobotUtil.h" #include "NamePool.h" using namespace std; GetIdleTableProc::GetIdleTableProc() { this->name = "GetIdleTableProc"; } GetIdleTableProc::~GetIdleTableProc() { } int GetIdleTableProc::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt ) { ClientHandler* clientHandler = reinterpret_cast <ClientHandler*> (client); _NOTUSED(clientHandler); _NOTUSED(pPacket); _NOTUSED(pt); return 0; } int GetIdleTableProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { _NOTUSED(clientHandler); int cmd = inputPacket->GetCmdType(); int retcode = inputPacket->ReadShort(); string retmsg = inputPacket->ReadString(); if(retcode < 0) { LOGGER(E_LOG_WARNING) << "GetIdleTableProc Error retcode[" <<retcode<< "] retmsg[" <<retmsg.c_str()<< "]"; //_LOG_ERROR_("GetIdleTableProc Error retcode[%d] retmsg[%s]\n", retcode, retmsg.c_str()); return 0; } int Time = inputPacket->ReadInt(); short Count = inputPacket->ReadShort(); // _LOG_INFO_("==>[GetIdleTableProc] [0x%04x] Count=[%d]\n", cmd, Count); for(int i = 0; i < Count; i++) { int tid = inputPacket->ReadInt(); short status = inputPacket->ReadShort(); short level = inputPacket->ReadShort(); short countUser = inputPacket->ReadShort(); int replayTime = inputPacket->ReadInt(); // _LOG_DEBUG_("[Data Recv] tid=[%d]\n", tid); //_LOG_DEBUG_("[Data Recv] status=[%d]\n", status); //_LOG_DEBUG_("[Data Recv] level=[%d]\n", level); //_LOG_DEBUG_("[Data Recv] countUser=[%d]\n", countUser); LOGGER(E_LOG_DEBUG) << "[Data Recv] tid=[" <<tid<< "] [Data Recv] status=[" <<status<< "] [Data Recv] level=["<<level<<"] [Data Recv] countUser=["<<countUser<<"]"; if(countUser == 0) { productRobot(tid, status, level, countUser); productRobot(tid, status, level, countUser); productRobot(tid, status, level, countUser); //productRobot(tid, status, level, countUser); //productRobot(tid, status, level, countUser); } else if((countUser > 0) && ((Time-replayTime) > Configure::instance()->entertime)) { productRobot(tid, status, level, countUser); //productRobot(tid, status, level, countUser); } } return 0; } int GetIdleTableProc::productRobot(int tid, short status, short level, short countUser) { bool bactive = false; //如果这个用户正在玩牌 if(countUser >= 3) return 0; //if(level == 2 && countUser == 2) // return 0; int64_t winmoney = RobotRedis::getInstance()->getRobotWinCount(level); Player* player = new Player(); if(player) { player->init(); player->clevel = level; player->playNum = Configure::instance()->baseplayCount + rand()%3; int robotuid = PlayerManager::getInstance()->getRobotUID(); if(robotuid < 0) { delete player; _LOG_ERROR_("robotuid is negative level[%d] robotuid[%d]\n", level, robotuid); return -1; } player->id = robotuid; player->tid = tid; if (bactive) { player->bactive = true; } int totalnum = 0; int winnum = 0; int roll = 0; int switchmoney = 0; if (level == 1) switchmoney = Configure::instance()->swtichWin1; else if (level == 2) switchmoney = Configure::instance()->swtichWin2; else if(level== 3) switchmoney = Configure::instance()->swtichWin6; if(winmoney > switchmoney) { int num = rand()%100; //if(num < 5) player->isKnow = false; } else { int num = rand()%100; if(num < Configure::instance()->randknow) player->isKnow = true; } int mostwin = 100; short viptype = 0; if(level == 1) { player->money = Configure::instance()->baseMoney1 + rand()%Configure::instance()->randMoney1; totalnum += 20 + rand()%380; mostwin = 2000 + rand()%30000; int rate = 20 + rand()%30; winnum = totalnum*rate/100; roll += 1; viptype = rand()%100 < 10 ? 1 : 0; } else if (level == 2) { player->money = Configure::instance()->baseMoney2 + rand()%Configure::instance()->randMoney2; totalnum = 50 + rand()%1500; int rate = 20 + rand()%30; winnum = totalnum*rate/100; mostwin = 20000 + rand()%3000000; roll += 150 + rand()%100; viptype = rand()%100 < 40 ? 1 : 0; } else if (level == 3) { player->money = Configure::instance()->baseMoney3 + rand()%Configure::instance()->randMoney2; totalnum = 50 + rand()%1000; winnum = 15 + rand()%400; if(totalnum < winnum) winnum = totalnum*3/10; roll += 250 + rand()%200; mostwin = 2000000 + rand()%30000000; } int sex = rand()%2 + 1; int randnum = rand()%100; char headlink[256] = {0}; string nickname = NamePool::getInstance()->AllocName(); strcpy(player->name,nickname.c_str()); //_LOG_DEBUG_("-------Idle---------uid:%d isKnow:%s winmoney:%d switchmoney:%d \n",player->id, player->isKnow ? "true" : "false", winmoney, switchmoney); printf("money =================:%d\n", player->money); if(randnum < Configure::instance()->randhead) { strcpy(headlink, "http://www.baiduc.com/data/icon/default/avatar.jpg"); } else { strcpy(headlink, ""); } int randuid = Configure::instance()->baseuid + rand()%Configure::instance()->randuid; int robotid = randuid+player->id; short randredis = rand()%2; int num = 0; while(true) { randuid = Configure::instance()->baseuid + rand()%Configure::instance()->randuid; robotid = randuid+player->id; if(num >10) break; string nickname, headurl; if (RobotUtil::makeRobotNameSex("", nickname, sex, headurl)) break; num++; } Json::Value data; data["picUrl"] = string(headlink); data["sum"] = totalnum; data["win"] = winnum; data["sex"] = sex; data["source"] = 30; data["lepaper"] = roll; data["mostwin"] = double(mostwin); data["uid"] = robotid; data["vip"] = viptype; data["iconid"] = rand() % 6; strcpy(player->json,data.toStyledString().c_str()); HallHandler * handler = new HallHandler(); if(CDLReactor::Instance()->Connect(handler,Configure::instance()->hall_ip,Configure::instance()->hall_port) < 0) { delete handler; delete player; LOGGER(E_LOG_WARNING)<<"Connect BackServer error["<<Configure::instance()->hall_ip<< ":" <<Configure::instance()->hall_port<< "]"; // _LOG_ERROR_("Connect BackServer error[%s:%d]\n",Configure::instance()->hall_ip,Configure::instance()->hall_port); return -1; } handler->uid = player->id; player->handler = handler; PlayerManager::getInstance()->addPlayer(player->id, player); _LOG_INFO_("StartRobot[%d] tid[%d]\n",player->id, tid); player->login(); } return 0; }
#include "EnemyInvisible.h" sf::Texture EnemyInvisible::texture; EnemyInvisible::EnemyInvisible(float x, float y, int level, int id) : BasicEnemy(id) { if (level == 1) { invisibleScale = 1; shootDelay = 2000; } if (level == 2) { invisibleScale = 1.5; shootDelay = 1200; } if (level == 3) { invisibleScale = 2; shootDelay = 800; } speed = 0.1; shootSpeed = 2.5; randShootDelay = 300; sprite.setScale(0.5, 0.5); sprite.setColor(sf::Color(255, 255, 20)); hitbox1.setScale(0.5, 0.75); hitbox1pos.x = 0; hitbox1pos.y = 0; hitbox2.setScale(0.3, 0.4); hitbox2pos.x = -40; hitbox2pos.y = -30; hitbox3.setScale(0.3, 0.4); hitbox3pos.x = 40; hitbox3pos.y = -30; hp = 3; shootType = 2; shootScale = 1; invisibleDeltaTime = 0; static bool firstTime = true; if (firstTime) { texture.loadFromFile("Images/Enemies/EnemyInvisible/normal.png"); firstTime = false; } sprite.setTexture(texture); sprite.setColor(sf::Color(255, 255, 255, 30)); sf::Vector2u size = texture.getSize(); sprite.setOrigin(size.x / 2, size.y / 2); sprite.setPosition(x, y); this->size.x = size.x * sprite.getScale().x; this->size.y = size.y * sprite.getScale().y; } void EnemyInvisible::update(int enemyNumber) { invisibleDeltaTime += GameInfo::getDeltaTime(); if (invisibleDeltaTime < 1000) { sprite.setColor(sf::Color(255, 255, 255, invisibleDeltaTime / 50)); } else if (invisibleDeltaTime >= 1000 && invisibleDeltaTime < 4000) //widzialny { sprite.setColor(sf::Color(255, 255, 255, 20)); } else if (invisibleDeltaTime >= 4000 && invisibleDeltaTime < 5000) { sprite.setColor(sf::Color(255, 255, 255, (invisibleDeltaTime - 5000) / -50)); } else if (invisibleDeltaTime >= 5000 && invisibleDeltaTime < 8000 * invisibleScale) //niewidzialny { sprite.setColor(sf::Color(255, 255, 255, 0)); } else if (invisibleDeltaTime >= 8000 * invisibleScale) invisibleDeltaTime -= 8000 * invisibleScale; shoot(); checkCollision(enemyNumber); //musi byc na koncu metody, bo moze usunac obiekt } void EnemyInvisible::create(float posX, float posY, int level, int id) { BasicEnemy::enemy.push_back(std::make_shared <EnemyInvisible>(posX, posY, level, id)); }
/************************************************************************/ /* Multi-tracker based on CNN */ /************************************************************************/ #ifndef __CNN_MULTI_TRACKER_H__ #define __CNN_MULTI_TRACKER_H__ #include "../utils/util.h" #include "../utils/singleton.h" namespace ice { class ObjectInfo; class CNNMultiTracker :public Singleton<CNNMultiTracker> { public: CNNMultiTracker(); ~CNNMultiTracker(); void OnInit(); void OnDestroy(); bool IsOutboard(cv::Rect & positionBox); void AddTracker(cv::Mat& frame, cv::Rect& positionBox); void OnUpdate(cv::Mat & frame); //void UpdateObjInfo(cv::Mat & frame); void Mark(size_t index); void RemoveInvalid(); void Replace(cv::Mat& frame, cv::Rect& positionBox, size_t index); void DrawTrace(cv::Mat& frame); void DrawUI(cv::Mat& frame); std::map<size_t, ObjectInfo*>& TrackingObectorMap() { return object_info_map_; } void SetAllMatchFalse(); void SetMatchTrue(size_t index); void SetBound(cv::Size, cv::Rect); //void PrintRecycle(); private: int GetIndex_(); void RemoveTrackerByIndex_(size_t index); private: std::map<size_t, ObjectInfo*> object_info_map_; std::list<size_t> invalid_index_list_; size_t key_max_; std::set<size_t> index_pool_set_; cv::Mat bound_mask_; }; } #endif // __CNN_MULTI_TRACKER_H__
/**************************************************************************** Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.6.3. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #include "domUtils.h" #include "vec.h" // Most of the methods are declared inline in vec.h using namespace qglviewer; using namespace std; /*! Projects the Vec on the axis of direction \p direction that passes through the origin. \p direction does not need to be normalized (but must be non null). */ void Vec::projectOnAxis(const Vec& direction) { #ifndef QT_NO_DEBUG if (direction.squaredNorm() < 1.0E-10) qWarning("Vec::projectOnAxis: axis direction is not normalized (norm=%f).", direction.norm()); #endif *this = (((*this)*direction) / direction.squaredNorm()) * direction; } /*! Projects the Vec on the plane whose normal is \p normal that passes through the origin. \p normal does not need to be normalized (but must be non null). */ void Vec::projectOnPlane(const Vec& normal) { #ifndef QT_NO_DEBUG if (normal.squaredNorm() < 1.0E-10) qWarning("Vec::projectOnPlane: plane normal is not normalized (norm=%f).", normal.norm()); #endif *this -= (((*this)*normal) / normal.squaredNorm()) * normal; } /*! Returns a Vec orthogonal to the Vec. Its norm() depends on the Vec, but is zero only for a null Vec. Note that the function that associates an orthogonalVec() to a Vec is not continous. */ Vec Vec::orthogonalVec() const { // Find smallest component. Keep equal case for null values. if ((fabs(y) >= 0.9*fabs(x)) && (fabs(z) >= 0.9*fabs(x))) return Vec(0.0, -z, y); else if ((fabs(x) >= 0.9*fabs(y)) && (fabs(z) >= 0.9*fabs(y))) return Vec(-z, 0.0, x); else return Vec(-y, x, 0.0); } /*! Constructs a Vec from a \c QDomElement representing an XML code of the form \code< anyTagName x=".." y=".." z=".." />\endcode If one of these attributes is missing or is not a number, a warning is displayed and the associated value is set to 0.0. See also domElement() and initFromDOMElement(). */ Vec::Vec(const QDomElement& element) { QStringList attribute; attribute << "x" << "y" << "z"; for (int i=0; i<attribute.size(); ++i) #ifdef QGLVIEWER_UNION_NOT_SUPPORTED this->operator[](i) = DomUtils::qrealFromDom(element, attribute[i], 0.0); #else v_[i] = DomUtils::qrealFromDom(element, attribute[i], 0.0); #endif } /*! Returns an XML \c QDomElement that represents the Vec. \p name is the name of the QDomElement tag. \p doc is the \c QDomDocument factory used to create QDomElement. When output to a file, the resulting QDomElement will look like: \code <name x=".." y=".." z=".." /> \endcode Use initFromDOMElement() to restore the Vec state from the resulting \c QDomElement. See also the Vec(const QDomElement&) constructor. Here is complete example that creates a QDomDocument and saves it into a file: \code Vec sunPos; QDomDocument document("myDocument"); QDomElement sunElement = document.createElement("Sun"); document.appendChild(sunElement); sunElement.setAttribute("brightness", sunBrightness()); sunElement.appendChild(sunPos.domElement("sunPosition", document)); // Other additions to the document hierarchy... // Save doc document QFile f("myFile.xml"); if (f.open(IO_WriteOnly)) { QTextStream out(&f); document.save(out, 2); f.close(); } \endcode See also Quaternion::domElement(), Frame::domElement(), Camera::domElement()... */ QDomElement Vec::domElement(const QString& name, QDomDocument& document) const { QDomElement de = document.createElement(name); de.setAttribute("x", QString::number(x)); de.setAttribute("y", QString::number(y)); de.setAttribute("z", QString::number(z)); return de; } /*! Restores the Vec state from a \c QDomElement created by domElement(). The \c QDomElement should contain \c x, \c y and \c z attributes. If one of these attributes is missing or is not a number, a warning is displayed and the associated value is set to 0.0. To restore the Vec state from an xml file, use: \code // Load DOM from file QDomDocument doc; QFile f("myFile.xml"); if (f.open(IO_ReadOnly)) { doc.setContent(&f); f.close(); } // Parse the DOM tree and initialize QDomElement main=doc.documentElement(); myVec.initFromDOMElement(main); \endcode See also the Vec(const QDomElement&) constructor. */ void Vec::initFromDOMElement(const QDomElement& element) { const Vec v(element); *this = v; } ostream& operator<<(ostream& o, const Vec& v) { return o << v.x << '\t' << v.y << '\t' << v.z; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2002-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/inputmanager/inputmanager.h" #include "modules/dochand/win.h" #include "modules/dochand/winman.h" #include "modules/inputmanager/inputcontext.h" #include "modules/locale/oplanguagemanager.h" #include "modules/locale/locale-enum.h" #include "modules/prefsfile/prefsentry.h" #include "modules/prefsfile/prefssection.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/util/filefun.h" #include "modules/util/OpLineParser.h" #include "modules/util/simset.h" #include "modules/widgets/OpWidget.h" #include "modules/hardcore/mh/messages.h" #ifdef QUICK # include "adjunct/quick/Application.h" # include "adjunct/quick/managers/CommandLineManager.h" # include "adjunct/quick/managers/opsetupmanager.h" #endif // QUICK #if defined(SDK) # include "product/sdk/src/operaembedded_internal.h" #endif // SDK #ifdef GTK_SDK extern PrefsSection* _gtk_opera_get_input_contextL(const uni_char* context_name, BOOL is_keyboard); #endif // GTK_SDK #ifdef EPOC # ifndef SYMGOGI # include "EpocUtils.h" # include "EpocModel.h" # endif // !SYMGOGI #endif // EPOC #if defined (MSWIN) extern BOOL IsSystemWin2000orXP(); #endif //MSWIN #include "modules/libcrypto/include/OpRandomGenerator.h" void Shortcut::GetShortcutStringL(OpString& string) { if (m_modifiers & SHIFTKEY_CTRL) { OpString tmp; g_languageManager->GetStringL(Str::M_KEY_CTRL, tmp); tmp.AppendL("+"); string.AppendL(tmp); } if (m_modifiers & SHIFTKEY_ALT) { OpString tmp; g_languageManager->GetStringL(Str::M_KEY_ALT, tmp); tmp.AppendL("+"); string.AppendL(tmp); } if (m_modifiers & SHIFTKEY_META) { OpString tmp; g_languageManager->GetStringL(Str::M_KEY_META, tmp); tmp.AppendL("+"); string.AppendL(tmp); } if (m_modifiers & SHIFTKEY_SHIFT) { OpString tmp; g_languageManager->GetStringL(Str::M_KEY_SHIFT, tmp); tmp.AppendL("+"); string.AppendL(tmp); } if (m_key_value == 0) { OpString key_string; LEAVE_IF_ERROR(OpInputManager::OpKeyToLanguageString(m_key, key_string)); string.AppendL(key_string); } else string.AppendL(&m_key_value, 1); } /*********************************************************************************** ** ** ShortcutAction ** ***********************************************************************************/ OP_STATUS ShortcutAction::Construct(OpInputAction::ActionMethod method, const uni_char* shortcut_string, OpInputAction* input_action) { m_input_action = input_action; OpLineParser line(shortcut_string); while (line.HasContent()) { OpString token; RETURN_IF_ERROR(line.GetNextToken(token)); RETURN_IF_ERROR(AddShortcutsFromString(token.CStr())); } return OpStatus::OK; } OP_STATUS ShortcutAction::AddShortcutsFromString(uni_char *s) { OpKey::Code key = OP_KEY_INVALID; uni_char key_value = '\0'; ShiftKeyState shift_keys = SHIFTKEY_NONE; while (s && *s) { while (uni_isspace(*s) || *s == '+') { ++s; } if (uni_stristr(s, UNI_L("Ctrl")) == s) { shift_keys |= SHIFTKEY_CTRL; s += 4; } else if (uni_stristr(s, UNI_L("Alt")) == s) { shift_keys |= SHIFTKEY_ALT; s += 3; } else if (uni_stristr(s, UNI_L("Shift")) == s) { shift_keys |= SHIFTKEY_SHIFT; s += 5; } else if (uni_stristr(s, UNI_L("Meta")) == s) { shift_keys |= SHIFTKEY_META; s += 4; } else { uni_char* key_string = s; while (*s && !uni_isspace(*s)) { ++s; } if (*s) { *s = 0; s++; } key = OpKey::FromString(key_string); switch (key) { case 0: { if (uni_isalpha(key_string[0])) { OP_ASSERT(uni_islower(key_string[0]) && !key_string[1]); key = static_cast<OpKey::Code>(OP_KEY_A + (uni_toupper(key_string[0]) - 'A')); } else key_value = key_string[0]; break; } case OP_KEY_PLUS: key_value = '+'; break; case OP_KEY_COMMA: key_value = ','; break; default: if (key >= OP_KEY_A && key <= OP_KEY_Z && uni_isupper(key_string[0])) shift_keys |= SHIFTKEY_SHIFT; /* Digit key shortcuts are overloaded to apply to both main and numeric pad digit keys. */ else if (key >= OP_KEY_0 && key <= OP_KEY_9) key_value = '0' + (key - OP_KEY_0); } } } if (key != OP_KEY_INVALID || key_value != 0) RETURN_IF_ERROR(AddShortcut(key, shift_keys, key_value)); return OpStatus::OK; } OP_STATUS ShortcutAction::AddShortcut(OpKey::Code key, ShiftKeyState shift_keys, uni_char key_value) { OpAutoPtr<Shortcut> shortcut(OP_NEW(Shortcut, ())); if (!shortcut.get()) return OpStatus::ERR_NO_MEMORY; shortcut->Set(key, shift_keys, key_value); RETURN_IF_ERROR(m_shortcut_list.Add(shortcut.get())); shortcut.release(); return OpStatus::OK; } BOOL ShortcutAction::MatchesKeySequence(Shortcut* shortcuts, unsigned shortcut_count) const { if (shortcut_count >= GetShortcutCount()) return FALSE; for (unsigned i = 0; i <= shortcut_count; i++) { if (!GetShortcutByIndex(i)->Equals(shortcuts[i])) { return FALSE; } } return TRUE; } /*********************************************************************************** ** ** ShortcutContext ** ***********************************************************************************/ ShortcutContext::ShortcutContext(OpInputAction::ActionMethod method) : m_shortcut_actions_hashtable(this), m_action_method(method) { m_shortcut_actions_hashtable.SetHashFunctions(this); #ifndef MOUSE_SUPPORT OP_ASSERT(m_action_method != OpInputAction::METHOD_KEYBOARD); #endif // !MOUSE_SUPPORT } OP_STATUS ShortcutContext::Construct(const char* context_name, PrefsSection* section) { RETURN_IF_ERROR(m_context_name.Set(context_name)); RETURN_IF_ERROR(AddShortcuts(context_name, section)); return OpStatus::OK; } OP_STATUS ShortcutContext::AddShortcuts(const char* context_name, PrefsSection * section) { RETURN_IF_LEAVE( AddShortcutsL(context_name, section) ); return OpStatus::OK; } void ShortcutContext::AddShortcutsL(const char* context_name, PrefsSection * section) { if (section == NULL) { #ifdef QUICK section = g_setup_manager->GetSectionL(context_name, m_action_method == OpInputAction::METHOD_KEYBOARD ? OPKEYBOARD_SETUP : OPMOUSE_SETUP); #elif defined SDK section = OperaEmbeddedInternal::GetInternal()->GetInputContextL(context_name, m_action_method == OpInputAction::METHOD_KEYBOARD); #elif defined GTK_SDK section = _gtk_opera_get_input_contextL(context_name, m_action_method == OpInputAction::METHOD_KEYBOARD); #elif defined GOGI extern PrefsSection * gogi_opera_get_input_contextL(const uni_char* context_name, BOOL is_keyboard); OpString uni_context_name; ANCHOR(OpString, uni_context_name); uni_context_name.SetL(context_name); section = gogi_opera_get_input_contextL(uni_context_name.CStr(), m_action_method == OpInputAction::METHOD_KEYBOARD); #elif defined EPOC section = g_iModel->GetInputContextL(_M(context_name), m_action_method == OpInputAction::METHOD_KEYBOARD); #else # error "You are not using OpSetupManager and do not have a platform specific interface" #endif } OpStackAutoPtr<PrefsSection> section_auto_ptr(section); #ifdef IM_EXTENDED_KEYBOARD_SHORTCUTS BOOL use_extended_keyboard = g_pcui->GetIntegerPref(PrefsCollectionUI::ExtendedKeyboardShortcuts); #endif if (section) { for (const PrefsEntry *entry = section->Entries(); entry; entry = (const PrefsEntry *) entry->Suc()) { #ifdef IM_EXTENDED_KEYBOARD_SHORTCUTS BOOL key_found = FALSE; BOOL ex_key_found = FALSE; #endif // IM_EXTENDED_KEYBOARD_SHORTCUTS const uni_char* key = entry->Key(); if (key && uni_stristr(key, UNI_L("Platform")) != NULL) { #if defined(_X11_) if( uni_stristr(key, UNI_L("Unix")) == NULL ) { continue; } #elif defined(MSWIN) BOOL isMCE = (uni_stristr(key, UNI_L("MCE")) != NULL); BOOL isWin2000 = (uni_stristr(key, UNI_L("Win2000")) != NULL); BOOL isWindows = (uni_stristr(key, UNI_L("Windows")) != NULL) || (uni_stristr(key, UNI_L("Win2000")) != NULL); if( CommandLineManager::GetInstance()->GetArgument(CommandLineManager::MediaCenter) ) { if(!isMCE) { continue; } } else if(isWindows) { if(isWin2000 && !IsSystemWin2000orXP()) { continue; } } else { continue; } #elif defined(_MACINTOSH_) if( uni_stristr(key, UNI_L("Mac")) == NULL ) { continue; } #endif #ifdef IM_EXTENDED_KEYBOARD_SHORTCUTS if (key && uni_stristr(key, UNI_L("Feature ExtendedShortcuts")) != NULL) { // If extended shortcuts are disabled, ignore this shortcut if (!use_extended_keyboard) continue; ex_key_found = TRUE; } #endif // IM_EXTENDED_KEYBOARD_SHORTCUTS // skip ahead to real content key = uni_stristr(key, UNI_L(",")); if (key == NULL) { continue; } else { key++; #ifdef IM_EXTENDED_KEYBOARD_SHORTCUTS key_found = TRUE; #endif // IM_EXTENDED_KEYBOARD_SHORTCUTS } } #ifdef IM_EXTENDED_KEYBOARD_SHORTCUTS if (key && uni_stristr(key, UNI_L("Feature ExtendedShortcuts")) != NULL) { // If extended shortcuts are disabled, ignore this shortcut if (!use_extended_keyboard) continue; ex_key_found = TRUE; } if(!key_found && use_extended_keyboard && ex_key_found) { // skip ahead to real content key = uni_stristr(key, UNI_L(",")); if (key == NULL) { continue; } else { key++; } } #endif // IM_EXTENDED_KEYBOARD_SHORTCUTS // translate voice commands, for example OpString translated_key; ANCHOR(OpString, translated_key); Str::LocaleString key_id(Str::NOT_A_STRING); OP_STATUS status; if (key && uni_stristr(key, UNI_L(",")) == NULL && m_action_method != OpInputAction::METHOD_KEYBOARD && m_action_method != OpInputAction::METHOD_MOUSE) { OpLineParser key_line(key); status = key_line.GetNextLanguageString(translated_key, &key_id); if (OpStatus::IsMemoryError(status)) LEAVE(status); if (translated_key.HasContent()) { key = translated_key.CStr(); } } OpInputAction* input_action = NULL; status = OpInputAction::CreateInputActionsFromString(entry->Value(), input_action, 0, TRUE); if (OpStatus::IsMemoryError(status)) LEAVE(status); if (OpStatus::IsSuccess(status) && input_action) { ShortcutAction* shortcut_action = OP_NEW(ShortcutAction, ()); if (shortcut_action == NULL) { OP_DELETE(input_action); LEAVE(OpStatus::ERR_NO_MEMORY); } status = shortcut_action->Construct(m_action_method, key, input_action); if (OpStatus::IsError(status)) { OP_DELETE(shortcut_action); LEAVE(status); } status = m_shortcut_actions_list.Add(shortcut_action); if (OpStatus::IsError(status)) { OP_DELETE(shortcut_action); LEAVE(status); } // only add to hash if action doesn't exist there already void* same_shortcut_action = NULL; m_shortcut_actions_hashtable.GetData(shortcut_action->GetAction(), &same_shortcut_action); if (!same_shortcut_action) { status = m_shortcut_actions_hashtable.Add(shortcut_action->GetAction(), shortcut_action); if (OpStatus::IsError(status)) { m_shortcut_actions_list.RemoveByItem(shortcut_action); OP_DELETE(shortcut_action); LEAVE(status); } } } } } } ShortcutAction* ShortcutContext::GetShortcutActionFromAction(OpInputAction* action) { void* shortcut_action = NULL; m_shortcut_actions_hashtable.GetData(action, &shortcut_action); return (ShortcutAction*)shortcut_action; } UINT32 ShortcutContext::Hash(const void* key) { OpInputAction* input_action = (OpInputAction*) key; UINT32 hash = input_action->GetAction() + input_action->GetActionData(); const uni_char* data_string = input_action->GetActionDataString(); if (data_string) { hash += *data_string; } return hash; } BOOL ShortcutContext::KeysAreEqual(const void* key1, const void* key2) { OpInputAction* input_action1 = (OpInputAction*) key1; OpInputAction* input_action2 = (OpInputAction*) key2; return input_action1->Equals(input_action2); } /*********************************************************************************** ** ** ShortcutContextList ** ***********************************************************************************/ ShortcutContext* ShortcutContextList::GetShortcutContextFromName(const char* context_name, PrefsSection* special_section) { if (!context_name) return NULL; ShortcutContext* shortcut_context = NULL; m_shortcut_context_hashtable.GetData(context_name, &shortcut_context); if (!shortcut_context) { shortcut_context = OP_NEW(ShortcutContext, (m_action_method)); if (shortcut_context && OpStatus::IsSuccess(shortcut_context->Construct(context_name, special_section))) { m_shortcut_context_hashtable.Add(shortcut_context->GetName(), shortcut_context); m_shortcut_context_list.Add(shortcut_context); } else { OP_DELETE(shortcut_context); return NULL; } } return shortcut_context; } void ShortcutContextList::Flush() { m_shortcut_context_hashtable.RemoveAll(); m_shortcut_context_list.DeleteAll(); } #ifdef MOUSE_SUPPORT /*********************************************************************************** ** ** MouseGestureManager ** ***********************************************************************************/ #define MOUSE_GESTURE_UI_DELAY (500) // in ms MouseGestureManager::MouseGestureManager() : m_callback_set(FALSE) , m_ui_shown(FALSE) , m_instantiation_id(0) , m_listener(NULL) { } MouseGestureManager::~MouseGestureManager() { if (m_callback_set) { g_main_message_handler->UnsetCallBack(this, MSG_MOUSE_GESTURE_UI_SHOW, (INTPTR) this); g_main_message_handler->RemoveDelayedMessage(MSG_MOUSE_GESTURE_UI_SHOW, (MH_PARAM_1)this, 0); } } void MouseGestureManager::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { OP_ASSERT(msg == MSG_MOUSE_GESTURE_UI_SHOW); // If the gesture has moved to a new gesture action, this resets the delay, // so we need to wait for the appropriate message, indicating a pause on one // specific gesture node. if (par2 == (MH_PARAM_2)m_instantiation_id && !m_ui_shown && g_input_manager->IsGestureRecognizing()) { if (m_listener) m_listener->OnGestureShow(); m_ui_shown = TRUE; } } void MouseGestureManager::ShowUIAfterDelay() { if (!m_callback_set) { g_main_message_handler->SetCallBack(this, MSG_MOUSE_GESTURE_UI_SHOW, (MH_PARAM_1)this); m_callback_set = TRUE; } g_main_message_handler->PostDelayedMessage( MSG_MOUSE_GESTURE_UI_SHOW, (MH_PARAM_1)this, (MH_PARAM_2)m_instantiation_id, MOUSE_GESTURE_UI_DELAY); } void MouseGestureManager::BeginPotentialGesture(OpPoint origin, OpInputContext* input_context) { m_gesture_origin = origin; m_active_idx = 0; m_ui_shown = FALSE; InitGestureTree(input_context); if (m_listener) m_listener->OnKillGestureUI(); m_instantiation_id++; ShowUIAfterDelay(); } void MouseGestureManager::InitGestureTree(OpInputContext* input_context) { m_gesture_tree.DeleteAll(); GestureNode* root_node = OP_NEW(GestureNode, ()); if (!root_node) return; if(OpStatus::IsError(m_gesture_tree.Add(root_node))) { OP_DELETE(root_node); return; } // So now we gotta find all the valid mouse gestures and add them to the tree. OpVector<OpInputContext> input_contexts; OpInputContext* ictx = input_context; for (;ictx; ictx = ictx->GetParentInputContext()) { input_contexts.Add(ictx); } for (int i = input_contexts.GetCount()-1; i >= 0; i--) { ictx = input_contexts.Get(i); const char* input_context_name = ictx->GetInputContextName(); ShortcutContext* shortcut_context = g_input_manager->GetShortcutContextFromActionMethodAndName(OpInputAction::METHOD_MOUSE, input_context_name); if (!shortcut_context) continue; int count = shortcut_context->GetShortcutActionCount(); for (int shortcut_action_pos = 0; shortcut_action_pos < count; shortcut_action_pos++) { ShortcutAction* shortcut_action = shortcut_context->GetShortcutActionFromIndex(shortcut_action_pos); if (!shortcut_action) continue; UINT32 shortcut_count = shortcut_action->GetShortcutCount(); BOOL is_a_gesture = TRUE; if (shortcut_count > MAX_SHORTCUT_SEQUENCE_LENGTH) { // holy shit, this gesture is long! skip it (at least for now) is_a_gesture = FALSE; } else { for (UINT32 i = 0; is_a_gesture && i < shortcut_count; i++) { OpKey::Code key = shortcut_action->GetShortcutByIndex(i)->GetKey(); if (shortcut_action->GetShortcutByIndex(i)->GetShiftKeys()) { // skip shift-gestures (at least for now) is_a_gesture = FALSE; } else { switch(key) { case OP_KEY_GESTURE_LEFT: case OP_KEY_GESTURE_RIGHT: case OP_KEY_GESTURE_UP: case OP_KEY_GESTURE_DOWN: break; // good, we maybe found a gesture default: is_a_gesture = FALSE; // this must not be a gesture } } } } if (!is_a_gesture) continue; // a good gesture, so add it to the m_gesture_tree AddToTree(root_node, shortcut_action, shortcut_action->GetAction()); } } } void MouseGestureManager::AddToTree(GestureNode* node, ShortcutAction* sa, OpInputAction* ia) { // First, we need to see how deep we have gone in the tree. // 'cut' could just as well have been called 'depth', I suppose, // but I called it 'cut' because it's also the index of // the relevant Shortcut. int cut = 0; while (cut < MAX_SHORTCUT_SEQUENCE_LENGTH && node->addr[cut] != -1) { cut++; } // Now, depending on 'cut', we do one of the following: // - set the action on this node // - fail (because we went too deep and ran out of space) // - move deeper down the tree, creating nodes as necessary, // until we get to the node we are looking for if (cut >= (int) sa->GetShortcutCount()) { // We are at the node we want, so set the corresponding action. node->action = ia; } else if (cut >= MAX_SHORTCUT_SEQUENCE_LENGTH) { // No more room, so just give up. // Maybe we should increase MAX_SHORTCUT_SEQUENCE_LENGTH if this happens. // (But seriously, who needs 10-move mouse gestures?!) return; } else { // Keep moving down the tree, creating nodes if necessary, // until we get to the node we are looking for. OpKey::Code key = sa->GetShortcutByIndex(cut)->GetKey(); int dir = 0; switch(key) { case OP_KEY_GESTURE_LEFT: dir = 0; break; case OP_KEY_GESTURE_RIGHT: dir = 1; break; case OP_KEY_GESTURE_UP: dir = 2; break; case OP_KEY_GESTURE_DOWN: dir = 3; break; } int next_node_idx = node->dirs[dir]; GestureNode* next_node = m_gesture_tree.Get(next_node_idx); if (!next_node) { // The node we want doesn't exist, so we have to create it. next_node = OP_NEW(GestureNode, ()); if (!next_node) return; if(OpStatus::IsError(m_gesture_tree.Add(next_node))) { OP_DELETE(next_node); return; } next_node_idx = m_gesture_tree.GetCount() - 1; node->dirs[dir] = next_node_idx; // make sure 'node' knows about its children // Now we need to store the address of the next node, // which is 'node->addr' plus 'dir' at the end. for (int i = 0; i < cut; i++) { next_node->addr[i] = node->addr[i]; } next_node->addr[cut] = dir; } AddToTree(next_node, sa, ia); } } void MouseGestureManager::UpdateMouseGesture(int dir) { GestureNode* curr_selected_node = m_gesture_tree.Get(m_active_idx); GestureNode* next_selected_node = NULL; if (curr_selected_node) { m_active_idx = curr_selected_node->dirs[dir]; next_selected_node = m_gesture_tree.Get(m_active_idx); } m_instantiation_id++; if (next_selected_node) { if (m_listener) m_listener->OnGestureMove(dir); ShowUIAfterDelay(); } else { CancelGesture(); m_active_idx = 0; } } void MouseGestureManager::EndGesture(BOOL gesture_was_cancelled) { m_ui_shown = TRUE; if (!m_listener) return; if (!gesture_was_cancelled && g_input_manager->WillKeyUpTriggerGestureAction(g_input_manager->GetGestureButton())) { m_listener->OnFadeOutGestureUI(m_active_idx); } else { m_listener->OnFadeOutGestureUI(-1); } } /* static */ OpKey::Code MouseGesture::CalculateMouseGesture(int delta_x, int delta_y, int threshold) { if (delta_x*delta_x + delta_y*delta_y < threshold*threshold) return OP_KEY_INVALID; OpKey::Code gesture = OP_KEY_INVALID; #if defined(OP_KEY_GESTURE_UP_ENABLED) && defined(OP_KEY_GESTURE_LEFT_ENABLED) && defined(OP_KEY_GESTURE_DOWN_ENABLED) && defined(OP_KEY_GESTURE_RIGHT_ENABLED) int delta_a, delta_b; if (delta_x >= 0) { if (delta_y < 0) { gesture = OP_KEY_GESTURE_UP; delta_a = -delta_y; delta_b = delta_x; } else { gesture = OP_KEY_GESTURE_RIGHT; delta_a = delta_x; delta_b = delta_y; } } else { if (delta_y >= 0) { gesture = OP_KEY_GESTURE_DOWN; delta_a = delta_y; delta_b = -delta_x; } else { gesture = OP_KEY_GESTURE_LEFT; delta_a = -delta_x; delta_b = -delta_y; } } if (delta_b > delta_a) { gesture = NextGesture(gesture); } #endif // (OP_KEY_GESTURE_UP_ENABLED) && (OP_KEY_GESTURE_LEFT_ENABLED) && (OP_KEY_GESTURE_DOWN_ENABLED) && (OP_KEY_GESTURE_RIGHT_ENABLED) return gesture; } #if 0 static OpKey::Code CalculateMouseGestureRef(int deltax, int deltay, int threshold) { double length = op_sqrt((double)((delta_x * delta_x) + (delta_y * delta_y))); if (length > threshold) { double angle = op_atan2((double)delta_x, (double)delta_y); OpKey::Code gesture = OP_KEY_GESTURE_UP; OpKey::Code next_gesture = OP_KEY_GESTURE_UP + 1; double pi = 3.1415926535; double sector_size = pi / 2; double sector_angle = (pi * 3 / 4); const INT32 last_gesture = OP_KEY_GESTURE_LEFT; for (; next_gesture <= last_gesture; next_gesture++, sector_angle -= sector_size) { if (angle <= sector_angle && angle >= (sector_angle - sector_size)) { gesture = next_gesture; break; } } if (gesture != m_last_gesture) { InvokeKeyPressed(gesture, SHIFTKEY_NONE); m_last_gesture = gesture; } m_last_gesture_mouse_position = new_mouse_position; } } #endif // 0 /* static */ OpKey::Code MouseGesture::NextGesture(OpKey::Code gesture, BOOL diagonal) { #if defined(OP_KEY_GESTURE_UP_ENABLED) && defined(OP_KEY_GESTURE_LEFT_ENABLED) && defined(OP_KEY_GESTURE_DOWN_ENABLED) && defined(OP_KEY_GESTURE_RIGHT_ENABLED) if (!diagonal) { switch (gesture) { case OP_KEY_GESTURE_UP: return OP_KEY_GESTURE_RIGHT; case OP_KEY_GESTURE_LEFT: return OP_KEY_GESTURE_UP; case OP_KEY_GESTURE_DOWN: return OP_KEY_GESTURE_LEFT; case OP_KEY_GESTURE_RIGHT: return OP_KEY_GESTURE_DOWN; } } #endif // OP_KEY_GESTURE_UP_ENABLED && OP_KEY_GESTURE_LEFT_ENABLED && OP_KEY_GESTURE_DOWN_ENABLED && OP_KEY_GESTURE_RIGHT_ENABLED return OP_KEY_INVALID; } #endif // MOUSE_SUPPORT /*********************************************************************************** ** ** OpKeyToLanguageString ** ***********************************************************************************/ /* static */ OP_STATUS OpInputManager::OpKeyToLanguageString(OpKey::Code key, OpString& string) { switch (key) { case OP_KEY_HOME: return g_languageManager->GetStringL(Str::M_KEY_HOME, string); case OP_KEY_END: return g_languageManager->GetStringL(Str::M_KEY_END, string); case OP_KEY_PAGEUP: return g_languageManager->GetStringL(Str::M_KEY_PAGEUP, string); case OP_KEY_PAGEDOWN: return g_languageManager->GetStringL(Str::M_KEY_PAGEDOWN, string); case OP_KEY_UP: return g_languageManager->GetStringL(Str::M_KEY_UP, string); case OP_KEY_DOWN: return g_languageManager->GetStringL(Str::M_KEY_DOWN, string); case OP_KEY_LEFT: return g_languageManager->GetStringL(Str::M_KEY_LEFT, string); case OP_KEY_RIGHT: return g_languageManager->GetStringL(Str::M_KEY_RIGHT, string); case OP_KEY_ESCAPE: return g_languageManager->GetStringL(Str::M_KEY_ESCAPE, string); case OP_KEY_INSERT: return g_languageManager->GetStringL(Str::M_KEY_INSERT, string); case OP_KEY_DELETE: return g_languageManager->GetStringL(Str::M_KEY_DELETE, string); case OP_KEY_BACKSPACE: return g_languageManager->GetStringL(Str::M_KEY_BACKSPACE, string); case OP_KEY_TAB: return g_languageManager->GetStringL(Str::M_KEY_TAB, string); case OP_KEY_SPACE: return g_languageManager->GetStringL(Str::M_KEY_SPACE, string); case OP_KEY_ENTER: return g_languageManager->GetStringL(Str::M_KEY_ENTER, string); #ifdef OP_KEY_SUBTRACT_ENABLED case OP_KEY_SUBTRACT: return string.Set("-"); #endif #ifdef OP_KEY_OEM_MINUS_ENABLED case OP_KEY_OEM_MINUS: return string.Set("-"); #endif #ifdef OP_KEY_OEM_PLUS_ENABLED case OP_KEY_OEM_PLUS: return string.Set("+"); #endif } // fallback const uni_char* key_string = OpKey::ToString(key); if (key_string) RETURN_IF_ERROR(string.Set(key_string)); return OpStatus::OK; } /*********************************************************************************** ** ** OpInputManager ** ***********************************************************************************/ #ifndef HAS_COMPLEX_GLOBALS extern void init_s_action_strings(); #endif // !HAS_COMPLEX_GLOBALS OpInputManager::OpInputManager() : m_full_update(FALSE) , m_update_message_pending(FALSE) , m_keyboard_input_context(NULL) , m_old_keyboard_input_context(NULL) , m_lock_keyboard_input_context(FALSE) , m_key_sequence_id(0) , m_keyboard_shortcut_context_list(OpInputAction::METHOD_KEYBOARD) , m_block_input_recording(FALSE) , m_action_first_input_context(NULL) #if !defined(IM_UI_HANDLES_SHORTCUTS) , m_external_input_listener(NULL) #endif // !IM_UI_HANDLES_SHORTCUTS #ifdef MOUSE_SUPPORT , m_mouse_input_context(NULL) , m_lock_mouse_input_context(FALSE) , m_is_flipping(FALSE) , m_last_gesture(0) , m_loaded_gesture_action(NULL) , m_gesture_recording_was_attempted(FALSE) , m_mouse_shortcut_context_list(OpInputAction::METHOD_MOUSE) , m_mouse_gestures_temporarily_disabled(FALSE) #endif // MOUSE_SUPPORT , m_touch_state(0) { CONST_ARRAY_INIT(s_action_strings); } OP_STATUS OpInputManager::Construct() { RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_UPDATE_ALL_INPUT_STATES, (MH_PARAM_1)this)); RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_IM_ACTION_DELAY, (MH_PARAM_1)this)); return OpStatus::OK; } OpInputManager::~OpInputManager() { g_main_message_handler->UnsetCallBacks(this); } /*********************************************************************************** ** ** Flush ** ***********************************************************************************/ void OpInputManager::Flush() { #ifdef MOUSE_SUPPORT m_mouse_shortcut_context_list.Flush(); #endif // MOUSE_SUPPORT m_keyboard_shortcut_context_list.Flush(); } /*********************************************************************************** ** ** RegisterActivity() ** ***********************************************************************************/ void OpInputManager::RegisterActivity() { #ifdef QUICK if( g_application ) { g_application->RegisterActivity(); } #endif } #ifdef MOUSE_SUPPORT BOOL OpInputManager::ShouldInvokeGestures() { if (m_block_input_recording || m_mouse_gestures_temporarily_disabled) { return FALSE; } return g_pccore->GetIntegerPref(PrefsCollectionCore::EnableGesture); } #endif // MOUSE_SUPPORT /*********************************************************************************** ** ** BroadcastInputContextChanged() ** ***********************************************************************************/ void OpInputManager::BroadcastInputContextChanged(BOOL keyboard, OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason) const { OpInputContext* input_context = old_input_context; while (input_context) { OpInputContext* parent_context = input_context->GetParentInputContext(); if (keyboard) { input_context->OnKeyboardInputLost(new_input_context, old_input_context, reason); } else { input_context->OnMouseInputLost(new_input_context, old_input_context); } input_context = parent_context; } input_context = new_input_context; while (input_context) { if (keyboard) { input_context->OnKeyboardInputGained(new_input_context, old_input_context, reason); } else { input_context->OnMouseInputGained(new_input_context, old_input_context); } input_context = input_context->GetParentInputContext(); } } /*********************************************************************************** ** ** SetKeyboardInputContext ** ***********************************************************************************/ void OpInputManager::SetKeyboardInputContext(OpInputContext* input_context, FOCUS_REASON reason) { if (m_keyboard_input_context != input_context && !m_lock_keyboard_input_context) { // check if input context is available, and only then switch (always allow NULL input_context) // To be available means that all parents must also be available BOOL switch_available = TRUE; OpInputContext* parent_context = input_context; while (parent_context) { if (!parent_context->IsInputContextAvailable(reason)) { switch_available = FALSE; break; } else if (!parent_context->IsParentInputContextAvailabilityRequired()) { break; } parent_context = parent_context->GetParentInputContext(); } if (switch_available) { // Inform new and old keyboard input contexts and all their parents about the change m_old_keyboard_input_context = m_keyboard_input_context; m_keyboard_input_context = input_context; // input context was available, so update recent child pointers up to root UpdateRecentKeyboardChildInputContext(input_context); m_key_sequence_id = 0; BroadcastInputContextChanged(TRUE, m_keyboard_input_context, m_old_keyboard_input_context, reason); if (m_keyboard_input_context) { OpInputAction input_action(OpInputAction::ACTION_LOWLEVEL_NEW_KEYBOARD_CONTEXT); InvokeActionInternal(&input_action); } } else if (input_context) { // input context wasn't available, but still update active child pointers up to the point where it meets the current active one UpdateRecentKeyboardChildInputContext(input_context); } } } /*********************************************************************************** ** ** UpdateRecentKeyboardChildInputContext ** ***********************************************************************************/ void OpInputManager::UpdateRecentKeyboardChildInputContext(OpInputContext* input_context) { OpInputContext* parent_context = input_context; while (parent_context && (!m_keyboard_input_context || input_context == m_keyboard_input_context || parent_context->GetRecentKeyboardChildInputContext() != m_keyboard_input_context)) { parent_context->SetRecentKeyboardChildInputContext(input_context); if (!parent_context->IsParentInputContextAvailabilityRequired()) { break; } parent_context = parent_context->GetParentInputContext(); } } /*********************************************************************************** ** ** RestoreKeyboardInputContext ** ***********************************************************************************/ void OpInputManager::RestoreKeyboardInputContext(OpInputContext* input_context, OpInputContext* fallback_input_context, FOCUS_REASON reason) { if (input_context->GetRecentKeyboardChildInputContext() && input_context->GetRecentKeyboardChildInputContext()->IsInputContextAvailable(reason)) { input_context = input_context->GetRecentKeyboardChildInputContext(); } else if (fallback_input_context) { input_context = fallback_input_context; } SetKeyboardInputContext(input_context, reason); } /*********************************************************************************** ** ** SetMouseInputContext ** ***********************************************************************************/ #ifdef MOUSE_SUPPORT void OpInputManager::SetMouseInputContext(OpInputContext* input_context) { if (m_mouse_input_context != input_context && !m_lock_mouse_input_context) { // Inform new and old mouse input context about the change OpInputContext* old_mouse_input_context = m_mouse_input_context; m_mouse_input_context = input_context; BroadcastInputContextChanged(FALSE, m_mouse_input_context, old_mouse_input_context); if (m_mouse_input_context) { OpInputAction input_action(OpInputAction::ACTION_LOWLEVEL_NEW_MOUSE_CONTEXT); InvokeActionInternal(&input_action, m_mouse_input_context); } } } #endif // MOUSE_SUPPORT /*********************************************************************************** ** ** ReleaseInputContext ** ***********************************************************************************/ void OpInputManager::ReleaseInputContext(OpInputContext* input_context, FOCUS_REASON reason, BOOL keep_keyboard_focus /*= FALSE*/) { // make sure noone above has recent children that points to input_context's recent child. if (input_context == m_old_keyboard_input_context) m_old_keyboard_input_context = NULL; OpInputContext* parent_context = input_context->GetParentInputContext(); if (input_context == m_action_first_input_context) m_action_first_input_context = parent_context; while (parent_context && parent_context->GetRecentKeyboardChildInputContext() == input_context->GetRecentKeyboardChildInputContext()) { parent_context->SetRecentKeyboardChildInputContext(NULL); parent_context = parent_context->GetParentInputContext(); } if (!keep_keyboard_focus) { // if current context lies in the path now being cut off, give focus to something // higher in the chain OpInputContext* check_input_context = m_keyboard_input_context; while (check_input_context) { if (input_context == check_input_context) { break; } check_input_context = check_input_context->GetParentInputContext(); } if (check_input_context) { m_lock_keyboard_input_context = FALSE; // set focus to first one that is really available OpInputContext* parent_input_context = input_context->GetParentInputContext(); OpInputContext* new_input_context = parent_input_context; while (parent_input_context) { if (!parent_input_context->IsInputContextAvailable(reason)) { new_input_context = parent_input_context->GetParentInputContext(); } else if (!parent_input_context->IsParentInputContextAvailabilityRequired()) { break; } parent_input_context = parent_input_context->GetParentInputContext(); } SetKeyboardInputContext(new_input_context, reason); } } #ifdef MOUSE_SUPPORT if (input_context == m_mouse_input_context) { m_lock_mouse_input_context = FALSE; SetMouseInputContext(NULL); } #endif // MOUSE_SUPPORT } /*********************************************************************************** ** ** SetMousePosition ** ***********************************************************************************/ #ifdef MOUSE_SUPPORT void OpInputManager::SetMousePosition(const OpPoint& new_mouse_position, INT32 ignore_modifiers) { OpRandomGenerator::AddEntropyFromTimeAllGenerators(); if (m_mouse_position.Equals(new_mouse_position)) return; INT32 pos_data[2]; /* ARRAY OK 2009-02-04 haavardm */ pos_data[0] = new_mouse_position.x; pos_data[1] = new_mouse_position.y; OpRandomGenerator::AddEntropyAllGenerators(pos_data, sizeof(pos_data), 8); m_mouse_position = new_mouse_position; RegisterActivity(); if (IsGestureRecognizing() && ShouldInvokeGestures()) { int threshold = g_pccore->GetIntegerPref(PrefsCollectionCore::GestureThreshold); int delta_x = new_mouse_position.x - m_last_gesture_mouse_position.x; int delta_y = new_mouse_position.y - m_last_gesture_mouse_position.y; OpKey::Code gesture = MouseGesture::CalculateMouseGesture(delta_x, delta_y, threshold); if (gesture != OP_KEY_INVALID) { if (gesture != m_last_gesture) { INT32 shiftkeys = 0; # ifdef OPSYSTEMINFO_SHIFTSTATE shiftkeys = g_op_system_info->GetShiftKeyState() & ~ignore_modifiers; # endif // OPSYSTEMINFO_SHIFTSTATE InvokeKeyPressed(gesture, shiftkeys); m_last_gesture = gesture; int dir = -1; switch(gesture) { case OP_KEY_GESTURE_LEFT: dir = 0; break; case OP_KEY_GESTURE_RIGHT: dir = 1; break; case OP_KEY_GESTURE_UP: dir = 2; break; case OP_KEY_GESTURE_DOWN: dir = 3; break; } if (dir >= 0) m_gesture_manager.UpdateMouseGesture(dir); } m_last_gesture_mouse_position = new_mouse_position; } } } #endif // MOUSE_SUPPORT /*********************************************************************************** ** ** GetFlipButtons ** ***********************************************************************************/ #ifdef MOUSE_SUPPORT void OpInputManager::GetFlipButtons(OpKey::Code &back_button, OpKey::Code &forward_button) const { if (g_pccore->GetIntegerPref(PrefsCollectionCore::ReverseButtonFlipping)) { back_button = OP_KEY_MOUSE_BUTTON_2; forward_button = OP_KEY_MOUSE_BUTTON_1; } else { back_button = OP_KEY_MOUSE_BUTTON_1; forward_button = OP_KEY_MOUSE_BUTTON_2; } } #endif // MOUSE_SUPPORT /*********************************************************************************** ** ** GetInputContextFromKey ** ***********************************************************************************/ OpInputContext* OpInputManager::GetInputContextFromKey(OpKey::Code key) { (void)key; //Yes compiler, we declare and possibly do not use this variable.. #ifdef MOUSE_SUPPORT OpInputAction::ActionMethod method = GetActionMethodFromKey(key); #endif // MOUSE_SUPPORT #ifdef MOUSE_SUPPORT if (method == OpInputAction::METHOD_MOUSE) return m_mouse_input_context; #endif // MOUSE_SUPPORT return m_keyboard_input_context; } /*********************************************************************************** ** ** GetActionMethodFromKey ** ***********************************************************************************/ OpInputAction::ActionMethod OpInputManager::GetActionMethodFromKey(OpKey::Code key) { (void)key; //Yes compiler, we declare and possibly do not use this variable.. #ifdef MOUSE_SUPPORT if (IS_OP_KEY_MOUSE_BUTTON(key) || IS_OP_KEY_GESTURE(key) || IS_OP_KEY_FLIP(key) || IsGestureRecognizing()) return OpInputAction::METHOD_MOUSE; #endif // MOUSE_SUPPORT return OpInputAction::METHOD_KEYBOARD; } /*********************************************************************************** ** ** InvokeAction ** ***********************************************************************************/ BOOL OpInputManager::InvokeAction(OpInputAction::Action action, INTPTR action_data, const uni_char* action_data_string, OpInputContext* first, OpInputContext* last, BOOL send_prefilter_action, OpInputAction::ActionMethod action_method) { OpInputAction input_action(action); input_action.SetActionData(action_data); input_action.SetActionDataString(action_data_string); return InvokeAction(&input_action, first, last, send_prefilter_action, action_method); } BOOL OpInputManager::InvokeAction(OpInputAction::Action action, INTPTR action_data, const uni_char* action_data_string, const uni_char* action_data_string_param, OpInputContext* first, OpInputContext* last, BOOL send_prefilter_action, OpInputAction::ActionMethod action_method) { OpInputAction input_action(action); input_action.SetActionData(action_data); input_action.SetActionDataString(action_data_string); input_action.SetActionDataStringParameter(action_data_string_param); return InvokeAction(&input_action, first, last, send_prefilter_action, action_method); } BOOL OpInputManager::InvokeAction(OpInputAction* action, OpInputContext* first, OpInputContext* last, BOOL send_prefilter_action, OpInputAction::ActionMethod action_method) { if (!action) return FALSE; #ifdef ACTION_CYCLE_TO_NEXT_PAGE_ENABLED if (action->GetAction() == OpInputAction::ACTION_CYCLE_TO_NEXT_PAGE) m_gesture_manager.CancelGesture(); #endif // ACTION_CYCLE_TO_NEXT_PAGE_ENABLED #ifdef ACTION_CYCLE_TO_PREVIOUS_PAGE_ENABLED if (action->GetAction() == OpInputAction::ACTION_CYCLE_TO_PREVIOUS_PAGE) m_gesture_manager.CancelGesture(); #endif // ACTION_CYCLE_TO_PREVIOUS_PAGE_ENABLED OpInputAction* action_copy = OpInputAction::CopyInputActions(action); if (action_copy == NULL) return FALSE; if (action_method != OpInputAction::METHOD_OTHER) { OpInputAction* next = action_copy; while (next) { next->SetActionMethod(action_method); next = next->GetNextInputAction(); } } BOOL handled = InvokeActionInternal(action_copy, first, last, send_prefilter_action); OP_DELETE(action_copy); return handled; } /*********************************************************************************** ** ** InvokeKeyDown ** ***********************************************************************************/ BOOL OpInputManager::InvokeKeyDown(OpKey::Code key, ShiftKeyState shift_keys) { /* Should only be used for keys not producing any character values. */ OP_ASSERT(OpKey::IsModifier(key) || OpKey::IsFunctionKey(key) || key == OP_KEY_ENTER || key == OP_KEY_ESCAPE || key >= 0x100); return InvokeKeyDown(key, NULL, 0, NULL, shift_keys, FALSE, OpKey::LOCATION_STANDARD, TRUE); } BOOL OpInputManager::InvokeKeyDown(OpKey::Code key, const uni_char *value, OpPlatformKeyEventData *event_data, ShiftKeyState shift_keys, BOOL repeat, OpKey::Location location, BOOL send_prefilter_action) { return InvokeKeyDown(key, reinterpret_cast<const char *>(value), UINT_MAX, event_data, shift_keys, repeat, location, send_prefilter_action); } BOOL OpInputManager::InvokeKeyDown(OpKey::Code key, const char *value, unsigned value_length, OpPlatformKeyEventData *event_data, ShiftKeyState shift_keys, BOOL repeat, OpKey::Location location, BOOL send_prefilter_action) { OP_ASSERT(IS_OP_KEY(key) || !"Unmapped keycode, please check virtual keycode remapping."); if (!IS_OP_KEY(key)) return TRUE; RegisterActivity(); if( key != OP_KEY_ESCAPE ) { #ifdef MOUSE_SUPPORT m_gesture_recording_was_attempted = false; m_gesture_manager.CancelGesture(); #endif // MOUSE_SUPPORT } #ifdef SKIN_SUPPORT // Count "in place drag" as drag, too. if (g_widget_globals->captured_widget && g_widget_globals->captured_widget->IsFloating()) { if( key == OP_KEY_ESCAPE || IS_OP_KEY_MOUSE_BUTTON(key)) { ResetInput(); } return TRUE; } #endif // SKIN_SUPPORT if (IS_OP_KEY_MOUSE_BUTTON(key)) { if(g_windowManager) { g_windowManager->ResetCurrentClickedURLAndWindow(); } } if (send_prefilter_action) { if (!m_block_input_recording) { if (OpStatus::IsMemoryError(m_key_down_hashtable.Add(key))) return FALSE; } } #ifdef MOUSE_SUPPORT #if defined (OP_KEY_FLIP_BACK_ENABLED) && defined (OP_KEY_FLIP_FORWARD_ENABLED) OpKey::Code back_button, forward_button; GetFlipButtons(back_button, forward_button); if (key == back_button && IsKeyDown(forward_button)) { SetFlipping(TRUE); if (g_pccore->GetIntegerPref(PrefsCollectionCore::EnableMouseFlips)) InvokeKeyPressed(OP_KEY_FLIP_BACK, shift_keys); } else if (key == forward_button && IsKeyDown(back_button)) { SetFlipping(TRUE); if (g_pccore->GetIntegerPref(PrefsCollectionCore::EnableMouseFlips)) InvokeKeyPressed(OP_KEY_FLIP_FORWARD, shift_keys); } if (IsFlipping()) { return TRUE; } #endif // OP_KEY_FLIP_BACK_ENABLED && OP_KEY_FLIP_FORWARD_ENABLED if (key == GetGestureButton()) { m_last_gesture_mouse_position = m_mouse_position; m_first_gesture_mouse_position = m_mouse_position; m_last_gesture = 0; if (ShouldInvokeGestures()) m_gesture_manager.BeginPotentialGesture(m_mouse_position, m_mouse_input_context); } #endif // MOUSE_SUPPORT if (m_key_sequence_id == 0) { OpInputAction input_action(OpInputAction::ACTION_LOWLEVEL_KEY_DOWN, key, shift_keys, repeat, location, GetActionMethodFromKey(key)); OpInputContext* input_context = GetInputContextFromKey(key); if (value_length == UINT_MAX) { if (value && OpStatus::IsError(input_action.SetActionKeyValue(reinterpret_cast<const uni_char *>(value)))) g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); } else if (value_length > 0 && OpStatus::IsError(input_action.SetActionKeyValue(value, value_length))) g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); if (event_data) input_action.SetPlatformKeyEventData(event_data); if (InvokeActionInternal(&input_action, input_context, input_context, send_prefilter_action)) { // NOTE: until all code is phased over to use this kind of mouse input // we should only return TRUE (which means mouseclick handled) only for keyboard keys // This is so that platform code can like before let the mouse click continue to // OpView mouse listeners etc. return !IS_OP_KEY_MOUSE_BUTTON(key); // return TRUE; } } #ifdef MOUSE_SUPPORT if (key != OP_KEY_MOUSE_BUTTON_1 && key != OP_KEY_MOUSE_BUTTON_2 && IS_OP_KEY_MOUSE_BUTTON(key)) { // mouse buttons with index 3 or greater are allowed to be translated into // actions, just like key clicks. // This is done at KeyDown, while something similar for mouse button 1 and 2 // must be done at KeyUp so that gestures and dragging can be done // without conflicting with those.. .anyway, we don't support translating for // the main 1 and 2 buttons now.. too much code around in Opera needs to be // changed first. return InvokeKeyPressed(key, NULL, shift_keys, FALSE, send_prefilter_action); } #endif // MOUSE_SUPPORT return FALSE; } /*********************************************************************************** ** ** InvokeKeyUp ** ***********************************************************************************/ BOOL OpInputManager::InvokeKeyUp(OpKey::Code key, ShiftKeyState shift_keys) { /* Should only be used for keys not producing any character values. */ OP_ASSERT(OpKey::IsModifier(key) || OpKey::IsFunctionKey(key) || key == OP_KEY_ENTER || key == OP_KEY_ESCAPE || key >= 0x100); return InvokeKeyUp(key, NULL, 0, NULL, shift_keys, FALSE, OpKey::LOCATION_STANDARD, TRUE); } BOOL OpInputManager::InvokeKeyUp(OpKey::Code key, const uni_char *value, OpPlatformKeyEventData *event_data, ShiftKeyState shift_keys, BOOL repeat, OpKey::Location location, BOOL send_prefilter_action) { return InvokeKeyUp(key, reinterpret_cast<const char *>(value), UINT_MAX, event_data, shift_keys, repeat, location, send_prefilter_action); } BOOL OpInputManager::InvokeKeyUp(OpKey::Code key, const char *value, unsigned value_length, OpPlatformKeyEventData *event_data, ShiftKeyState shift_keys, BOOL repeat, OpKey::Location location, BOOL send_prefilter_action) { OP_ASSERT(IS_OP_KEY(key) || !"Unmapped keycode, please check virtual keycode remapping."); if (!IS_OP_KEY(key)) return TRUE; RegisterActivity(); if (send_prefilter_action) { if (!m_block_input_recording) OpStatus::Ignore(m_key_down_hashtable.Remove(key)); } // Code used to close the alt-tab cycler on desktop. // FIXME: This code should preferrably not be here. #ifdef ACTION_CLOSE_CYCLER_ENABLED if ((key == OP_KEY_CTRL || key == OP_KEY_ALT #ifdef OP_KEY_MAC_CTRL_ENABLED || key == OP_KEY_MAC_CTRL #endif // OP_KEY_MAC_CTRL_ENABLED #ifdef MOUSE_SUPPORT || key == GetGestureButton() #endif // MOUSE_SUPPORT ) && InvokeAction(OpInputAction::ACTION_CLOSE_CYCLER, 1)) { #ifdef MOUSE_SUPPORT SetFlipping(FALSE); m_loaded_gesture_action = NULL; m_gesture_manager.CancelGesture(); #endif // MOUSE_SUPPORT m_key_sequence_id = 0; return TRUE; } #endif // ACTION_CLOSE_CYCLER_ENABLED #ifdef MOUSE_SUPPORT if (IsFlipping()) { OpKey::Code back_button, forward_button; GetFlipButtons(back_button, forward_button); if (!IsKeyDown(back_button) && !IsKeyDown(forward_button)) { SetFlipping(FALSE); m_loaded_gesture_action = NULL; m_gesture_manager.CancelGesture(); m_key_sequence_id = 0; } return TRUE; } #endif // MOUSE_SUPPORT #ifdef MOUSE_SUPPORT if (key == GetGestureButton()) { m_key_sequence_id = 0; if (m_loaded_gesture_action) { OpInputAction* loaded_gesture_action = m_loaded_gesture_action; OpInputContext* mouse_input_context = m_mouse_input_context; loaded_gesture_action->SetActionPosition(m_first_gesture_mouse_position); loaded_gesture_action->SetGestureInvoked(TRUE); if (m_mouse_input_context && ShouldInvokeGestures()) { InvokeAction(loaded_gesture_action, mouse_input_context, NULL, TRUE, OpInputAction::METHOD_MOUSE); } m_gesture_manager.EndGesture(); m_loaded_gesture_action = NULL; return TRUE; } else if( m_gesture_recording_was_attempted || m_block_input_recording ) { // Do not open popup menu after a failed or aborted gesture stroke or when we block recording return TRUE; } else { // No gesture action, even though we were gesturing, means that // we default to rt-click bringing up the context menu. So we // have to end this gesture, but don't return TRUE. m_gesture_manager.EndGesture(); } } #endif // MOUSE_SUPPORT if (m_key_sequence_id == 0) { OpInputAction input_action(OpInputAction::ACTION_LOWLEVEL_KEY_UP, key, shift_keys, repeat, location, GetActionMethodFromKey(key)); OpInputContext* input_context = GetInputContextFromKey(key); if (value_length == UINT_MAX) { if (value && OpStatus::IsError(input_action.SetActionKeyValue(reinterpret_cast<const uni_char *>(value)))) g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); } else if (value_length > 0 && OpStatus::IsError(input_action.SetActionKeyValue(value, value_length))) g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); if (event_data) input_action.SetPlatformKeyEventData(event_data); if (InvokeActionInternal(&input_action, input_context, input_context, send_prefilter_action)) { // NOTE: until all code is phased over to use this kind of mouse input // we should only return TRUE (which means mouseclick handled) only for keyboard keys // This is so that platform code can like before let the mouse click continue to // OpView mouse listeners etc. return !IS_OP_KEY_MOUSE_BUTTON(key); // return TRUE; } } return FALSE; } /*********************************************************************************** ** ** InvokeKeyPressed ** ***********************************************************************************/ BOOL OpInputManager::InvokeKeyPressed(OpKey::Code key, ShiftKeyState shift_keys) { OP_ASSERT(OpKey::IsModifier(key) || OpKey::IsFunctionKey(key) || key == OP_KEY_ENTER || key == OP_KEY_ESCAPE || key >= 0x100); return InvokeKeyPressed(key, NULL, 0, shift_keys, FALSE, TRUE); } BOOL OpInputManager::InvokeKeyPressed(OpKey::Code key, const uni_char *value, ShiftKeyState shift_keys, BOOL repeat, BOOL send_prefilter_action) { return InvokeKeyPressed(key, reinterpret_cast<const char *>(value), UINT_MAX, shift_keys, repeat, send_prefilter_action); } BOOL OpInputManager::InvokeKeyPressed(OpKey::Code key, const char *value, unsigned value_length, ShiftKeyState shift_keys, BOOL repeat, BOOL send_prefilter_action) { OP_ASSERT(IS_OP_KEY(key) || !"Unmapped keycode, please check virtual keycode remapping."); if (!IS_OP_KEY(key)) return TRUE; OpRandomGenerator::AddEntropyAllGenerators(&key, sizeof(key), 5); OpRandomGenerator::AddEntropyFromTimeAllGenerators(); RegisterActivity(); uni_char key_value = 0; OpInputAction::ActionMethod method = GetActionMethodFromKey(key); OpInputContext* input_context = GetInputContextFromKey(key); if (m_key_sequence_id > 0 #ifdef MOUSE_SUPPORT || IsGestureRecognizing() #endif // MOUSE_SUPPORT ) { if (key == OP_KEY_ESCAPE) { m_key_sequence_id = 0; #ifdef MOUSE_SUPPORT m_loaded_gesture_action = NULL; m_gesture_manager.CancelGesture(); #endif // MOUSE_SUPPORT return TRUE; } } else if (input_context && method == OpInputAction::METHOD_KEYBOARD) { // not sure how to handle this yet.. kludge for 7.0 final #ifdef ACTION_CLOSE_CYCLER_ENABLED if (key == OP_KEY_ESCAPE && InvokeAction(OpInputAction::ACTION_CLOSE_CYCLER)) return TRUE; #endif // ACTION_CLOSE_CYCLER_ENABLED // send lowlevel key pressed for real keys if (!IS_OP_KEY_MODIFIER(key)) { OpInputAction input_action(OpInputAction::ACTION_LOWLEVEL_KEY_PRESSED, key, shift_keys, repeat, OpKey::LOCATION_STANDARD, method); if (value_length == UINT_MAX) { if (value && OpStatus::IsError(input_action.SetActionKeyValue(reinterpret_cast<const uni_char *>(value)))) g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); } else if (value_length > 0 && OpStatus::IsError(input_action.SetActionKeyValue(value, value_length))) g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); if (input_action.GetKeyValue()) key_value = *input_action.GetKeyValue(); if (InvokeActionInternal(&input_action, input_context, input_context, send_prefilter_action)) { return TRUE; } // reread input_context, if previous call caused focus to change input_context = GetInputContextFromKey(key); } } // don't translate modifier key presses to actions if (IS_OP_KEY_MODIFIER(key)) return FALSE; BOOL incomplete_sequence_found = FALSE; m_key_sequence[m_key_sequence_id].Set(key, shift_keys, key_value); for (;input_context; input_context = input_context->GetParentInputContext()) { ShortcutContext* shortcut_context = GetShortcutContextFromActionMethodAndName(method, input_context->GetInputContextName()); if (!shortcut_context) { continue; } INT32 count = shortcut_context->GetShortcutActionCount(); for (INT32 shortcut_action_pos = 0; shortcut_action_pos < count; shortcut_action_pos++) { ShortcutAction* shortcut_action = shortcut_context->GetShortcutActionFromIndex(shortcut_action_pos); // Check if the current key sequence is a possible match for this short cut. Skip otherwise. if (!shortcut_action->MatchesKeySequence(m_key_sequence, m_key_sequence_id)) continue; // check if more keypresses are needed before action is invoked if (shortcut_action->GetShortcutCount() - 1 > m_key_sequence_id) { incomplete_sequence_found = TRUE; continue; } // if gesture recognizing, save action for later trigger #ifdef MOUSE_SUPPORT if (IsGestureRecognizing()) { m_gesture_recording_was_attempted = TRUE; m_loaded_gesture_action = shortcut_action->GetAction(); if (m_key_sequence_id < MAX_SHORTCUT_SEQUENCE_LENGTH) { m_key_sequence_id++; } return TRUE; } #endif // MOUSE_SUPPORT OpInputAction * input_action = shortcut_action->GetAction(); // this will set the correct action states to all actions in the action list if (GetActionState(input_action, GetInputContextFromKey(key)) & OpInputAction::STATE_DISABLED) { while ( input_action ) { INT32 state = input_action->GetActionState(); // Only look for the next action if this one is specifically disabled if (!(state & OpInputAction::STATE_DISABLED)) break; // all actions where disabled, don't invoke anything if (!input_action->GetNextInputAction()) input_action = NULL; else input_action = input_action->GetNextInputAction(); } } BOOL handled = FALSE; if (input_action) handled = InvokeAction(input_action, GetInputContextFromKey(key), input_context, send_prefilter_action, method); if (handled) { m_key_sequence_id = 0; return TRUE; } } } if (incomplete_sequence_found #ifdef MOUSE_SUPPORT || IsGestureRecognizing() #endif // MOUSE_SUPPORT ) { #ifdef MOUSE_SUPPORT m_loaded_gesture_action = NULL; #endif // MOUSE_SUPPORT if (m_key_sequence_id < MAX_SHORTCUT_SEQUENCE_LENGTH) { m_key_sequence_id++; } return TRUE; } else { #if !defined(IM_UI_HANDLES_SHORTCUTS) if (m_external_input_listener) m_external_input_listener->OnKeyPressed(key, shift_keys); #endif // !IM_UI_HANDLES_SHORTCUTS m_key_sequence_id = 0; return FALSE; } } /*********************************************************************************** ** ** ResetInput ** ***********************************************************************************/ void OpInputManager::ResetInput() { m_key_down_hashtable.RemoveAll(); m_key_sequence_id = 0; #ifdef MOUSE_SUPPORT m_loaded_gesture_action = NULL; m_gesture_manager.CancelGesture(); m_is_flipping = FALSE; OpWidget::ZeroCapturedWidget(); OpWidget::ZeroHoveredWidget(); #endif // MOUSE_SUPPORT } /*********************************************************************************** ** ** InvokeActionInternal ** ***********************************************************************************/ BOOL OpInputManager::InvokeActionInternal(OpInputAction* input_action, OpInputContext* first_input_context, OpInputContext* last_input_context, BOOL send_prefilter_action) { if (!input_action) return FALSE; if (!first_input_context) { first_input_context = m_keyboard_input_context; if (!first_input_context) return FALSE; } input_action->SetFirstInputContext(first_input_context); #ifdef MOUSE_SUPPORT if (input_action->IsMouseInvoked() && !input_action->IsGestureInvoked()) { input_action->SetActionPosition(m_mouse_position); } #endif // MOUSE_SUPPORT // send prefilter actions first if (send_prefilter_action) { OpInputAction pre_filter_action(input_action, OpInputAction::ACTION_LOWLEVEL_PREFILTER_ACTION); OpInputContext* next_input_context = first_input_context; while (next_input_context) { if (!next_input_context->IsInputDisabled() && next_input_context->OnInputAction(&pre_filter_action)) { return TRUE; } next_input_context = next_input_context->GetParentInputContext(); } } // usually start with first, but if OPERATOR_NEXT is used, search for first selected // item and start with the one after that OpInputAction* first_input_action = input_action; OpInputAction* next_input_action = first_input_action; while (next_input_action->GetActionOperator() == OpInputAction::OPERATOR_NEXT && next_input_action->GetNextInputAction()) { INT32 action_state = GetActionState(next_input_action, first_input_context); next_input_action = next_input_action->GetNextInputAction(); if (action_state & OpInputAction::STATE_SELECTED) { first_input_action = next_input_action; break; } } // restart next_input_action = first_input_action; // send one or more of the actions to first context and up to last one BOOL handled = FALSE; BOOL update_states = FALSE; m_action_first_input_context = first_input_context; while (next_input_action) { # ifdef ACTION_DELAY_ENABLED if(next_input_action->GetAction() == OpInputAction::ACTION_DELAY) { UINT32 delay = (UINT32)next_input_action->GetActionData(); if(delay) { g_main_message_handler->PostDelayedMessage(MSG_IM_ACTION_DELAY, (MH_PARAM_1)this, (MH_PARAM_2)next_input_action->GetNextInputAction(), delay); next_input_action->SetNextInputAction(NULL); return TRUE; } } # endif // ACTION_DELAY_ENABLED #ifdef QUICK if( g_application ) { if(g_application->KioskFilter(next_input_action)) return TRUE; } #endif OpInputContext* next_input_context = m_action_first_input_context; while (next_input_context) { if (next_input_action->GetActionMethod() != OpInputAction::METHOD_OTHER && next_input_context->IsInputDisabled()) { break; } // kludge until we get enum return value from OnInputAction.. just don't bother to change all those now next_input_action->SetWasReallyHandled(TRUE); if (next_input_context->OnInputAction(next_input_action)) { handled = TRUE; if (next_input_action->IsUpdateAction()) { update_states = TRUE; } break; } if (next_input_context == last_input_context) { break; } next_input_context = next_input_context->GetParentInputContext(); } switch (next_input_action->GetActionOperator()) { case OpInputAction::OPERATOR_AND: next_input_action = next_input_action->GetNextInputAction(); break; case OpInputAction::OPERATOR_OR: case OpInputAction::OPERATOR_NEXT: if (handled && next_input_action->WasReallyHandled()) { next_input_action = NULL; } else { next_input_action = next_input_action->GetNextInputAction(); handled = FALSE; if (!next_input_action) next_input_action = input_action; if (next_input_action == first_input_action) next_input_action = NULL; } break; default: next_input_action = NULL; break; } } if (update_states) { UpdateAllInputStates(); } return handled; } /*********************************************************************************** ** ** GetShortcutStringFromAction ** ***********************************************************************************/ OP_STATUS OpInputManager::GetShortcutStringFromAction(OpInputAction* action, OpString& string, OpInputContext* input_context) { if (action == NULL) { return OpStatus::ERR_NULL_POINTER; } if (input_context == NULL) { input_context = m_keyboard_input_context; } for (;input_context; input_context = input_context->GetParentInputContext()) { ShortcutContext* shortcut_context = GetShortcutContextFromActionMethodAndName(OpInputAction::METHOD_KEYBOARD, input_context->GetInputContextName()); if (!shortcut_context) { continue; } ShortcutAction* shortcut_action = shortcut_context->GetShortcutActionFromAction(action); if (shortcut_action) { INT32 shortcut_count = shortcut_action->GetShortcutCount(); for (INT32 i = 0; i < shortcut_count; i++) { Shortcut* shortcut = shortcut_action->GetShortcutByIndex(i); RETURN_IF_ERROR(shortcut->GetShortcutString(string)); if (i < shortcut_count - 1) { RETURN_IF_ERROR(string.Append(UNI_L(", "))); } } return OpStatus::OK; } } return OpStatus::OK; } /*********************************************************************************** ** ** GetTypedObject ** ***********************************************************************************/ OpTypedObject* OpInputManager::GetTypedObject(OpTypedObject::Type type, OpInputContext* input_context) { OpInputAction get_typed_object_action(OpInputAction::ACTION_GET_TYPED_OBJECT); get_typed_object_action.SetActionData(type); InvokeActionInternal(&get_typed_object_action, input_context, NULL, FALSE); return get_typed_object_action.GetActionObject(); } /*********************************************************************************** ** ** GetActionState ** ***********************************************************************************/ INT32 OpInputManager::GetActionState(OpInputAction* action, OpInputContext* first_input_context) { if (first_input_context == NULL) { first_input_context = m_keyboard_input_context; } INT32 state = 0; #ifdef QUICK if( g_application && action ) { if(g_application->KioskFilter(action)) { return action->GetActionState(); } } #endif for (;action; action = action->GetNextInputAction()) { action->SetActionState(OpInputAction::STATE_ENABLED); for (OpInputContext* input_context = first_input_context; input_context; input_context = input_context->GetParentInputContext()) { if (input_context->IsInputDisabled()) { continue; } OpInputAction get_state_action(action, OpInputAction::ACTION_GET_ACTION_STATE); get_state_action.SetFirstInputContext(first_input_context); if (input_context->OnInputAction(&get_state_action)) { state |= action->GetActionState(); break; } } if (action->GetActionOperator() != OpInputAction::OPERATOR_AND) break; } return state; } /*********************************************************************************** ** ** GetShortcutContextListFromActionMethod ** ***********************************************************************************/ ShortcutContextList* OpInputManager::GetShortcutContextListFromActionMethod(OpInputAction::ActionMethod method) { (void)method; //Yes compiler, we declare and possibly do not use this variable.. #ifdef MOUSE_SUPPORT if (method == OpInputAction::METHOD_MOUSE) return &m_mouse_shortcut_context_list; #endif // MOUSE_SUPPORT return &m_keyboard_shortcut_context_list; } /*********************************************************************************** ** ** GetShortcutContextFromActionMethodAndName ** ***********************************************************************************/ ShortcutContext* OpInputManager::GetShortcutContextFromActionMethodAndName(OpInputAction::ActionMethod method, const char* context_name) { if (!context_name) return NULL; PrefsSection* special_section = NULL; #ifdef SPECIAL_INPUT_SECTIONS if (method == OpInputAction::METHOD_KEYBOARD) { m_special_inputsections.GetData(context_name, &special_section); if(special_section) { m_special_inputsections.Remove(context_name, &special_section); } } #endif // SPECIAL_INPUT_SECTIONS return GetShortcutContextListFromActionMethod(method)->GetShortcutContextFromName(context_name, special_section); } /*********************************************************************************** ** ** AddInputState ** ***********************************************************************************/ void OpInputManager::AddInputState(OpInputState* input_state) { if (!input_state->InList()) input_state->Into(input_state->GetWantsOnlyFullUpdate() ? &m_full_update_input_states : &m_input_states); } /*********************************************************************************** ** ** RemoveInputState ** ***********************************************************************************/ void OpInputManager::RemoveInputState(OpInputState* input_state) { if (input_state->InList()) input_state->Out(); } /*********************************************************************************** ** ** UpdateAllInputStates ** ***********************************************************************************/ void OpInputManager::UpdateAllInputStates(BOOL full_update) { if (full_update) m_full_update = TRUE; if (m_update_message_pending) return; m_update_message_pending = TRUE; g_main_message_handler->PostMessage(MSG_UPDATE_ALL_INPUT_STATES, (MH_PARAM_1)this, 0); } /*********************************************************************************** ** ** SyncInputStates ** ***********************************************************************************/ void OpInputManager::SyncInputStates() { if (!m_update_message_pending) return; OpInputState* input_state = NULL; OpInputState* next_input_state = NULL; INT32 count = 0; if (m_full_update) { input_state = (OpInputState*) m_full_update_input_states.First(); while (input_state) { count++; next_input_state = (OpInputState*) input_state->Suc(); input_state->Update(m_full_update); input_state = next_input_state; } } input_state = (OpInputState*) m_input_states.First(); while (input_state) { count++; next_input_state = (OpInputState*) input_state->Suc(); input_state->Update(m_full_update); input_state = next_input_state; } m_full_update = FALSE; m_update_message_pending = FALSE; } /*********************************************************************************** ** ** HandleCallback ** ***********************************************************************************/ void OpInputManager::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if(msg == MSG_UPDATE_ALL_INPUT_STATES) { SyncInputStates(); } else if(msg == MSG_IM_ACTION_DELAY) { OpInputAction *action = (OpInputAction *)par2; if(action) { InvokeActionInternal(action); OP_DELETE(action); } } } /*********************************************************************************** ** ** GetActionFromString ** ***********************************************************************************/ OP_STATUS OpInputManager::GetActionFromString(const char* string, OpInputAction::Action* result) { while (op_isspace(*string)) { string++; } if (m_action_hashtable.GetCount() == 0) { for (INT32 i = OpInputAction::ACTION_UNKNOWN + 1; i < OpInputAction::LAST_ACTION; i++) { const char* action_string = OpInputAction::GetStringFromAction((OpInputAction::Action) i); if (action_string) RETURN_IF_MEMORY_ERROR(m_action_hashtable.Add(action_string, (OpInputAction::Action) i)); } } OpInputAction::Action action = OpInputAction::ACTION_UNKNOWN; m_action_hashtable.GetAction(string, &action); *result = action; return OpStatus::OK; } OP_STATUS OpInputManager::OpStringToActionHashTable::GetAction(const char* key, OpInputAction::Action* action) { HashItem item; RETURN_IF_ERROR(OpGenericString8HashTable::GetData(key, &item.value)); *action = item.action; return OpStatus::OK; } OP_STATUS OpInputManager::OpStringToActionHashTable::Add(const char* key, OpInputAction::Action action) { HashItem item; item.value = 0; item.action = action; return OpGenericString8HashTable::Add(key, item.value); }
//===-- server/multi-client-handler.hh - MultiClientHandler ----*- C++ -*-===// // // ODB Library // Author: Steven Lariau // //===----------------------------------------------------------------------===// /// /// \file /// Implementation of ClientHandler that can handle multiple client types /// //===----------------------------------------------------------------------===// #include "client-handler.hh" #include <vector> #include "../mess/db-client.hh" #include "../mess/simple-cli-client.hh" namespace odb { /// Implementation to handle multiple type of client handlers /// Create a list of client handlers and try to connect to a client with all /// As soon as one the handler establish a connection, it becomes the main one, /// and all others are dropped class MultiClientHandler : public ClientHandler { public: MultiClientHandler(Debugger &db, const ServerConfig &conf); /// Shortcut for ServerApp to avoid waiting for clients if they are no /// handlers bool empty() const { return _wait.empty() && _main.get() == nullptr; }; void setup_connection() override; void run_command() override; void check_stopped() override; private: std::vector<std::unique_ptr<ClientHandler>> _wait; std::unique_ptr<ClientHandler> _main; }; } // namespace odb
#include <iostream> #include <vector> #define print_vector(v)\ std::cout << "size = " << v.size() << std::endl\ << "capacity = " << v.capacity() << std::endl int main() { std::vector<int> v; print_vector(v); v.resize(100); print_vector(v); }
#ifndef DEVICESEARCHWINDOW_H #define DEVICESEARCHWINDOW_H #include <QDialog> #include <QTimer> #include <QString> #include <iostream> #include <QMutex> #include <QCloseEvent> #include <QThread> extern std::vector<QString> device_search_ips; extern QMutex device_search_ips_mutex; extern void log(std::string log_msg); namespace Ui { class DeviceSearchWindow; } /* DEVICESEARCHWINDOW Dialogo que, al abrirse, muestra una lista de los dispositivos onvif que son encontrados por el devicesearcher Se debe utilizar el devicesearcher antes de abrir el dialogo, para que actualice la lista global de ips encontradas */ class DeviceSearchWindow : public QDialog { Q_OBJECT #ifdef __unix__ public: explicit DeviceSearchWindow(QWidget *parent = 0); ~DeviceSearchWindow(); private slots: void updateList(); void on_accept_clicked(); void closeEvent(QCloseEvent *event); private: Ui::DeviceSearchWindow *ui; QTimer update_list_timer_; #endif }; #endif // DEVICESEARCHWINDOW_H
#include "Bone_Animation.h" Bone_Animation::Bone_Animation() { } Bone_Animation::~Bone_Animation() { } void Bone_Animation::init() { root_position = { 2.0f,1.0f,2.0f }; // // target_position = { 3.0f, 8.0f, 3.0f }; roottop_position = { 2.0f, 1.5f, 2.0f }; roottop_upp_trans = { 0.0f, 2.0f, 0.0f }; roottop_upptop_trans = { 0.0f, 4.0f, 0.0f }; upptop_mid_trans = { 0.0f, 1.5f, 0.0f }; upptop_midtop_trans = { 0.0f, 3.0f, 0.0f }; midtop_bot_trans = { 0.0f, 1.0f, 0.0f }; midtop_bottop_trans = { 0.0f, 2.0f, 0.0f }; target_point = glm::vec4(target_position, 1.0f); upp_end_point = glm::vec4(glm::vec3(0.0f),1.0f); upp_transformed = glm::vec4(glm::vec3(0.0f),1.0f); mid_end_point = glm::vec4(glm::vec3(0.0f),1.0f); mid_transformed = glm::vec4(glm::vec3(0.0f),1.0f); bot_end_point = glm::vec4(glm::vec3(0.0f),1.0f); bot_transformed = glm::vec4(glm::vec3(0.0f),1.0f); upp_bone_obj_mat = glm::mat4(1.0f); mid_bone_obj_mat = glm::mat4(1.0f); bot_bone_obj_mat = glm::mat4(1.0f); scale_vector = { {1.0f,1.0f,1.0f}, {0.5f,4.0f,0.5f}, {0.5f,3.0f,0.5f}, {0.5f,2.0f,0.5f} }; rotation_degree_vector = { {0.0f,0.0f,0.0f}, {0.0f,0.0f,0.0f}, {0.0f,0.0f,0.0f}, {0.0f,0.0f,0.0f} }; colors = { {0.7f,0.0f,0.0f,1.0f}, // red {0.7f,0.7f,0.0f,1.0f}, // yellow {0.7f,0.0f,0.7f,1.0f}, // purple {0.0f,0.7f,0.7f,1.0f}, // blue {0.2f,1.0f,0.2f,1.0f} // green }; // // rotate_bones = rotation_degree_vector; } void Bone_Animation::update(float delta_time) { // // target_cube_obj_mat = glm::mat4(1.0f); target_cube_obj_mat = glm::translate(target_cube_obj_mat, target_position); upp_bone_obj_mat = glm::mat4(1.0f); mid_bone_obj_mat = glm::mat4(1.0f); bot_bone_obj_mat = glm::mat4(1.0f); upp_bone_obj_mat = glm::translate(upp_bone_obj_mat, roottop_position); mid_bone_obj_mat = glm::translate(mid_bone_obj_mat, roottop_position); bot_bone_obj_mat = glm::translate(bot_bone_obj_mat, roottop_position); // .1.2 ROTATE all three bones accord to upp_bone for (int i = 2; i >= 0; i--) // for loop rotate three bones, specific sequence of 'i' denotes y -> z -> x { upp_bone_obj_mat = glm::rotate(upp_bone_obj_mat, glm::radians(rotate_bones[1][(i+1)%3]), rotate_axis[(i+1)%3]); mid_bone_obj_mat = glm::rotate(mid_bone_obj_mat, glm::radians(rotate_bones[1][(i+1)%3]), rotate_axis[(i+1)%3]); bot_bone_obj_mat = glm::rotate(bot_bone_obj_mat, glm::radians(rotate_bones[1][(i+1)%3]), rotate_axis[(i+1)%3]); } // .1.3 TRANS first bone to correct pos upp_bone_obj_mat = glm::translate(upp_bone_obj_mat, roottop_upp_trans); // .2.1 TRANS last two bones to the second joint mid_bone_obj_mat = glm::translate(mid_bone_obj_mat, roottop_upptop_trans); bot_bone_obj_mat = glm::translate(bot_bone_obj_mat, roottop_upptop_trans); // .2.2 ROTATE last two bones accord to mid_bone for (int i = 2; i >= 0; i--) // for loop rotate two bones, specific sequence of 'i' denotes y -> z -> x { mid_bone_obj_mat = glm::rotate(mid_bone_obj_mat, glm::radians(rotate_bones[2][(i+1)%3]), rotate_axis[(i+1)%3]); bot_bone_obj_mat = glm::rotate(bot_bone_obj_mat, glm::radians(rotate_bones[2][(i+1)%3]), rotate_axis[(i+1)%3]); } // .2.3 TRANS second bone to correct pos mid_bone_obj_mat = glm::translate(mid_bone_obj_mat, upptop_mid_trans); // .3.1 TRANS final bone to the third joint bot_bone_obj_mat = glm::translate(bot_bone_obj_mat, upptop_midtop_trans); // .3.2 ROTATE final bone accord to bot_bone for (int i = 2; i >= 0; i--) // for loop rotate last bone, specific sequence of 'i' denotes y -> z -> x { bot_bone_obj_mat = glm::rotate(bot_bone_obj_mat, glm::radians(rotate_bones[3][(i+1)%3]), rotate_axis[(i+1)%3]); } // .3.3 TRANS final bone to correct pos bot_bone_obj_mat = glm::translate(bot_bone_obj_mat, midtop_bot_trans); // .3.4 caculate end_point pos for IK upp_transformed = glm::translate(upp_bone_obj_mat, roottop_upp_trans) * upp_end_point; mid_transformed = glm::translate(mid_bone_obj_mat, upptop_mid_trans) * mid_end_point; bot_transformed = glm::translate(bot_bone_obj_mat, midtop_bot_trans) * bot_end_point; // .4 SCALE three bones upp_bone_obj_mat = glm::scale(upp_bone_obj_mat, scale_vector[1]); mid_bone_obj_mat = glm::scale(mid_bone_obj_mat, scale_vector[2]); bot_bone_obj_mat = glm::scale(bot_bone_obj_mat, scale_vector[3]); // Inverse Kinematics float dist = pow((bot_transformed[0]-target_position[0]),2) + pow((bot_transformed[1]-target_position[1]),2) + pow((bot_transformed[2]-target_position[2]),2); // std::cout << dist << std::endl; float threshold = pow(10, -6); if (bone_move == true && dist > threshold) { // std::cout << "to far." << std::endl; // .1 Calculate the Jacobian Matric 'jac' glm::vec3 upp_joint_pos = roottop_position; glm::vec3 mid_joint_pos = {upp_transformed.x, upp_transformed.y, upp_transformed.z}; glm::vec3 bot_joint_pos = {mid_transformed.x, mid_transformed.y, mid_transformed.z}; glm::vec3 end_effector = {bot_transformed.x, bot_transformed.y, bot_transformed.z}; glm::vec3 goal_pos = target_position; // upp glm::vec3 axis_upp = glm::cross(end_effector - upp_joint_pos, goal_pos - upp_joint_pos); // axis of upper joint axis_upp = glm::normalize(axis_upp); glm::vec3 d_upp = glm::cross(axis_upp, end_effector - upp_joint_pos); // mid glm::vec3 axis_mid = glm::cross(end_effector - mid_joint_pos, goal_pos - mid_joint_pos); axis_mid = glm::normalize(axis_mid); glm::vec3 d_mid = glm::cross(axis_mid, end_effector - mid_joint_pos); // bot glm::vec3 axis_bot = glm::cross(end_effector - bot_joint_pos, goal_pos - bot_joint_pos); axis_bot = glm::normalize(axis_bot); glm::vec3 d_bot = glm::cross(axis_bot, end_effector - bot_joint_pos); // 3 1-DOF glm::vec4 axis_upp_x = glm::transpose(glm::translate(upp_bone_obj_mat, -roottop_upp_trans))[0]; glm::vec4 axis_upp_y = glm::transpose(glm::translate(upp_bone_obj_mat, -roottop_upp_trans))[1]; glm::vec4 axis_upp_z = glm::transpose(glm::translate(upp_bone_obj_mat, -roottop_upp_trans))[2]; glm::vec4 axis_mid_x = glm::transpose(glm::translate(mid_bone_obj_mat, -upptop_mid_trans))[0]; glm::vec4 axis_mid_y = glm::transpose(glm::translate(mid_bone_obj_mat, -upptop_mid_trans))[1]; glm::vec4 axis_mid_z = glm::transpose(glm::translate(mid_bone_obj_mat, -upptop_mid_trans))[2]; glm::vec4 axis_bot_x = glm::transpose(glm::translate(bot_bone_obj_mat, -midtop_bot_trans))[0]; glm::vec4 axis_bot_y = glm::transpose(glm::translate(bot_bone_obj_mat, -midtop_bot_trans))[1]; glm::vec4 axis_bot_z = glm::transpose(glm::translate(bot_bone_obj_mat, -midtop_bot_trans))[2]; glm::vec3 d_upp_x = glm::cross({axis_upp_x[0], axis_upp_x[1], axis_upp_x[2]}, (end_effector - upp_joint_pos)); glm::vec3 d_mid_x = glm::cross({axis_mid_x[0], axis_mid_x[1], axis_mid_x[2]}, (end_effector - mid_joint_pos)); glm::vec3 d_bot_x = glm::cross({axis_bot_x[0], axis_bot_x[1], axis_bot_x[2]}, (end_effector - bot_joint_pos)); glm::vec3 d_upp_y = glm::cross({axis_upp_y[0], axis_upp_y[1], axis_upp_y[2]}, (end_effector - upp_joint_pos)); glm::vec3 d_mid_y = glm::cross({axis_mid_y[0], axis_mid_y[1], axis_mid_y[2]}, (end_effector - mid_joint_pos)); glm::vec3 d_bot_y = glm::cross({axis_bot_y[0], axis_bot_y[1], axis_bot_y[2]}, (end_effector - bot_joint_pos)); glm::vec3 d_upp_z = glm::cross({axis_upp_z[0], axis_upp_z[1], axis_upp_z[2]}, (end_effector - upp_joint_pos)); glm::vec3 d_mid_z = glm::cross({axis_mid_z[0], axis_mid_z[1], axis_mid_z[2]}, (end_effector - mid_joint_pos)); glm::vec3 d_bot_z = glm::cross({axis_bot_z[0], axis_bot_z[1], axis_bot_z[2]}, (end_effector - bot_joint_pos)); // Jacobian glm::mat3 jac = {d_upp, d_mid, d_bot}; jac = glm::transpose(jac); glm::mat3 jac_t = glm::transpose(jac); glm::mat3 jac_axis_upp = {d_upp_x, d_upp_y, d_upp_z}; glm::mat3 jac_axis_mid = {d_mid_x, d_mid_y, d_mid_z}; glm::mat3 jac_axis_bot = {d_bot_x, d_bot_y, d_bot_z}; jac_axis_upp = glm::transpose(jac_axis_upp); jac_axis_mid = glm::transpose(jac_axis_mid); jac_axis_bot = glm::transpose(jac_axis_bot); glm::mat3 jac_axis_upp_t = glm::transpose(jac_axis_upp); glm::mat3 jac_axis_mid_t = glm::transpose(jac_axis_mid); glm::mat3 jac_axis_bot_t = glm::transpose(jac_axis_bot); // .2 Calculate the step size float step_size; step_size = glm::pow(glm::length(jac_t * (target_position - end_effector)), 2) / glm::pow(glm::length(jac * jac_t * (target_position - end_effector)), 2); float step_size_upp; float step_size_mid; float step_size_bot; step_size_upp = glm::pow(glm::length(jac_axis_upp_t * (target_position - end_effector)), 2) / glm::pow(glm::length(jac_axis_upp * jac_axis_upp_t * (target_position - end_effector)), 2); step_size_mid = glm::pow(glm::length(jac_axis_mid_t * (target_position - end_effector)), 2) / glm::pow(glm::length(jac_axis_mid * jac_axis_mid_t * (target_position - end_effector)), 2); step_size_bot = glm::pow(glm::length(jac_axis_bot_t * (target_position - end_effector)), 2) / glm::pow(glm::length(jac_axis_bot * jac_axis_bot_t * (target_position - end_effector)), 2); glm::vec3 delta_e = goal_pos - end_effector; glm::vec3 change_res_upp = step_size_upp * jac_axis_upp_t * delta_e; glm::vec3 change_res_mid = step_size_mid * jac_axis_mid_t * delta_e; glm::vec3 change_res_bot = step_size_bot * jac_axis_bot_t * delta_e; std::cout << "Node change_res:" << std::endl; std::cout << "upp.x: " << change_res_upp[0] << " mid.x: " << change_res_mid[0] << " bot.x: " << change_res_bot[0] << std::endl; std::cout << "upp.y: " << change_res_upp[1] << " mid.y: " << change_res_mid[1] << " bot.y: " << change_res_bot[1] << std::endl; std::cout << "upp.z: " << change_res_upp[2] << " mid.z: " << change_res_mid[2] << " bot.z: " << change_res_bot[2] << std::endl; std::cout << std::endl << std::endl; // .3 Update 9 DOF bone values using the Transpose of 'jac' and step size; glm::mat3 change_res = step_size * jac_t; // std::cout << "Node change_res:" << std::endl; // std::cout << "[0][0]: " << change_res[0][0] << " [0][1]: " << change_res[0][1] << " [0][2]: " << change_res[0][2] << std::endl; // std::cout << "[1][0]: " << change_res[1][0] << " [1][1]: " << change_res[1][1] << " [1][2]: " << change_res[1][2] << std::endl; // std::cout << "[2][0]: " << change_res[2][0] << " [2][1]: " << change_res[2][1] << " [2][2]: " << change_res[2][2] << std::endl; // std::cout << std::endl << std::endl; glm::mat3 change_res_t = glm::transpose(change_res); // glm::vec3 degree_change_axis_upp; // glm::vec3 degree_change_axis_mid; // glm::vec3 degree_change_axis_bot; glm::mat3 degree_change_axis; float frac_top, frac_bot; glm::vec2 va,vb; // upp for (int j = 0; j < 3; j++) { // j : 0 , 1 , 2 => joint: upp , mid , bot for (int i = 0; i < 3 ; i++) { // i: 0 , 1 , 2 => axis: z , x , y va = {mid_joint_pos[i]-upp_joint_pos[i], mid_joint_pos[(i+1)%3]-upp_joint_pos[(i+1)%3]}; vb = {mid_joint_pos[i]-upp_joint_pos[i]+change_res_t[0][i], mid_joint_pos[(i+1)%3]-upp_joint_pos[(i+1)%3]+change_res_t[0][(i+1)%3]}; frac_top = va[0] * vb[0] + va[1] * vb[1]; frac_bot = glm::length(va) * glm::length(vb); degree_change_axis[j][(i+2)%3] = glm::acos(frac_top/frac_bot); } } // std::cout << "Node change_deg:" << std::endl; // std::cout << "[0][0]: " << degree_change_axis[0][0] << " [0][1]: " << degree_change_axis[0][1] << " [0][2]: " << degree_change_axis[0][2] << std::endl; // std::cout << "[1][0]: " << degree_change_axis[1][0] << " [1][1]: " << degree_change_axis[1][1] << " [1][2]: " << degree_change_axis[1][2] << std::endl; // std::cout << "[2][0]: " << degree_change_axis[2][0] << " [2][1]: " << degree_change_axis[2][1] << " [2][2]: " << degree_change_axis[2][2] << std::endl; // std::cout << std::endl << std::endl; // degree_change_axis = glm::transpose(degree_change_axis); // .4 Update the end effector position , to 'rotat_bones' std::vector<glm::vec3> rotate_bones_IK = {{0.0f,0.0f,0.0f}, change_res_upp, change_res_mid, change_res_bot}; // rotate_bones[1] += rotate_bones_IK[1]; // rotate_bones[2] += rotate_bones_IK[2]; // rotate_bones[3] += rotate_bones_IK[3]; // rotate_bones[1] += degree_change_axis[0]; // rotate_bones[2] += degree_change_axis[1]; // rotate_bones[3] += degree_change_axis[2]; } } void Bone_Animation::reset() { // // rotate_bones = rotation_degree_vector; }
#include "Socket.hpp" namespace net { Socket::Socket(int socket) { this->m_socket = socket; } Socket::Socket(const NetAddress &address) { m_socket = socket(address.family(), SOCK_STREAM, IPPROTO_TCP); if(m_socket == -1) throw Exception(__PRETTY_FUNCTION__, "Failed to create socket handle, error: " + std::string(strerror(errno))); int result; if(address.family() == AF_INET) result = connect(m_socket, address.sockaddr_ptr(), sizeof(address.get_sockaddr_ipv4())); else result = connect(m_socket, address.sockaddr_ptr(), sizeof(address.get_sockaddr_ipv6())); if(result == -1) throw Exception(__PRETTY_FUNCTION__, "Failed to connect to the host, error: " + std::string(strerror(errno))); } Socket::Socket(const std::string &ip, int port) : Socket(NetAddress(ip, port)) { } Socket::~Socket() { close(m_socket); } void Socket::send(const std::string &s) { ::send(m_socket, s.c_str(), s.length(), 0); } void Socket::send(const char *data, size_t length) { ::send(m_socket, data, length, 0); } std::string Socket::receive() { //block (infinite) untill there is data. struct pollfd pfd{m_socket, POLLIN, 0}; int err = poll(&pfd, 1, -1); if(err == -1) throw Exception(__PRETTY_FUNCTION__, "Error while waiting for POLLIN event, error: " + std::string(strerror(errno))); //determine how much data is available. int available; ioctl(m_socket, FIONREAD, &available); //read data and push it into the string char buf[available+1]; ::recv(m_socket, buf, available, 0); buf[available] = '\0'; return std::string(buf); } int Socket::receive(char *data, size_t buffersize) { return ::recv(m_socket, data, buffersize, 0); } NetAddress Socket::local_address() const { sockaddr_in6 sin; socklen_t size = sizeof(sin); getsockname(m_socket, (struct sockaddr*)&sin, &size); if(sin.sin6_family == AF_INET) return NetAddress(*(sockaddr_in *)&sin); else return NetAddress(sin); } NetAddress Socket::remote_address() const { sockaddr_in6 sin; socklen_t size = sizeof(sin); getpeername(m_socket, (struct sockaddr*)&sin, &size); if(sin.sin6_family == AF_INET) return NetAddress(*(sockaddr_in *)&sin); else return NetAddress(sin); } std::string Socket::to_string() const { std::string s = "Socket:\n"; s += "Local: " + local_address().to_string() + "\n"; s += "Remote: " + remote_address().to_string(); return s; } }
#ifndef __STDNORMAL_TEST_H__ #define __STDNORMAL_TEST_H__ #include <vector> #include "../../Point2D.h" void testStdNormal(const std::vector<Point2D>& pts, float exp_mean[2], float exp_std[2]); #endif
#include "maneuvers/trajectoryPublisher.h" int main(int argc, char **argv) { ros::init(argc, argv, "trajectory_generator"); ros::NodeHandle nh(""); trajectoryPublisher referencePublisher(nh); ros::spin(); return 0; }
#include <iostream> #include "base/config/config.h" #include "base/util/file.h" #include "base/util/runfiles_db.h" #include "tile/codegen/driver.h" #include "tile/lang/gen_stripe.h" #include "tile/lib/lib.h" #include "tile/stripe/stripe.h" #include "tile/targets/cpu/jit.h" template <typename F> void with_profile(F f) { auto start = std::chrono::high_resolution_clock::now(); f(); auto d = std::chrono::high_resolution_clock::now() - start; std::cout << "Execution took: " << std::chrono::duration<double>(d).count() * 1000 << "ms" << std::endl; } int main(int argc, char* argv[]) { START_EASYLOGGINGPP(argc, argv); el::Loggers::setVerboseLevel(2); using namespace vertexai::tile; // NOLINT std::cout << "Hey!" << std::endl; // Express auto in1 = SimpleShape(DataType::FLOAT32, {1024, 1024}); auto in2 = SimpleShape(DataType::FLOAT32, {1024, 1024}); auto runinfo = lib::LoadMatMul("test", in1, in2); auto program = lang::GenerateStripe(runinfo); std::cout << *program->entry << std::endl; // static vertexai::RunfilesDB runfiles_db{"com_intel_plaidml"}; // std::string cfg_file = runfiles_db["tile/cpu/cpu.json"]; std::string cfg_file = "external/com_intel_plaidml/tile/cpu/cpu.json"; auto cfg = vertexai::ParseConfig<codegen::proto::Config>(vertexai::ReadFile(cfg_file)); codegen::OptimizeOptions options; options.dump_passes = true; options.dbg_dir = "/tmp/stripe_cpu/passes"; codegen::Optimize(program->entry.get(), cfg.passes(), options); std::cout << "============================================================\n" << *program->entry << std::endl; // Run std::vector<float> a_data(1024 * 1024); std::vector<float> b_data(1024 * 1024); std::vector<float> c_data(1024 * 1024); a_data[0] = 1.f; b_data[0] = 1.f; std::map<std::string, void*> io; io["A"] = a_data.data(); io["B"] = b_data.data(); io["C"] = c_data.data(); targets::cpu::Native native; native.compile(*program->entry); for (int i = 0; i < 10; i++) { for (auto& f : c_data) { f = 0.f; } with_profile([&]() { // native.run(io); }); } std::cout << c_data[0] << std::endl; return 0; }
#include <iberbar/RHI/OpenGL/Device.h> #include <iberbar/RHI/OpenGL/Buffer.h> #include <iberbar/RHI/OpenGL/CommandContext.h> #include <iberbar/RHI/OpenGL/ShaderProgram.h> #include <iberbar/RHI/OpenGL/ShaderState.h> #include <iberbar/RHI/OpenGL/ShaderVariables.h> #include <iberbar/RHI/OpenGL/VertexDeclaration.h> #include <iberbar/RHI/OpenGL/Texture.h> #include <iberbar/RHI/OpenGL/Types.h> iberbar::RHI::OpenGL::CDevice::CDevice() : IDevice( UApiType::OpenGL ) , m_bHasLostDevice( false ) #ifdef _WINDOWS , m_hWnd( nullptr ) , m_hDC( nullptr ) , m_hRC( nullptr ) #endif , m_ArrayBufferBound( 0 ) , m_ElementArrayBufferBound( 0 ) , m_SamplerStateList() { memset( m_SamplerStateList, 0, sizeof( m_SamplerStateList ) ); } iberbar::RHI::OpenGL::CDevice::~CDevice() { glDeleteSamplers( 8, m_SamplerStateList ); memset( m_SamplerStateList, 0, sizeof( m_SamplerStateList ) ); #ifdef _WIN32 if ( m_hRC ) { ::wglMakeCurrent( NULL, NULL ); ::wglDeleteContext( m_hRC ); } if ( m_hDC ) ::ReleaseDC( m_hWnd, m_hDC ); #endif } #ifdef _WIN32 iberbar::CResult iberbar::RHI::OpenGL::CDevice::CreateDevice( HWND hWnd, bool bWindowed /* = true */, int nSuitedWidth /* = 0 */, int nSuitedHeight /* = 0 */ ) { assert( m_hWnd == NULL ); if ( hWnd == NULL ) return CResult( ResultCode::Bad, "" ); m_hWnd = hWnd; GLuint PixelFormat; PIXELFORMATDESCRIPTOR lc_PixelFormat = { sizeof( PIXELFORMATDESCRIPTOR ), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 24, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 32, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; m_hDC = ::GetDC( hWnd ); if ( m_hDC == NULL ) { return CResult( ResultCode::Bad, "" ); } PixelFormat = ::ChoosePixelFormat( m_hDC, &lc_PixelFormat ); if ( PixelFormat == 0 ) // Did Windows Find A Matching Pixel Format? { return CResult( ResultCode::Bad, "" ); // Return FALSE } if ( !SetPixelFormat( m_hDC, PixelFormat, &lc_PixelFormat ) ) // Are We Able To Set The Pixel Format? { return CResult( ResultCode::Bad, "" ); } if ( !( m_hRC=wglCreateContext( m_hDC ) ) ) // Are We Able To Get A Rendering Context? { return CResult( ResultCode::Bad, "" ); } if ( !wglMakeCurrent( m_hDC, m_hRC ) ) // Try To Activate The Rendering Context { return CResult( ResultCode::Bad, "" ); } glDisable( GL_POINT_SMOOTH ); glDisable( GL_LINE_SMOOTH ); glDisable( GL_POLYGON_SMOOTH ); //glEnable( GL_POINT_SMOOTH ); //glEnable( GL_LINE_SMOOTH ); //glEnable( GL_POLYGON_SMOOTH ); // glHint( GL_POINT_SMOOTH_HINT, GL_NICEST ); // Make round points, not square points // glHint( GL_LINE_SMOOTH_HINT, GL_NICEST ); // Antialias the lines // glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST ); //glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); glEnable( GL_DEPTH ); glEnable( GL_BLEND ); glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_ALPHA_TEST ); /*glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_MULTISAMPLE);*/ //glEnable(GL_MULTISAMPLE); //glEnable( GL_SAMPLE_ALPHA_TO_ONE ); glewInit(); m_ContextSize = CSize2i( nSuitedWidth, nSuitedHeight ); glViewport( 0, 0, m_ContextSize.w, m_ContextSize.h ); // Reset The Current Viewport // glMatrixMode( GL_PROJECTION ); // Select The Projection Matrix // glLoadIdentity(); // Reset The Projection Matrix // gluPerspective( 90.0f, (GLfloat)m_GLSize.cx/(GLfloat)m_GLSize.cy, 1.0f, 1000.0f ); // // glMatrixMode( GL_MODELVIEW ); // glLoadIdentity(); if ( m_CallbackCreated ) { CResult ret = m_CallbackCreated( this ); if ( ret.IsOK() == false ) return ret; } return CResult(); } #else iberbar::CResult iberbar::RHI::OpenGL::CDevice::CreateDevice( int nSuitedWidth, int nSuitedHeight ) { m_ContextSize = CSize2i( nSuitedWidth, nSuitedHeight ); glViewport( 0, 0, m_ContextSize.w, m_ContextSize.h ); if ( m_CallbackCreated ) { CResult ret = m_CallbackCreated( this ); if ( ret.IsOK() == false ) return ret; } return CResult(); } #endif void iberbar::RHI::OpenGL::CDevice::LostDevice() { m_bHasLostDevice = true; if ( m_CallbackLost ) { m_CallbackLost( this ); } } iberbar::CResult iberbar::RHI::OpenGL::CDevice::ResetDevice( int nBackBufferWidth, int nBackBufferHeight, bool bIsWindow ) { //assert( m_bHasLostDevice == true ); if ( nBackBufferHeight == 0 ) { nBackBufferHeight = 1; } glViewport( 0, 0, nBackBufferWidth, nBackBufferHeight ); m_ContextSize = CSize2i( nBackBufferWidth, nBackBufferHeight ); if ( m_CallbackReset ) { CResult ret = m_CallbackReset( this ); if ( ret.IsOK() == false ) return ret; } m_bHasLostDevice = false; return CResult(); } void iberbar::RHI::OpenGL::CDevice::CreateTexture( ITexture** ppOutTexture ) { assert( ppOutTexture ); TSmartRefPtr<CTexture> pTexture = TSmartRefPtr<CTexture>::_sNew(); UNKNOWN_SAFE_RELEASE_NULL( *ppOutTexture ); (*ppOutTexture) = pTexture; (*ppOutTexture)->AddRef(); } iberbar::CResult iberbar::RHI::OpenGL::CDevice::CreateVertexBuffer( uint32 nInSize, uint32 nUsage, IVertexBuffer** ppOutBuffer ) { assert( ppOutBuffer ); TSmartRefPtr<CVertexBuffer> pVertexBuffer = TSmartRefPtr<CVertexBuffer>::_sNew( this, nInSize, nUsage ); pVertexBuffer->Initial(); UNKNOWN_SAFE_RELEASE_NULL( *ppOutBuffer ); (*ppOutBuffer) = pVertexBuffer; (*ppOutBuffer)->AddRef(); return CResult(); } iberbar::CResult iberbar::RHI::OpenGL::CDevice::CreateIndexBuffer( uint32 nStride, uint32 nInSize, uint32 nUsage, IIndexBuffer** ppOutBuffer ) { assert( ppOutBuffer ); TSmartRefPtr<CIndexBuffer> pNewBuffer = TSmartRefPtr<CIndexBuffer>::_sNew( this, nStride, nInSize, nUsage ); pNewBuffer->Initial(); UNKNOWN_SAFE_RELEASE_NULL( *ppOutBuffer ); (*ppOutBuffer) = pNewBuffer; (*ppOutBuffer)->AddRef(); return CResult(); } iberbar::CResult iberbar::RHI::OpenGL::CDevice::CreateShader( IShader** ppOutShader ) { assert( ppOutShader ); TSmartRefPtr<CShaderProgram> pNewShader = TSmartRefPtr<CShaderProgram>::_sNew(); UNKNOWN_SAFE_RELEASE_NULL( *ppOutShader ); (*ppOutShader) = pNewShader; (*ppOutShader)->AddRef(); return CResult(); } iberbar::CResult iberbar::RHI::OpenGL::CDevice::CreateVertexDeclaration( IVertexDeclaration** ppOutDeclaration, const UVertexElement* pVertexElements, uint32 nVertexElementsCount, uint32 nStride ) { assert( ppOutDeclaration ); TSmartRefPtr<CVertexDeclaration> pDeclaration = TSmartRefPtr<CVertexDeclaration>::_sNew( this, pVertexElements, nVertexElementsCount, nStride ); UNKNOWN_SAFE_RELEASE_NULL( *ppOutDeclaration ); (*ppOutDeclaration) = pDeclaration; (*ppOutDeclaration)->AddRef(); return CResult(); } iberbar::CResult iberbar::RHI::OpenGL::CDevice::CreateShaderState( IShaderState** ppOutShaderState, IShader* pShader, IVertexDeclaration* pVertexDeclaration ) { assert( ppOutShaderState ); ((CVertexDeclaration*)pVertexDeclaration)->Initial( (CShaderProgram*)pShader ); TSmartRefPtr<CShaderState> pShaderState = TSmartRefPtr<CShaderState>::_sNew( this, (CShaderProgram*)pShader, (CVertexDeclaration*)pVertexDeclaration ); CResult ret = pShaderState->GenarateConstTable(); if ( ret.IsOK() == false ) return ret; UNKNOWN_SAFE_RELEASE_NULL( *ppOutShaderState ); (*ppOutShaderState) = pShaderState; (*ppOutShaderState)->AddRef(); return CResult(); } void iberbar::RHI::OpenGL::CDevice::CreateShaderVariableTable( IShaderVariableTable** ppOutShaderVarTable ) { assert( ppOutShaderVarTable ); TSmartRefPtr<CShaderVariableTable> pShaderVarTable = TSmartRefPtr<CShaderVariableTable>::_sNew(); UNKNOWN_SAFE_RELEASE_NULL( *ppOutShaderVarTable ); (*ppOutShaderVarTable) = pShaderVarTable; (*ppOutShaderVarTable)->AddRef(); } void iberbar::RHI::OpenGL::CDevice::CreateCommandContext( ICommandContext** ppOutContext ) { assert( ppOutContext ); TSmartRefPtr<CCommandContext> pNewContext = TSmartRefPtr<CCommandContext>::_sNew( this ); UNKNOWN_SAFE_RELEASE_NULL( *ppOutContext ); (*ppOutContext) = pNewContext; (*ppOutContext)->AddRef(); } iberbar::CResult iberbar::RHI::OpenGL::CDevice::Begin() { if ( m_bHasLostDevice ) { LostDevice(); CResult RetReset = ResetDevice( m_ContextSize.w, m_ContextSize.h, m_bIsWindow ); if ( RetReset.IsOK() == false ) return RetReset; m_bHasLostDevice = false; } //--------------------------------- // 清屏并初始化视觉 //--------------------------------- glClearColor( m_ClearColor.r, m_ClearColor.g, m_ClearColor.b, 1.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Clear Screen And Depth Buffer #ifdef WIN32 glEnable( GL_DEPTH ); glEnable( GL_MULTISAMPLE ); #endif return CResult(); } void iberbar::RHI::OpenGL::CDevice::End() { #ifdef WIN32 //将在后台缓冲区绘制的图形提交到前台缓冲区显示 SwapBuffers( m_hDC ); #endif } // //void iberbar::RHI::CGLesDevice::useGLProgram( CGLShaderProgram* program ) //{ // // if ( program == NULL ) // { // if ( m_pCurrentGLProgram ) // { // m_pCurrentGLProgram->release(); // m_pCurrentGLProgram = NULL; // } // // glUseProgram( 0 ); // } // else // { // assert( program->getProgram() != 0 ); // // if ( program == m_pCurrentGLProgram ) // return; // // if ( m_pCurrentGLProgram ) // m_pCurrentGLProgram->release(); // m_pCurrentGLProgram = program; // m_pCurrentGLProgram->addRef(); // // glUseProgram( m_pCurrentGLProgram->getProgram() ); // } //} // // //void iberbar::RHI::CGLesDevice::getGLProgramCurrent( CGLShaderProgram** pp ) //{ // if ( pp == nullptr ) // return ; // UNKNOWN_SAFE_RELEASE_NULL( *pp ); // ( *pp ) = m_pCurrentGLProgram; // UNKNOWN_SAFE_ADDREF( *pp ); //} // // //void iberbar::RHI::CGLesDevice::setBlendFunc( GLenum sfactor, GLenum dfactor ) //{ // if ( sfactor != m_eBlendingSource || dfactor != m_eBlendingDest ) // { // m_eBlendingSource = sfactor; // m_eBlendingDest = dfactor; // // if ( sfactor == GL_ONE && dfactor == GL_ZERO ) // { // glDisable( GL_BLEND ); // } // else // { // glEnable( GL_BLEND ); // glBlendFunc( sfactor, dfactor ); // } // } //} void iberbar::RHI::OpenGL::CDevice::SetSamplerState( uint32 nStage, const UTextureSamplerState& SamplerState ) { if ( nStage >= 8 ) return; GLuint nSamplerHandle = m_SamplerStateList[ nStage ]; #ifdef _WIN32 //glTexParameteri; //glSamplerParameteri( nSamplerHandle, GL_TEXTURE_MAG_FILTER, ConvertTextureFilterType( SamplerState.nMagFilter ) ); //glSamplerParameteri( nSamplerHandle, GL_TEXTURE_MIN_FILTER, ConvertTextureFilterType( SamplerState.nMinFilter ) ); //glSamplerParameteri( nSamplerHandle, GL_TEXTURE_WRAP_S, ConvertTextureAddress( SamplerState.nAddressU ) ); //glSamplerParameteri( nSamplerHandle, GL_TEXTURE_WRAP_T, ConvertTextureAddress( SamplerState.nAddressV ) ); #endif #ifdef __ANDROID__ glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, ConvertTextureFilterType( SamplerState.nMagFilter ) ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, ConvertTextureFilterType( SamplerState.nMinFilter ) ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, ConvertTextureAddress( SamplerState.nAddressU ) ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, ConvertTextureAddress( SamplerState.nAddressV ) ); #endif } void iberbar::RHI::OpenGL::CDevice::OnCreated() { #ifdef _WIN32 glGenSamplers( 8, m_SamplerStateList ); for ( int i = 0; i < 8; i++ ) { glBindSampler( i, m_SamplerStateList[ i ] ); } #endif }
#include "GamePch.h" #include "HealthModule.h" #include "Projectile.h" #include "Common.h" #include "../Engine/Component/ParticleEmitter.h" uint32_t Projectile::s_TypeID = hg::ComponentFactory::GetGameComponentID(); Projectile::Projectile() : m_damage(0), m_live(true) { } void Projectile::LoadFromXML(tinyxml2::XMLElement * data) { data->QueryFloatAttribute("speed", &m_speed); data->QueryFloatAttribute("life", &m_lifeTime); data->QueryFloatAttribute("damage", &m_damage); m_Bounce = false; data->QueryBoolAttribute("bounce", &m_Bounce); m_Gravity = 0.0f; data->QueryFloatAttribute("gravity", &m_Gravity); } void Projectile::Init() { } void Projectile::Start() { m_timer = 0; m_Velocity = GetEntity()->GetTransform()->Forward() * m_speed; } void Projectile::SetSpeed(const float speed) { m_speed = speed; m_Velocity = GetEntity()->GetTransform()->Forward() * speed; } void Projectile::SetLifeTime(const float life) { m_lifeTime = life; } void Projectile::AddDamage(float damage) { m_damage += damage; } void Projectile::Update() { if (m_timer >= m_lifeTime) { hg::Light* light = GetEntity()->GetComponent<hg::Light>(); if(light) light->SetEnabled(false); m_live = false; } if (m_live) { m_timer += hg::g_Time.Delta(); //assert(GetEntity()->GetComponent<hg::PrimitiveRenderer>() == nullptr); //assert(GetEntity()->GetComponent<hg::MeshRenderer>() == nullptr); SimpleMath::Vector3 pos = GetEntity()->GetTransform()->GetWorldPosition(); SimpleMath::Vector3 forward = GetEntity()->GetTransform()->Forward(); //SimpleMath::Vector3 vel = (forward * m_speed + m_VelocityY) * hg::g_Time.Delta(); SimpleMath::Vector3 end = pos + m_Velocity * hg::g_Time.Delta(); if (m_Gravity != 0.0f) m_Velocity += Vector3(0, -10, 0) * m_Gravity * hg::g_Time.Delta(); //hg::DebugRenderer::DrawLine(pos, pos + forward * 1.5f); hg::Ray ray(pos, end); hg::Entity* hit; GetEntity()->GetTransform()->Translate(end - pos); Vector3 hitPos; Vector3 surfaceNormal; if (hg::g_Physics.RayCast(ray, &hit, &hitPos, &surfaceNormal, COLLISION_BULLET_HIT_MASK)) { bool causeDamage = false; if (hit->GetComponent<Health>()) { hg::Entity* particle = hg::Entity::Assemble(SID(FX_BulletImpact_Metal)); particle->GetTransform()->SetPosition(hitPos); particle->GetTransform()->Rotate(GetEntity()->GetTransform()->GetWorldRotation()); //OutputDebugStringA(hit->GetName().c_str()); DamageMessage dmg(kDmgType_Bullet); hit->SendMsg(&dmg); causeDamage = true; } else { hg::Entity* particle = hg::Entity::Assemble(SID(FX_BulletImpact_Metal)); particle->GetTransform()->SetPosition(hitPos); particle->GetTransform()->SetRotation(GetEntity()->GetTransform()->GetWorldRotation()); } if (m_Bounce && !causeDamage) { // Bounce projectile against surface m_Velocity = Vector3::Reflect(m_Velocity, surfaceNormal); Vector3 dir = m_Velocity; dir.Normalize(); GetEntity()->GetTransform()->SetPosition(hitPos + dir * 0.01f); } else { hg::Light* light = GetEntity()->GetComponent<hg::Light>(); if (light) light->SetEnabled(false); m_live = false; } } Vector3 dir = m_Velocity; dir.Normalize(); GetEntity()->GetTransform()->LookAt(GetEntity()->GetPosition() + dir); } if (!m_live) { GetEntity()->Destroy(); return; } } void Projectile::SetBounce(bool enable) { m_Bounce = enable; } hg::IComponent * Projectile::MakeCopyDerived() const { Projectile* cpy = (Projectile*)IComponent::Create(SID(Projectile)); *cpy = *this; return cpy; }
// Created on: 1992-11-18 // Created by: Christian CAILLET // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFSelect_SelectRange_HeaderFile #define _IFSelect_SelectRange_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IFSelect_SelectExtract.hxx> #include <Standard_Integer.hxx> class IFSelect_IntParam; class Standard_Transient; class Interface_InterfaceModel; class TCollection_AsciiString; class IFSelect_SelectRange; DEFINE_STANDARD_HANDLE(IFSelect_SelectRange, IFSelect_SelectExtract) //! A SelectRange keeps or rejects a sub-set of the input set, //! that is the Entities of which rank in the iteration list //! is in a given range (for instance form 2nd to 6th, etc...) class IFSelect_SelectRange : public IFSelect_SelectExtract { public: //! Creates a SelectRange. Default is Take all the input list Standard_EXPORT IFSelect_SelectRange(); //! Sets a Range for numbers, with a lower and a upper limits //! Error if rankto is lower then rankfrom Standard_EXPORT void SetRange (const Handle(IFSelect_IntParam)& rankfrom, const Handle(IFSelect_IntParam)& rankto); //! Sets a unique number (only one Entity will be sorted as True) Standard_EXPORT void SetOne (const Handle(IFSelect_IntParam)& rank); //! Sets a Lower limit but no upper limit Standard_EXPORT void SetFrom (const Handle(IFSelect_IntParam)& rankfrom); //! Sets an Upper limit but no lower limit (equivalent to lower 1) Standard_EXPORT void SetUntil (const Handle(IFSelect_IntParam)& rankto); //! Returns True if a Lower limit is defined Standard_EXPORT Standard_Boolean HasLower() const; //! Returns Lower limit (if there is; else, value is senseless) Standard_EXPORT Handle(IFSelect_IntParam) Lower() const; //! Returns Value of Lower Limit (0 if none is defined) Standard_EXPORT Standard_Integer LowerValue() const; //! Returns True if a Lower limit is defined Standard_EXPORT Standard_Boolean HasUpper() const; //! Returns Upper limit (if there is; else, value is senseless) Standard_EXPORT Handle(IFSelect_IntParam) Upper() const; //! Returns Value of Upper Limit (0 if none is defined) Standard_EXPORT Standard_Integer UpperValue() const; //! Returns True for an Entity of which occurrence number in the //! iteration is inside the selected Range (considers <rank>) Standard_EXPORT Standard_Boolean Sort (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE; //! Returns a text defining the criterium : following cases, //! " From .. Until .." or "From .." or "Until .." or "Rank no .." Standard_EXPORT TCollection_AsciiString ExtractLabel() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IFSelect_SelectRange,IFSelect_SelectExtract) private: Handle(IFSelect_IntParam) thelower; Handle(IFSelect_IntParam) theupper; }; #endif // _IFSelect_SelectRange_HeaderFile
#include <iostream> using namespace std; using ll = long long; template <typename T> T gcd(T a, T b) { if (a < b) return gcd(b, a); return b == 0 ? a : gcd(b, a % b); } int main() { ll N, M, K; cin >> N >> M >> K; if (N * M * 2 % K != 0) { cout << "NO" << endl; return 0; } cout << "YES" << endl; ll x[3], y[3]; x[0] = y[0] = x[1] = y[2] = 0; ll g = gcd(N, K); if (g > 1) { g = gcd(N * 2, K); x[2] = N * 2 / g; y[1] = M / (K / g); } else { x[2] = N / g; y[1] = M * 2 / (K / g); } for (int i = 0; i < 3; ++i) { cout << x[i] << " " << y[i] << endl; } return 0; }
#include<netinet/in.h> #include<sys/types.h> #include<sys/socket.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<iostream> #include<arpa/inet.h> #include<unistd.h> #define SERVER_PORT 6666 #define LENGTH_OF_LISTEN_QUEUE 20 #define BUFFER_SIZE 1024 #define FILE_NAME_MAX_SIZE 512 using namespace std; int main(int argc, char **argv) { struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htons(INADDR_ANY); server_addr.sin_port = htons(SERVER_PORT); int server_socket = socket(PF_INET, SOCK_STREAM, 0); if (server_socket < 0){ cout<<"Create Socket Failed!"<<endl; exit(1); } if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr))){ printf("Server Bind Port: %d Failed!\n", SERVER_PORT); exit(1); } if (listen(server_socket, LENGTH_OF_LISTEN_QUEUE)){ cout<<"Server Listen Failed!"<<endl; exit(1); } while(1){ struct sockaddr_in client_addr; socklen_t length = sizeof(client_addr); int new_server_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length); if (new_server_socket < 0){ cout<<"Server Accept Failed!"<<endl; break; } char buffer[BUFFER_SIZE]; bzero(buffer, sizeof(buffer)); length = recv(new_server_socket, buffer, BUFFER_SIZE, 0); if (length < 0) { cout<<"Server Recieve Data Failed!"<<endl; break; } char file_name[FILE_NAME_MAX_SIZE + 1]; bzero(file_name, sizeof(file_name)); strncpy(file_name, buffer, strlen(buffer) > FILE_NAME_MAX_SIZE ? FILE_NAME_MAX_SIZE : strlen(buffer)); FILE *fp = fopen(file_name, "r"); if (fp == NULL){ printf("File:\t%s Not Found!\n", file_name); }else{ bzero(buffer, BUFFER_SIZE); int file_block_length = 0; while( (file_block_length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0){ cout<<"file_block_length ="<<file_block_length<<endl; if (send(new_server_socket, buffer, file_block_length, 0) < 0){ printf("Send File:\t%s Failed!\n", file_name); break; } bzero(buffer, sizeof(buffer)); } fclose(fp); printf("File:\t%s Transfer Finished!\n", file_name); } close(new_server_socket); } close(server_socket); return 0; }
// // Created by Yujing Shen on 28/05/2017. // #ifndef TENSORGRAPH_SESSIONNODE_H #define TENSORGRAPH_SESSIONNODE_H #include "TensorGraph.h" namespace sjtu{ class SessionNode { friend class Graph; public: SessionNode(Session *sess, const vector<int>& shape); SessionNode(const SessionNode &r); virtual ~SessionNode(); Node set_data(Tensor data); Node set_diff(Tensor diff); Tensor get_data(); Tensor get_diff(); Node set_opt(Optimizer opt); Optimizer get_opt(); Node set_name(const string &str); string get_name() const; virtual Node forward() = 0; virtual Node backward() = 0; virtual Node optimize() = 0; protected: Node link_backward(Node r); Node link_forward(Node r); Node set_first(Edge p); Edge first(); Node dec_degree(); Node rst_degree(); bool zero_degree(); protected: Session *_sess; Shape _shape; Tensor _data, _diff; Edge _f; vector<Node> _port_in; vector<Node> _port_out; int _in_degree; Optimizer _opt; string _name; }; } #endif //TENSORGRAPH_SESSIONNODE_H
#ifndef VNALINEARSWEEP_H #define VNALINEARSWEEP_H // RsaToolbox #include "Definitions.h" #include "NetworkData.h" // Qt #include <QObject> #include <QScopedPointer> namespace RsaToolbox { class Vna; class VnaChannel; class VnaLinearSweep : public QObject { Q_OBJECT public: explicit VnaLinearSweep(QObject *parent = 0); VnaLinearSweep(VnaLinearSweep &other); VnaLinearSweep(Vna *vna, VnaChannel *channel, QObject *parent = 0); VnaLinearSweep(Vna *vna, uint channelIndex, QObject *parent = 0); ~VnaLinearSweep(); uint points(); void setPoints(uint numberOfPoints); double start_Hz(); void setStart(double frequency, SiPrefix prefix = SiPrefix::None); double stop_Hz(); void setStop(double frequency, SiPrefix prefix = SiPrefix::None); double center_Hz(); void setCenter(double frequency, SiPrefix prefix = SiPrefix::None); double span_Hz(); void setSpan(double frequencyRange, SiPrefix prefix = SiPrefix::None); double spacing_Hz(); void setSpacing(double frequencySpacing, SiPrefix prefix = SiPrefix::None); QRowVector frequencies_Hz(); double power_dBm(); void setPower(double power_dBm); double ifBandwidth_Hz(); void setIfbandwidth(double bandwidth, SiPrefix prefix = SiPrefix::None); // Harmonic grids for time domain traces void createHarmonicGrid(double stopFrequency_Hz, double spacing_Hz); void createHarmonicGrid(double stopFrequency_Hz, uint points); QVector<uint> sParameterGroup(); void setSParameterGroup(QVector<uint> ports); void clearSParameterGroup(); ComplexMatrix3D readSParameterGroup(); bool isAutoSweepTimeOn(); bool isAutoSweepTimeOff(); void autoSweepTimeOn(bool isOn = true); void autoSweepTimeOff(bool isOff = true); uint sweepTime_ms(); void setSweepTime(uint time_ms); NetworkData measure(uint port1); NetworkData measure(uint port1, uint port2); NetworkData measure(uint port1, uint port2, uint port3); NetworkData measure(uint port1, uint port2, uint port3, uint port4); NetworkData measure(QVector<uint> ports); bool saveSnp(QString filePathName, uint testPort1, ComplexFormat format = ComplexFormat::RealImaginary); bool saveSnp(QString filePathName, uint testPort1, uint testPort2, ComplexFormat format = ComplexFormat::RealImaginary); bool saveSnp(QString filePathName, uint testPort1, uint testPort2, uint testPort3, ComplexFormat format = ComplexFormat::RealImaginary); bool saveSnp(QString filePathName, uint testPort1, uint testPort2, uint testPort3, uint testPort4, ComplexFormat format = ComplexFormat::RealImaginary); bool saveSnp(QString filePathName, QVector<uint> testPorts, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnp(QString filePathName, uint testPort1, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnp(QString filePathName, uint testPort1, uint testPort2, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnp(QString filePathName, uint testPort1, uint testPort2, uint testPort3, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnp(QString filePathName, uint testPort1, uint testPort2, uint testPort3, uint testPort4, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnp(QString filePathName, QVector<uint> testPorts, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnpLocally(QString filePathName, uint testPort1, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnpLocally(QString filePathName, uint testPort1, uint testPort2, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnpLocally(QString filePathName, uint testPort1, uint testPort2, uint testPort3, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnpLocally(QString filePathName, uint testPort1, uint testPort2, uint testPort3, uint testPort4, ComplexFormat format = ComplexFormat::RealImaginary); bool measureToSnpLocally(QString filePathName, QVector<uint> testPorts, ComplexFormat format = ComplexFormat::RealImaginary); void operator=(VnaLinearSweep const &other); private: Vna *_vna; QScopedPointer<Vna> placeholder; QScopedPointer<VnaChannel> _channel; uint _channelIndex; bool isFullyInitialized() const; static uint frequencyBufferSize(uint points); static uint dataBufferSize(uint ports, uint points); QString toScpi(ComplexFormat format); }; } #endif // VnaLinearSweep_H
#include "treeface/base/PackageManager.h" #include "treeface/misc/Errors.h" #include <treecore/File.h> #include <treecore/HashMap.h> #include <treecore/HashSet.h> #include <treecore/RefCountHolder.h> #include <treecore/InputStream.h> #include <treecore/JSON.h> #include <treecore/MemoryBlock.h> #include <treecore/MemoryInputStream.h> #include <treecore/Result.h> #include <treecore/StringRef.h> #include <treecore/ZipFile.h> using namespace treecore; namespace treeface { struct PackageEntryPoint { treecore::ZipFile* package; int entry_index; treecore::Time time; }; struct PackageManager::Impl { treecore::HashSet<RefCountHolder<ZipFile> > m_packages; treecore::HashMap<treecore::Identifier, PackageEntryPoint> m_name_pkg_map; }; void PackageManager::add_package( treecore::ZipFile* pkg, PackageItemConflictPolicy pol ) { if ( !m_impl->m_packages.insert( pkg ) ) return; printf( "add package %p, has %d entries\n", pkg, pkg->getNumEntries() ); for (int index = 0; index < pkg->getNumEntries(); index++) { const ZipFile::ZipEntry* entry = pkg->getEntry( index ); printf( " entry %s\n", entry->filename.toRawUTF8() ); if ( m_impl->m_name_pkg_map.contains( entry->filename ) ) { switch (pol) { case KEEP_EXISTING: break; case OVERWRITE: m_impl->m_name_pkg_map.set( entry->filename, { pkg, index, entry->fileTime } ); break; case USE_OLDER: if (entry->fileTime < m_impl->m_name_pkg_map[entry->filename].time) m_impl->m_name_pkg_map.set( entry->filename, { pkg, index, entry->fileTime } ); break; case USE_NEWER: if (m_impl->m_name_pkg_map[entry->filename].time < entry->fileTime) m_impl->m_name_pkg_map.set( entry->filename, { pkg, index, entry->fileTime } ); break; default: abort(); } } else { m_impl->m_name_pkg_map.set( entry->filename, { pkg, index, entry->fileTime } ); } } } void PackageManager::add_package( const void* zip_data, size_t zip_data_size, PackageItemConflictPolicy pol ) { MemoryInputStream* mem_stream = new MemoryInputStream( zip_data, zip_data_size, false ); ZipFile* pkg = new ZipFile( mem_stream, true ); add_package( pkg, pol ); } void PackageManager::add_package( const treecore::File& zip_file, PackageItemConflictPolicy pol ) { ZipFile* pkg = new ZipFile( zip_file ); add_package( pkg, pol ); } treecore::InputStream* PackageManager::get_item_stream( const treecore::Identifier& name ) { if ( m_impl->m_name_pkg_map.contains( name ) ) { PackageEntryPoint entry = m_impl->m_name_pkg_map[name]; return entry.package->createStreamForEntry( entry.entry_index ); } else { return nullptr; } } bool PackageManager::get_item_data( const treecore::Identifier& name, treecore::MemoryBlock& data, bool append_zero ) { InputStream* stream = get_item_stream( name ); if (!stream) return false; size_t size = stream->getTotalLength(); if (append_zero) data.ensureSize( size + 1, false ); else data.ensureSize( size, false ); int size_got = stream->read( data.getData(), int32( size ) ); if (size_got != size) die( "PackageManager item %s size %lu bytes, but only got %d bytes", name.getPtr(), size, size_got ); // assign a zero on tail of data, so that it can be directly used as C string if (append_zero) data[size] = 0; delete stream; return true; } treecore::var PackageManager::get_item_json( const treecore::Identifier& name ) { // load JSON string data treecore::MemoryBlock json_src; if ( !get_item_data( name, json_src, true ) ) return treecore::var::null; // parse JSON var root_node; { Result json_re = JSON::parse( (char*) json_src.getData(), root_node ); if (!json_re) throw ConfigParseError( "PackageManager: failed to parse JSON content:\n" + json_re.getErrorMessage() + "\n\n" + String( "==== JSON source ====\n\n" ) + String( (char*) json_src.getData() ) + "\n" + String( "==== end of JSON source ====\n" ) ); } return root_node; } bool PackageManager::has_resource( const treecore::Identifier& name ) const noexcept { return m_impl->m_name_pkg_map.contains( name ); } PackageManager::PackageManager(): m_impl( new Impl() ) {} PackageManager::~PackageManager() { if (m_impl) delete m_impl; } } // namespace treeface
#pragma once #include <boost/container/deque.hpp> #include <boost/container/options.hpp> #include <boost/container/small_vector.hpp> #include <boost/container/static_vector.hpp> template <typename I, size_t N> using SmallVector = boost::container::small_vector<I, N>; template <typename I, size_t N> using StaticVector = boost::container::static_vector<I, N>; // Boost deque container with default block size N. (REQUIRES LATEST BOOST). template <typename I, size_t N = 128> using Deque = boost::container::deque<I, void, typename boost::container::deque_options< boost::container::block_size<N>>::type>;
// includes system #include <algorithm> #include <iomanip> #include <fstream> #include <cmath> // includes project #include "file_util.h" #include "tools.h" #include "util.h" #include "red_type.h" #include "red_macro.h" #include "red_constants.h" using namespace std; using namespace pp_disk_t; namespace redutilcu { static sim_data* create_sim_data() { sim_data_t *sim_data = new sim_data_t; allocate_host_storage(sim_data, 4); // Populate 0. body's x metadata sim_data->h_body_md[0].id = 1; sim_data->h_body_md[0].body_type = BODY_TYPE_STAR; sim_data->h_body_md[0].mig_type = MIGRATION_TYPE_NO; sim_data->h_body_md[0].mig_stop_at = 0.0; // Populate 1. body's x metadata sim_data->h_body_md[1].id = 1; sim_data->h_body_md[1].body_type = BODY_TYPE_GIANTPLANET; sim_data->h_body_md[1].mig_type = MIGRATION_TYPE_NO; sim_data->h_body_md[1].mig_stop_at = 0.0; // Populate 2. body's x metadata sim_data->h_body_md[2].id = 2; sim_data->h_body_md[2].body_type = BODY_TYPE_GIANTPLANET; sim_data->h_body_md[2].mig_type = MIGRATION_TYPE_NO; sim_data->h_body_md[2].mig_stop_at = 0.0; // Populate 3. body's x metadata sim_data->h_body_md[3].id = 3; sim_data->h_body_md[3].body_type = BODY_TYPE_PROTOPLANET; sim_data->h_body_md[3].mig_type = MIGRATION_TYPE_NO; sim_data->h_body_md[3].mig_stop_at = 0.0; // Populate 0. body's x coordinate sim_data->h_y[0][0].x = 0.0; sim_data->h_y[0][0].y = 0.0; sim_data->h_y[0][0].z = 0.0; sim_data->h_y[0][0].w = 0.0; // Populate 1. body's x coordinate sim_data->h_y[0][1].x = 1.0; sim_data->h_y[0][1].y = 0.0; sim_data->h_y[0][1].z = 0.0; sim_data->h_y[0][1].w = 0.0; // Populate 2. body's x coordinate sim_data->h_y[0][2].x = 1.0; sim_data->h_y[0][2].y = 1.0; sim_data->h_y[0][2].z = 0.0; sim_data->h_y[0][2].w = 0.0; // Populate 3. body's x coordinate sim_data->h_y[0][3].x = 0.0; sim_data->h_y[0][3].y = 1.0; sim_data->h_y[0][3].z = 0.0; sim_data->h_y[0][3].w = 0.0; // Populate 0. body's x velocity sim_data->h_y[1][0].x = 1.0; sim_data->h_y[1][0].y = 0.0; sim_data->h_y[1][0].z = 0.0; sim_data->h_y[1][0].w = 0.0; // Populate 1. body's x velocity sim_data->h_y[1][1].x = 2.0; sim_data->h_y[1][1].y = 0.0; sim_data->h_y[1][1].z = 0.0; sim_data->h_y[1][1].w = 0.0; // Populate 2. body's x velocity sim_data->h_y[1][2].x = 2.0; sim_data->h_y[1][2].y = 0.0; sim_data->h_y[1][2].z = 0.0; sim_data->h_y[1][2].w = 0.0; // Populate 3. body's x velocity sim_data->h_y[1][3].x = 1.0; sim_data->h_y[1][3].y = 0.0; sim_data->h_y[1][3].z = 0.0; sim_data->h_y[1][3].w = 0.0; // Set the mass sim_data->h_p[0].mass = 1.0; sim_data->h_p[1].mass = 1.0; sim_data->h_p[2].mass = 1.0; sim_data->h_p[3].mass = 1.0; // Set the radius sim_data->h_p[0].radius = 1.0; sim_data->h_p[1].radius = 1.0; sim_data->h_p[2].radius = 1.0; sim_data->h_p[3].radius = 1.0; // Set the density sim_data->h_p[0].density = 0.23873241463784300365332564505877; sim_data->h_p[1].density = 0.23873241463784300365332564505877; sim_data->h_p[2].density = 0.23873241463784300365332564505877; sim_data->h_p[3].density = 0.23873241463784300365332564505877; // Set the Stokes-coefficient sim_data->h_p[0].cd = 0.0; sim_data->h_p[1].cd = 0.0; sim_data->h_p[2].cd = 0.0; sim_data->h_p[3].cd = 0.0; return sim_data; } static void test_util() { //__host__ __device__ var4_t rotate_2D_vector(var_t theta, var_t v_r, var_t v_theta); //template <typename T> //std::string number_to_string(T number); //int device_query(ostream& sout, int id_dev); //void allocate_host_vector( void **ptr, size_t size, const char *file, int line); //void allocate_device_vector(void **ptr, size_t size, const char *file, int line); //void allocate_vector( void **ptr, size_t size, bool cpu, const char *file, int line); //#define ALLOCATE_HOST_VECTOR( ptr, size) (allocate_host_vector( ptr, size, __FILE__, __LINE__)) //#define ALLOCATE_DEVICE_VECTOR(ptr, size) (allocate_device_vector(ptr, size, __FILE__, __LINE__)) //#define ALLOCATE_VECTOR( ptr, size, cpu) (allocate_vector( ptr, size, cpu, __FILE__, __LINE__)) //void free_host_vector( void **ptr, const char *file, int line); //void free_device_vector(void **ptr, const char *file, int line); //void free_vector( void **ptr, bool cpu, const char *file, int line); //#define FREE_HOST_VECTOR( ptr) (free_host_vector( ptr, __FILE__, __LINE__)) //#define FREE_DEVICE_VECTOR(ptr) (free_device_vector(ptr, __FILE__, __LINE__)) //#define FREE_VECTOR( ptr, cpu) (free_vector( ptr, cpu, __FILE__, __LINE__)) //void allocate_host_storage(sim_data_t *sd, int n); //void allocate_device_storage(sim_data_t *sd, int n); //void deallocate_host_storage(sim_data_t *sd); //void deallocate_device_storage(sim_data_t *sd); //void copy_vector_to_device(void* dst, const void *src, size_t count); //void copy_vector_to_host( void* dst, const void *src, size_t count); //void copy_vector_d2d( void* dst, const void *src, size_t count); //void copy_constant_to_device(const void* dst, const void *src, size_t count); //void set_device(int id_a_dev, bool verbose); //void print_array(string path, int n, var_t *data, computing_device_t comp_dev); const char test_set[] = "test_util"; fprintf(stderr, "TEST: %s\n", test_set); // Test rotate_2D_vector() { char test_func[] = "rotate_2D_vector"; var_t theta = 0.0; var4_t v = {0, 1, 0, 0}; var4_t expected = {0, 1, 0, 0}; var4_t result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } theta = PI / 2.0; expected.x = -1; expected.y = 0; result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } theta = PI; expected.x = 0; expected.y = -1; result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } theta = 3.0 * PI / 2.0; expected.x = 1; expected.y = 0; result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } theta = PI / 4.0; expected.x = -1/sqrt(2.0); expected.y = 1/sqrt(2.0); result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } theta = 3.0 * PI / 4.0; expected.x = -1/sqrt(2.0); expected.y = -1/sqrt(2.0); result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } theta = 5.0 * PI / 4.0; expected.x = 1/sqrt(2.0); expected.y = -1/sqrt(2.0); result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } theta = 7.0 * PI / 4.0; expected.x = 1/sqrt(2.0); expected.y = 1/sqrt(2.0); result = rotate_2D_vector(theta, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(result.x - expected.x) && 1.0e-16 < fabs(result.y - expected.y)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf, %25.16lf\n\t\t But was: %25.16lf, %25.16lf\n", expected.x, expected.y, result.x, result.y); } else { fprintf(stderr, "PASSED\n"); } } } static void test_tools() { //bool is_number(const string& str); //void rtrim(string& str); //void ltrim(string& str); //void trim(string& str); //string get_time_stamp(); //string convert_time_t(time_t t); ////! Computes the total mass of the system //var_t get_total_mass(int n, const sim_data_t *sim_data); ////! Computes the total mass of the bodies with type in the system //var_t get_total_mass(int n, body_type_t type, const sim_data_t *sim_data); //void calc_bc(int n, bool verbose, const sim_data_t *sim_data, var4_t* R0, var4_t* V0); //void transform_to_bc(int n, bool verbose, const sim_data_t *sim_data); //var_t calc_radius(var_t m, var_t density); //var_t calc_density(var_t m, var_t R); //var_t calc_mass(var_t R, var_t density); //void calc_position_after_collision(var_t m1, var_t m2, const var4_t* r1, const var4_t* r2, var4_t& r); //void calc_velocity_after_collision(var_t m1, var_t m2, const var4_t* v1, const var4_t* v2, var4_t& v); //void calc_physical_properties(var_t m1, var_t m2, var_t r1, var_t r2, var_t cd, param_t &p); //var_t norm(const var4_t* r); //var_t calc_dot_product(const var4_t& v, const var4_t& u); //var4_t calc_cross_product(const var4_t& v, const var4_t& u); //var_t calc_kinetic_energy(const var4_t* v); //var_t calc_pot_energy(var_t mu, const var4_t* r); //int kepler_equation_solver(var_t ecc, var_t mean, var_t eps, var_t* E); //int calc_phase(var_t mu, const orbelem_t* oe, var4_t* rVec, var4_t* vVec); //void print_vector(var4_t *v); const char test_set[] = "test_tools"; fprintf(stderr, "TEST: %s\n", test_set); // Test is_number() { char test_func[] = "is_number"; string arg = "1.0"; var_t num = 1.0; bool expected = true; bool result = tools::is_number(arg); fprintf(stderr, "\t%s(): ", test_func); if (result != expected && num == atof(arg.c_str())) { fprintf(stderr, "FAILED\n\t\tExpected: %5s\n\t\t But was: %5s\n", (expected ? "true" : "false"), (result ? "true" : "false")); } else { fprintf(stderr, "PASSED\n"); } arg = "-1.0"; num = -1.0; expected = true; result = tools::is_number(arg); fprintf(stderr, "\t%s(): ", test_func); if (result != expected && num == atof(arg.c_str())) { fprintf(stderr, "FAILED\n\t\tExpected: %5s\n\t\t But was: %5s\n", (expected ? "true" : "false"), (result ? "true" : "false")); } else { fprintf(stderr, "PASSED\n"); } arg = "+1.0e3"; num = 1000.0; expected = true; result = tools::is_number(arg); fprintf(stderr, "\t%s(): ", test_func); if (result != expected && num == atof(arg.c_str())) { fprintf(stderr, "FAILED\n\t\tExpected: %5s\n\t\t But was: %5s\n", (expected ? "true" : "false"), (result ? "true" : "false")); } else { fprintf(stderr, "PASSED\n"); } arg = "1.e3"; num = 1000.0; expected = true; result = tools::is_number(arg); fprintf(stderr, "\t%s(): ", test_func); if (result != expected && num == atof(arg.c_str())) { fprintf(stderr, "FAILED\n\t\tExpected: %5s\n\t\t But was: %5s\n", (expected ? "true" : "false"), (result ? "true" : "false")); } else { fprintf(stderr, "PASSED\n"); } arg = "1.E-3"; num = 0.001; expected = true; result = tools::is_number(arg); fprintf(stderr, "\t%s(): ", test_func); if (result != expected && num == atof(arg.c_str())) { fprintf(stderr, "FAILED\n\t\tExpected: %5s\n\t\t But was: %5s\n", (expected ? "true" : "false"), (result ? "true" : "false")); } else { fprintf(stderr, "PASSED\n"); } arg = "1.g-3"; expected = false; result = tools::is_number(arg); fprintf(stderr, "\t%s(): ", test_func); if (result != expected) { fprintf(stderr, "FAILED\n\t\tExpected: %5s\n\t\t But was: %5s\n", (expected ? "true" : "false"), (result ? "true" : "false")); } else { fprintf(stderr, "PASSED\n"); } } // Test trim_right() { char test_func[] = "trim_right"; string result = " This string will be trimed to the right "; string expected = " This string will be trimed to the right"; result = tools::rtrim(result); fprintf(stderr, "\t%s(): ", test_func); if (result != expected) { fprintf(stderr, "FAILED\n\t\tExpected: %s\n\t\t But was: %s\n", expected.c_str(), result.c_str()); } else { fprintf(stderr, "PASSED\n"); } result = "This string will be trimed to the right after the 'x' character "; expected = "This string will be trimed to the right after the '"; result = tools::rtrim(result, "x"); fprintf(stderr, "\t%s(): ", test_func); if (result != expected) { fprintf(stderr, "FAILED\n\t\tExpected: %s\n\t\t But was: %s\n", expected.c_str(), result.c_str()); } else { fprintf(stderr, "PASSED\n"); } } // Test trim_left() { char test_func[] = "trim_left"; string result = " This string will be trimed to the left "; string expected = "This string will be trimed to the left "; result = tools::ltrim(result); fprintf(stderr, "\t%s(): ", test_func); if (result != expected) { fprintf(stderr, "FAILED\n\t\tExpected: %s\n\t\t But was: %s\n", expected.c_str(), result.c_str()); } else { fprintf(stderr, "PASSED\n"); } result = " c This string will be trimed to the left "; expected = "c This string will be trimed to the left "; result = tools::ltrim(result); fprintf(stderr, "\t%s(): ", test_func); if (result != expected) { fprintf(stderr, "FAILED\n\t\tExpected: %s\n\t\t But was: %s\n", expected.c_str(), result.c_str()); } else { fprintf(stderr, "PASSED\n"); } } // Test trim() { char test_func[] = "trim"; string result = " This string will be trimed to the right as well as to the left "; string expected = "This string will be trimed to the right as well as to the left"; result = tools::trim(result); fprintf(stderr, "\t%s(): ", test_func); if (result != expected) { fprintf(stderr, "FAILED\n\t\tExpected: %s\n\t\t But was: %s\n", expected.c_str(), result.c_str()); } else { fprintf(stderr, "PASSED\n"); } } // Test get_time_stamp() { char test_func[] = "get_time_stamp"; string result = tools::get_time_stamp(false); fprintf(stderr, "\t%s(): [should print the actual date and time] ", test_func); fprintf(stderr, "%s: PASSED ??\n", result.c_str()); } // Test convert_time_t() { char test_func[] = "convert_time_t"; string result = tools::convert_time_t((time_t)60); string expected = "60"; fprintf(stderr, "\t%s(): ", test_func); if (result != expected) { fprintf(stderr, "FAILED\n\t\tExpected: %s\n\t\t But was: %s\n", expected.c_str(), result.c_str()); } else { fprintf(stderr, "PASSED\n"); } } // Test get_total_mass() { char test_func[] = "get_total_mass"; sim_data_t* sim_data = create_sim_data(); var_t expected = 4.0; var_t result = tools::get_total_mass(4, sim_data); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } delete sim_data; } // Test get_total_mass() { char test_func[] = "get_total_mass"; sim_data_t* sim_data = create_sim_data(); var_t expected = 1.0; var_t result = tools::get_total_mass(4, BODY_TYPE_STAR, sim_data); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } expected = 2.0; result = tools::get_total_mass(4, BODY_TYPE_GIANTPLANET, sim_data); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } expected = 1.0; result = tools::get_total_mass(4, BODY_TYPE_PROTOPLANET, sim_data); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } expected = 0.0; result = tools::get_total_mass(4, BODY_TYPE_ROCKYPLANET, sim_data); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } delete sim_data; } // Test calc_bc() { char test_func[] = "calc_bc"; sim_data_t* sim_data = create_sim_data(); var4_t expected_R0 = {0.5, 0.5, 0.0, 0.0}; var4_t expected_V0 = {1.5, 0.0, 0.0, 0.0}; var4_t result_R0 = {0.0, 0.0, 0.0, 0.0}; var4_t result_V0 = {0.0, 0.0, 0.0, 0.0}; var_t M0 = tools::get_total_mass(4, sim_data); tools::calc_bc(4, sim_data, M0, &result_R0, &result_V0); var_t dr = fabs(expected_R0.x - result_R0.x) + fabs(expected_R0.y - result_R0.y) + fabs(expected_R0.z - result_R0.z) + fabs(expected_R0.w - result_R0.w); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < dr) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", 0.0, dr); } else { fprintf(stderr, "R0 PASSED\n"); } var_t dv = fabs(expected_V0.x - result_V0.x) + fabs(expected_V0.y - result_V0.y) + fabs(expected_V0.z - result_V0.z) + fabs(expected_V0.w - result_V0.w); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < dv) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", 0.0, dv); } else { fprintf(stderr, "V0 PASSED\n"); } delete sim_data; } // Test transform_to_bc() { char test_func[] = "transform_to_bc"; sim_data_t* sim_data = create_sim_data(); tools::transform_to_bc(4, sim_data); var4_t r0[] = { {-0.5, -0.5, 0.0, 0.0}, { 0.5, -0.5, 0.0, 0.0}, { 0.5, 0.5, 0.0, 0.0}, {-0.5, 0.5, 0.0, 0.0}, }; for (int i = 0; i < 4; i++) { var_t dr = fabs(r0[i].x - sim_data->h_y[0][i].x) + fabs(r0[i].y - sim_data->h_y[0][i].y) + fabs(r0[i].z - sim_data->h_y[0][i].z) + fabs(r0[i].w - sim_data->h_y[0][i].w); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < dr) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", 0.0, dr); } else { fprintf(stderr, "R PASSED\n"); } } var4_t v0[] = { {-0.5, 0.0, 0.0, 0.0}, { 0.5, 0.0, 0.0, 0.0}, { 0.5, 0.0, 0.0, 0.0}, {-0.5, 0.0, 0.0, 0.0}, }; for (int i = 0; i < 4; i++) { var_t dv = fabs(v0[i].x - sim_data->h_y[1][i].x) + fabs(v0[i].y - sim_data->h_y[1][i].y) + fabs(v0[i].z - sim_data->h_y[1][i].z) + fabs(v0[i].w - sim_data->h_y[1][i].w); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < dv) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", 0.0, dv); } else { fprintf(stderr, "V PASSED\n"); } } delete sim_data; } // Test calc_radius() { char test_func[] = "calc_radius"; var_t mass = 1.0; var_t density = 1.0; var_t expected = 0.62035049089940001666800681204778; var_t result = tools::calc_radius(mass, density); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } } // Test calc_mass() { char test_func[] = "calc_mass"; var_t radius = 1.0; var_t density = 1.0; var_t expected = 4.1887902047863909846168578443727; var_t result = tools::calc_mass(radius, density); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } } // Test calc_density() { char test_func[] = "calc_density"; var_t mass = 1.0; var_t radius = 1.0; var_t expected = 0.23873241463784300365332564505877; var_t result = tools::calc_density(mass, radius); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } } // Test calc_position_after_collision() { char test_func[] = "calc_position_after_collision"; var_t m1 = 1.0; var_t m2 = 1.0; var4_t r1 = {1.0, 1.0, 1.0, 0.0}; var4_t r2 = {4.0, 3.0, 1.0, 0.0}; var4_t expected = {2.5, 2.0, 1.0, 0.0}; var4_t result = {0.0, 0.0, 0.0, 0.0}; tools::calc_position_after_collision(m1, m2, &r1, &r2, result); var_t dr = fabs(expected.x - result.x) + fabs(expected.y - result.y) + fabs(expected.z - result.z) + fabs(expected.w - result.w); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < dr) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", 0.0, dr); } else { fprintf(stderr, "PASSED\n"); } } // Test calc_velocity_after_collision() { char test_func[] = "calc_velocity_after_collision"; var_t m1 = 1.0; var_t m2 = 1.0; var4_t v1 = { 1.0, 0.0, 0.0, 0.0}; var4_t v2 = {-1.0, 0.0, 0.0, 0.0}; var4_t expected = {0.0, 0.0, 0.0, 0.0}; var4_t result = {0.0, 0.0, 0.0, 0.0}; tools::calc_velocity_after_collision(m1, m2, &v1, &v2, result); var_t dr = fabs(expected.x - result.x) + fabs(expected.y - result.y) + fabs(expected.z - result.z) + fabs(expected.w - result.w); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < dr) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", 0.0, dr); } else { fprintf(stderr, "PASSED\n"); } v1.x = -1.0; v1.y = 0.0; v1.z = 0.0; v2.x = -1.0; v2.y = 0.0; v2.z = 0.0; expected.x = -1.0; expected.y = 0.0; expected.z = 0.0; tools::calc_velocity_after_collision(m1, m2, &v1, &v2, result); dr = fabs(expected.x - result.x) + fabs(expected.y - result.y) + fabs(expected.z - result.z) + fabs(expected.w - result.w); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < dr) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", 0.0, dr); } else { fprintf(stderr, "PASSED\n"); } } // Test calc_physical_properties() { char test_func[] = "calc_physical_properties"; param_t p1 = {0.0, 0.0, 0.0, 0.0}; param_t p2 = {0.0, 0.0, 0.0, 0.0}; p1.cd = 1.0; p1.density = 1.0; p1.mass = 1.0; p1.radius = 1.0; p2.cd = 1.0; p2.density = 1.0; p2.mass = 1.0; p2.radius = 1.0; param_t result = {0.0, 0.0, 0.0, 0.0}; param_t expected = {0.0, 0.0, 0.0, 0.0}; expected.mass = 2.0; expected.density = 0.23873241463784300365332564505877; expected.radius = tools::calc_radius(2.0, 0.23873241463784300365332564505877); expected.cd = 1.0; tools::calc_physical_properties(p1, p2, result); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected.cd - result.cd)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected.cd, result.cd); } else { fprintf(stderr, "PASSED\n"); } fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected.density - result.density)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected.density, result.density); } else { fprintf(stderr, "PASSED\n"); } fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected.mass - result.mass)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected.mass, result.mass); } else { fprintf(stderr, "PASSED\n"); } fprintf(stderr, "\t%s(): ", test_func); if (1.0e-15 < fabs(expected.radius - result.radius)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected.radius, result.radius); } else { fprintf(stderr, "PASSED\n"); } } // Test var_t norm(const var4_t* r) { char test_func[] = "norm"; var4_t v = {0.0, 0.0, 0.0, 0.0}; var_t expected = 0.0; var_t result = tools::norm(&v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } v.x = 1.0; v.y = -1.0; expected = sqrt(2.0); result = tools::norm(&v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } v.x = -2.0; v.y = -1.0; expected = sqrt(5.0); result = tools::norm(&v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } } //Test var_t calc_dot_product(const var4_t& u, const var4_t& v) { char test_func[] = "calc_dot_product"; var4_t u = {0.0, 0.0, 0.0, 0.0}; var4_t v = {0.0, 0.0, 0.0, 0.0}; var_t expected = 0.0; var_t result = tools::calc_dot_product(v, u); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } u.x = 1.0; v.x = 1.0; expected = 1.0; result = tools::calc_dot_product(v, u); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } u.x = 2.0; v.x = 0.0; v.y = 1.0; expected = 0.0; result = tools::calc_dot_product(v, u); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected - result)) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result); } else { fprintf(stderr, "PASSED\n"); } } //Test calc_cross_product(const var4_t& u, const var4_t& v) { char test_func[] = "calc_cross_product"; var4_t u = {0.0, 0.0, 0.0, 0.0}; var4_t v = {0.0, 0.0, 0.0, 0.0}; var4_t expected = {0.0, 0.0, 0.0, 0.0}; var4_t result = tools::calc_cross_product(u, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected.x - result.x) || 1.0e-16 < fabs(expected.y - result.y) || 1.0e-16 < fabs(expected.z - result.z) ) { fprintf(stderr, "FAILED\n\t\tExpected: (%25.16lf, %25.16lf, %25.16lf)\n\t\t But was: (%25.16lf, %25.16lf, %25.16lf)\n", expected.x, expected.y, expected.z, result.x, result.y, result.z); } else { fprintf(stderr, "PASSED\n"); } u.x = 1.0; v.x = 1.0; u.y = 0.0; v.y = 0.0; u.z = 0.0; v.z = 0.0; result = tools::calc_cross_product(u, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected.x - result.x) || 1.0e-16 < fabs(expected.y - result.y) || 1.0e-16 < fabs(expected.z - result.z) ) { fprintf(stderr, "FAILED\n\t\tExpected: (%25.16lf, %25.16lf, %25.16lf)\n\t\t But was: (%25.16lf, %25.16lf, %25.16lf)\n", expected.x, expected.y, expected.z, result.x, result.y, result.z); } else { fprintf(stderr, "PASSED\n"); } u.x = 1.0; v.x = 0.0; u.y = 0.0; v.y = 1.0; u.z = 0.0; v.z = 0.0; expected.x = 0.0; expected.y = 0.0; expected.z = 1.0; result = tools::calc_cross_product(u, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected.x - result.x) || 1.0e-16 < fabs(expected.y - result.y) || 1.0e-16 < fabs(expected.z - result.z) ) { fprintf(stderr, "FAILED\n\t\tExpected: (%25.16lf, %25.16lf, %25.16lf)\n\t\t But was: (%25.16lf, %25.16lf, %25.16lf)\n", expected.x, expected.y, expected.z, result.x, result.y, result.z); } else { fprintf(stderr, "PASSED\n"); } u.x = 1.0; v.x = 0.0; u.y = 0.0; v.y = 1.0; u.z = 1.0; v.z = 0.0; expected.x = -1.0; expected.y = 0.0; expected.z = 1.0; result = tools::calc_cross_product(u, v); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-16 < fabs(expected.x - result.x) || 1.0e-16 < fabs(expected.y - result.y) || 1.0e-16 < fabs(expected.z - result.z) ) { fprintf(stderr, "FAILED\n\t\tExpected: (%25.16lf, %25.16lf, %25.16lf)\n\t\t But was: (%25.16lf, %25.16lf, %25.16lf)\n", expected.x, expected.y, expected.z, result.x, result.y, result.z); } else { fprintf(stderr, "PASSED\n"); } } //Test calc_total_energy() { } // Test kepler_equation_solver() { char test_func[] = "kepler_equation_solver"; var_t ecc = 0.5; var_t mean_anomaly = 27.0 * constants::DegreeToRadian; var_t expected = 48.43417991487915; // degree var_t result = 0.0; tools::kepler_equation_solver(ecc, mean_anomaly, 1.0e-15, &result); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-13 < fabs(expected - (result * constants::RadianToDegree))) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result * constants::RadianToDegree); } else { fprintf(stderr, "PASSED\n"); } mean_anomaly = 225.0 * constants::DegreeToRadian; expected = 210.47211284530107; // degree result = 0.0; tools::kepler_equation_solver(ecc, mean_anomaly, 1.0e-15, &result); fprintf(stderr, "\t%s(): ", test_func); if (1.0e-13 < fabs(expected - (result * constants::RadianToDegree))) { fprintf(stderr, "FAILED\n\t\tExpected: %25.16lf\n\t\t But was: %25.16lf\n", expected, result * constants::RadianToDegree); } else { fprintf(stderr, "PASSED\n"); } } // Test print_vector() { char test_func[] = "print_vector"; var4_t v = {-1.0, 1.0, 2.0, 0.0}; fprintf(stderr, "\t%s(): [the two lines below must be identical]\n", test_func); fprintf(stderr, " -1.0000000000000000e+000 1.0000000000000000e+000 2.0000000000000000e+000 0.0000000000000000e+000\n"); tools::print_vector(&v); fprintf(stderr, "\tPASSED ??\n"); } } namespace red_test { int run(int argc, char *argv[]) { test_tools(); test_util(); return 0; } } /* red_test */ } /* redutilcu */
// // Created by zhanggyb on 16-9-19. // #include "test.hpp" #include <skland/core/color.hpp> #include <skland/graphic/paint.hpp> #include <SkPaint.h> using skland::Color; using skland::Paint; Test::Test() : testing::Test() { } Test::~Test() { } TEST_F(Test, enums_check_1) { // Compare Paint::Style and SkPaint::Style ASSERT_TRUE((int) Paint::Style::kStyleFill == (int) SkPaint::Style::kFill_Style); ASSERT_TRUE((int) Paint::Style::kStyleStroke == (int) SkPaint::Style::kStroke_Style); ASSERT_TRUE((int) Paint::Style::kStyleStrokeAndFill == (int) SkPaint::Style::kStrokeAndFill_Style); // Compare Paint::Hinting and SkPaint::Hinting ASSERT_TRUE((int) Paint::Hinting::kHintingNone == (int) SkPaint::Hinting::kNo_Hinting); ASSERT_TRUE((int) Paint::Hinting::kHintingSlight == (int) SkPaint::Hinting::kSlight_Hinting); ASSERT_TRUE((int) Paint::Hinting::kHintingNormal == (int) SkPaint::Hinting::kNormal_Hinting); ASSERT_TRUE((int) Paint::Hinting::kHintingFull == (int) SkPaint::Hinting::kFull_Hinting); } TEST_F(Test, constructor_1) { Color blue(0.f, 0.f, 1.f, 1.f); Color ret; Paint paint; paint.SetColor(blue); ret = paint.GetColor(); ASSERT_TRUE(ret == blue); }