text
stringlengths 8
6.88M
|
|---|
/*
Bullet Continuous Collision Detection and Physics Library Maya Plugin
Copyright (c) 2008 Walt Disney Studios
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising
from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Written by: Erwin Coumans <erwin.coumans@gmail.com>
*/
//bt_compound_shape.h
#ifndef DYN_BT_COMPOUND_SHAPE_H
#define DYN_BT_COMPOUND_SHAPE_H
#include "composite_shape_impl.h"
#include "drawUtils.h"
#include "BulletCollision/CollisionShapes/btCompoundShape.h"
class bt_composite_shape_t: public bt_collision_shape_t
{
public:
virtual void gl_draw(size_t draw_style)
{
std::cout << "bt_box_shape_t::draw" << std::endl;
}
virtual void set_scale(vec3f const& s) {
const btVector3& scale = shape()->getLocalScaling();
if(scale.x() != s[0] || scale.y() != s[1] || scale.z() != s[2]) {
shape()->setLocalScaling(btVector3(s[0], s[1], s[2]));
update();
}
}
virtual void get_scale(vec3f& s) {
const btVector3& scale = shape()->getLocalScaling();
s = vec3f(scale.x(), scale.y(), scale.z());
}
virtual float volume() { return m_volume; }
virtual vec3f const& local_inertia() { return m_local_inertia; }
virtual vec3f const& center() { return m_center; }
virtual quatf const& rotation() { return m_rotation; }
virtual void getCenterOfMassTransformShift(class btTransform& shiftTransform)
{
shiftTransform.setIdentity();
shiftTransform.setOrigin(btVector3(center()[0],center()[1],center()[2]));
shiftTransform.setRotation(btQuaternion(rotation()[1],rotation()[2],rotation()[3],rotation()[0]));
}
protected:
friend class bt_solver_t;
std::vector<collision_shape_t::pointer> m_childCollisionShapes;
std::vector< vec3f> m_childPosition;
std::vector< quatf> m_childOrientations;
bt_composite_shape_t(
collision_shape_t::pointer* childShapes,
vec3f* childPositions,
quatf* childOrientations,
int numChildren):
bt_collision_shape_t()
{
for (int i=0;i<numChildren;i++)
{
m_childCollisionShapes.push_back(childShapes[i]);
m_childPosition.push_back(childPositions[i]);
m_childOrientations.push_back(childOrientations[i]);
}
btCompoundShape* compound = new btCompoundShape();
for (int i=0;i<numChildren;i++)
{
btTransform childTrans;
childTrans.setIdentity();
childTrans.setOrigin(btVector3(childPositions[i][0],childPositions[i][1],childPositions[i][2]));
childTrans.setRotation(btQuaternion(childOrientations[i][1],childOrientations[i][2],childOrientations[i][3],childOrientations[i][0]));
btCollisionShape* childShape = childShapes[i]->getBulletCollisionShape();
if (childShape)
{
compound->addChildShape(childTrans, childShape);
}
}
btScalar* masses = new btScalar[numChildren];
for (int i=0;i<numChildren;i++)
masses[i] = 1.f;
btTransform principal;
btVector3 inertia;
compound->calculatePrincipalAxisTransform(masses, principal, inertia);
delete[] masses;
m_center = vec3f(principal.getOrigin().x(),principal.getOrigin().y(),principal.getOrigin().z());
m_rotation = quatf(principal.getRotation().w(),principal.getRotation().x(),principal.getRotation().y(),principal.getRotation().z());
for (int i=0;i<numChildren;i++)
{
btTransform newChildTrans = principal.inverse() * compound->getChildTransform(i);
compound->updateChildTransform(i,newChildTrans,false);
}
compound->recalculateLocalAabb();
set_shape(compound);
update();
}
virtual ~bt_composite_shape_t()
{
int i;
i=0;
}
void update()
{
btCompoundShape* compound_shape = static_cast<btCompoundShape*>(shape());
//btVector3 e = 2 * compound_shape->getHalfExtentsWithoutMargin();
btTransform tr;
tr.setIdentity();
btVector3 aabbMin,aabbMax,localInertia;
compound_shape->getAabb(tr, aabbMin,aabbMax);
compound_shape->calculateLocalInertia(1.f,localInertia);
btVector3 e = aabbMax-aabbMin;
m_volume = e.x() * e.y() * e.z();
//m_center = vec3f(0,0,0);
//m_rotation = qidentity<float>();
m_local_inertia = vec3f(localInertia.x(),localInertia.y(),localInertia.z());
}
private:
float m_volume;
vec3f m_center;
quatf m_rotation;
vec3f m_local_inertia;
};
#endif //DYN_BT_COMPOUND_SHAPE_H
|
#ifndef INEXOR_RPC_MCRPCSERVER_HEADER
#define INEXOR_RPC_MCRPCSERVER_HEADER
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>
#include <cstdbool>
#include <cstddef>
#include <cstdint>
#include "net/MessageConnect.h"
namespace inexor {
namespace rpc {
/**
* Rpc Server backed by a MessageConnect.
*
* The only thing you need to do is calling
* ProcessAllCalls() or ProcessOneCall(), this should
* automatically call the correct method in the service
* object and then send the message right back.
*
* This implementation expects messages on the
* MessageConnect. Those messages must be serialized
* ServiceCall protobufs.
* Return values are also encoded, serialized with the
* ServiceCall and sent via the message connect.
*
* TODO: Implement the Closure (callback) and the
* RpcController
*/
class MCRpcServer {
private:
typedef google::protobuf::Service Service;
typedef inexor::net::MessageConnect MessageConnect;
MessageConnect *mc = NULL;
Service *service = NULL;
public:
/**
* Create a new MCRpcServer.
*
* @param service_ The service to serve.
* @param mc_ The message connect to use for receiving
* calls and sending return values.
*/
MCRpcServer(Service *service_, MessageConnect *mc_)
: mc(mc_), service(service_) {}
/**
* Process all calls to be processed.
*
* This calls ProcessOneCall() as long as it processes
* calls.
*
* TODO: Limit/Timeout!
*
* @return The number of calls processed.
*/
unsigned int ProcessAllCalls();
/**
* Receive one call if available and execute the
* associated code.
*
* @return Whether a call had been made.
*/
bool ProcessOneCall();
};
}
}
#endif
|
/*********************************************************************
Matt Marchant 2014 - 2016
http://trederia.blogspot.com
xygine - Zlib license.
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*********************************************************************/
#ifndef XY_CUBE_BUILDER_HPP_
#define XY_CUBE_BUILDER_HPP_
#include <xygine/mesh/ModelBuilder.hpp>
#include <xygine/mesh/BoundingBox.hpp>
#include <array>
namespace xy
{
/*!
\brief Implements the ModelBuilder interface for quickly creating
cube meshes.
\see ModelBuilder
*/
class XY_EXPORT_API CubeBuilder final : public ModelBuilder
{
public:
explicit CubeBuilder(float size);
~CubeBuilder() = default;
void build() override;
VertexLayout getVertexLayout() const override;
const float* getVertexData() const override { return m_vertexData.data(); }
std::size_t getVertexCount() const override { return 24; }
const BoundingBox& getBoundingBox() const override { return m_boundingBox; }
private:
float m_size;
BoundingBox m_boundingBox;
std::array<std::uint8_t, 36> m_indices;
std::vector<float> m_vertexData;
std::vector<VertexLayout::Element> m_elements;
};
}
#endif //XY_CUBE_BUILDER_HPP_
|
#pragma once
#include <QObject>
class Integ : public QObject
{
Q_OBJECT
public:
Integ(QObject *parent);
~Integ();
};
|
#ifndef TREE_HPP
#define TREE_HPP
#define USTEMP template<typename T>
#include "node.hpp"
//fournir les operateurs [], =, ==, <, >, <=, >=, parcourir les noeud
//Classe template a semantique de valeur qui represente un arbre
template<typename T>
class BasicTree
{
public:
BasicTree()
{
}//Le constructeur sans première valeur
BasicTree(T const& first_val)
{
m_first_nodes.push_back(std::make_unique<Node<T>>(first_val)); //On ajoute un nouveau pointeur au tableau
}
//Constructeur avec première valeur
virtual ~BasicTree()
{
for(auto& ref: m_first_nodes)
ref.reset();
}//Le destructeur est virtuel car le BasicTree pourrat être dérivé pour faire un binary tree
std::size_t size()
{
std::size_t i { 0 }; //Compteur
for(auto& ref: m_first_nodes)
{
++i;
i += parcourir_for_size(ref);
}
return i;
}//Renvoie le nombre de noeud de l'arbre
std::vector<std::unique_ptr<Node<T>>>& child()
{
return m_first_nodes;
}
Node<T> operator[](BasicTree<T> const& tr)
{
return Node<int>(5);
}
protected:
std::size_t parcourir_for_size(std::unique_ptr<Node<T>>& ptr)
{
std::size_t i { 0 };
for(auto& ref: ptr->children())
{
++i;
i += parcourir_for_size(ref);
}
return i;
}
std::vector<std::unique_ptr<Node<T>>> m_first_nodes;
};
USTEMP
bool operator==(BasicTree<T> const& tr1, BasicTree<T> const& tr2);
USTEMP
bool operator!=(BasicTree<T> const& tr1, BasicTree<T> const& tr2);
USTEMP
bool operator<(BasicTree<T> const& tr1, BasicTree<T> const& tr2);
USTEMP
bool operator>(BasicTree<T> const& tr1, BasicTree<T> const& tr2);
USTEMP
bool operator<=(BasicTree<T> const& tr1, BasicTree<T> const& tr2);
USTEMP
bool operator>=(BasicTree<T> const& tr1, BasicTree<T> const& tr2);
#endif // TREE_HPP
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// Classes:
// ComponentAccess<T>
// CompFwd<Eng, N>
// Engine<Dim, T, CompFwd<Eng, N> >
// NewEngine< Engine<Dim, T, CompFwd<Eng, N> >, Domain >
//-----------------------------------------------------------------------------
#ifndef POOMA_ENGINE_FORWARDINGENGINE_H
#define POOMA_ENGINE_FORWARDINGENGINE_H
#include "Domain/Loc.h"
#include "Functions/ComponentAccess.h"
#include "Engine/Engine.h"
#include "Engine/EngineFunctor.h"
#include "Engine/EnginePatch.h"
#include "Engine/NotifyEngineWrite.h"
#include "PETE/PETE.h"
/** @file
* @ingroup Engine
* @brief
* A ForwardingEngine is used to forward indices to the elements of another
* engine.
*/
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
template <int Dim> class DomainLayout;
/**
* The component forwarding tag class.
*/
template<class Eng, class Components>
struct CompFwd { };
/**
* A ForwardingEngine is used to forward indices to the elements of another
* engine.
*/
template<int Dim, class T, class Eng, class Components>
class Engine<Dim, T, CompFwd<Eng, Components> >
{
public:
//---------------------------------------------------------------------------
// This_t is a convenience typedef referring to this class.
typedef Engine<Dim, T, Eng> This_t;
//---------------------------------------------------------------------------
// Engine_t is a typedef that makes the template parameter Engine accessible
// to other classes. ElemEngine_t makes the engine we're forwarding to
// visible.
typedef This_t Engine_t;
typedef Eng ElemEngine_t;
//---------------------------------------------------------------------------
// Element_t is the type of elements managed by this engine.
// ElementRef_t is the type that is used to write to a single element.
// This might be a reference or a proxy object.
// The typedef Domain_t gives the type of domain this engine is defined on.
// The enum 'dimensions' gives the dimensionality of this engine.
// Tag_t is my tag.
// Layout_t is the type of layout I'd cough up, if asked.
typedef typename Eng::Element_t FwdElement_t;
typedef ComponentAccess<FwdElement_t, Components> CompAccess_t;
typedef typename CompAccess_t::Element_t Element_t;
typedef typename CompAccess_t::ElementRef_t ElementRef_t;
typedef typename Eng::Domain_t Domain_t;
typedef CompFwd<Eng, Components> Tag_t;
typedef typename Eng::Layout_t Layout_t;
//---------------------------------------------------------------------------
// required constants
enum { dimensions = Eng::dimensions };
enum { hasDataObject = Eng::hasDataObject };
enum { dynamic = false };
enum { zeroBased = Eng::zeroBased };
enum { multiPatch = Eng::multiPatch };
//---------------------------------------------------------------------------
// Empty constructor required for containers of engines.
Engine()
: engine_m(), components_m()
{ }
//---------------------------------------------------------------------------
// This is the most basic way to build a forwarding engine. We take an
// engine and a Components giving the components we're supposed to forward.
Engine(const Eng &e, const Components &l)
: engine_m(e), components_m(l)
{ }
//---------------------------------------------------------------------------
// Copy constructor.
Engine(const This_t &e)
: engine_m(e.elemEngine()), components_m(e.components()) { }
//---------------------------------------------------------------------------
// View constructor. This is used to take a view of another forwarding
// engine. OtherEngine should be the type computed by taking a view of
// Engine_t using Domain_t.
template<class OtherEng, class Domain>
Engine(const Engine< Dim, T, CompFwd<OtherEng, Components> > &e,
const Domain &domain)
: engine_m(NewEngineEngine<OtherEng,Domain>::apply(e.elemEngine(),domain),
NewEngineDomain<OtherEng,Domain>::apply(e.elemEngine(),domain)),
components_m(e.components()) { }
//---------------------------------------------------------------------------
// Destructor. Trivial since the engine_m and components_m objects have their
// destructors called automatically.
~Engine() { }
//---------------------------------------------------------------------------
// Element accessor. Get engine()'s element by passing the domain to
// its operator(). Then, forward the components to the element using
// Element_t's operator().
inline ElementRef_t operator()(const Loc<dimensions> &eloc) const
{
return CompAccess_t::indexRef(elemEngine()(eloc), components());
}
inline ElementRef_t operator()(int i1) const
{
return CompAccess_t::indexRef(elemEngine()(i1), components());
}
inline ElementRef_t operator()(int i1, int i2) const
{
return CompAccess_t::indexRef(elemEngine()(i1, i2), components());
}
inline ElementRef_t operator()(int i1, int i2, int i3) const
{
return CompAccess_t::indexRef(elemEngine()(i1, i2, i3),
components());
}
inline ElementRef_t operator()(int i1, int i2, int i3, int i4) const
{
return CompAccess_t::indexRef(elemEngine()(i1, i2, i3, i4),
components());
}
inline ElementRef_t operator()(int i1, int i2, int i3, int i4, int i5) const
{
return CompAccess_t::indexRef(elemEngine()(i1, i2, i3, i4, i5),
components());
}
inline ElementRef_t operator()(int i1, int i2, int i3, int i4, int i5,
int i6) const
{
return CompAccess_t::indexRef(elemEngine()(i1, i2, i3, i4, i5, i6),
components());
}
inline ElementRef_t operator()(int i1, int i2, int i3, int i4, int i5,
int i6, int i7) const
{
return CompAccess_t::indexRef(elemEngine()(i1, i2, i3, i4, i5, i6, i7),
components());
}
//---------------------------------------------------------------------------
// Read-only element accessor. Get engine()'s element by passing the domain
// to its operator(). Then, forward the components to the element using
// Element_t's operator().
inline Element_t read(const Loc<dimensions> &eloc) const
{
return CompAccess_t::index(elemEngine().read(eloc), components());
}
inline Element_t read(int i1) const
{
return CompAccess_t::index(elemEngine().read(i1), components());
}
inline Element_t read(int i1, int i2) const
{
return CompAccess_t::index(elemEngine().read(i1, i2), components());
}
inline Element_t read(int i1, int i2, int i3) const
{
return CompAccess_t::index(elemEngine().read(i1, i2, i3),
components());
}
inline Element_t read(int i1, int i2, int i3, int i4) const
{
return CompAccess_t::index(elemEngine().read(i1, i2, i3, i4),
components());
}
inline Element_t read(int i1, int i2, int i3, int i4, int i5) const
{
return CompAccess_t::index(elemEngine().read(i1, i2, i3, i4, i5),
components());
}
inline Element_t read(int i1, int i2, int i3, int i4, int i5,
int i6) const
{
return CompAccess_t::index(elemEngine().read(i1, i2, i3, i4, i5, i6),
components());
}
inline Element_t read(int i1, int i2, int i3, int i4, int i5,
int i6, int i7) const
{
return CompAccess_t::index(elemEngine().read(i1, i2, i3, i4, i5, i6, i7),
components());
}
//---------------------------------------------------------------------------
// Returns the layout, which is acquired from the contained engine.
inline const Layout_t& layout() const
{
return elemEngine().layout();
}
inline Layout_t& layout()
{
return elemEngine().layout();
}
//---------------------------------------------------------------------------
// Returns the domain, which is acquired from the contained engine.
inline const Domain_t& domain() const { return elemEngine().domain(); }
//---------------------------------------------------------------------------
// Return the first value for the specified direction.
inline int first(int i) const
{
return elemEngine().first(i);
}
//---------------------------------------------------------------------------
// Get a private copy of this engine. Simply forwards the 'makeOwnCopy'
// request to the contained engine.
This_t &makeOwnCopy()
{
elemEngine().makeOwnCopy();
return *this;
}
//---------------------------------------------------------------------------
// Assessor functions that return the engine and components.
Eng &elemEngine() { return engine_m; }
const Eng &elemEngine() const { return engine_m; }
const Components &components() const { return components_m; }
private:
Eng engine_m;
Components components_m;
};
/**
* Specialization allowing a view to be taken of a forwarding engine.
*/
template <int Dim, class T, class Eng, class Components, class Domain>
struct NewEngine<Engine<Dim, T, CompFwd<Eng, Components> >, Domain>
{
typedef typename NewEngine<Eng, Domain>::Type_t NewEngine_t;
typedef Engine<NewEngine_t::dimensions, T, CompFwd<NewEngine_t, Components> > Type_t;
};
/**
* General version of engineFunctor to passes the request to
* the contained engine.
*/
template<int Dim, class T, class Eng, class Components, class EFTag>
struct EngineFunctor<Engine<Dim, T, CompFwd<Eng, Components> >, EFTag>
{
typedef typename EngineFunctor<Eng, EFTag>::Type_t Type_t;
static Type_t
apply(const Engine<Dim, T, CompFwd<Eng, Components> > &engine,
const EFTag &tag)
{
return engineFunctor(engine.elemEngine(), tag);
}
};
template <int D, class T, class E, class Comp, class Tag>
struct LeafFunctor<Engine<D, T, CompFwd<E, Comp> >, EngineView<Tag> >
{
typedef LeafFunctor<E, EngineView<Tag> > LeafFunctor_t;
typedef typename LeafFunctor_t::Type_t NewViewed_t;
typedef Engine<D, T, CompFwd<NewViewed_t, Comp> > Type_t;
static
Type_t apply(const Engine<D, T, CompFwd<E, Comp> > &engine,
const EngineView<Tag> &tag)
{
return Type_t(LeafFunctor_t::apply(engine.elemEngine(), tag),
engine.components());
}
};
template <int D, class T, class E, class Comp, class Tag>
struct LeafFunctor<Engine<D, T, CompFwd<E, Comp> >, ExpressionApply<Tag> >
{
typedef LeafFunctor<E, ExpressionApply<Tag> > LeafFunctor_t;
typedef int Type_t;
static
Type_t apply(const Engine<D, T, CompFwd<E, Comp> > &engine,
const ExpressionApply<Tag> &tag)
{
return LeafFunctor_t::apply(engine.elemEngine(), tag);
}
};
/**
* Tell contained engine that it's dirty.
*/
template<int Dim, class T, class Eng, class Components>
struct NotifyEngineWrite<Engine<Dim,T,CompFwd<Eng,Components> > >
{
inline static void
notify(const Engine<Dim,T,CompFwd<Eng,Components> > &engine)
{
typedef typename Engine<Dim, T,
CompFwd<Eng, Components> >::ElemEngine_t Engine_t;
NotifyEngineWrite<Engine_t>::notify(engine.elemEngine());
}
};
/**
* Version of EnginePatch that gets the patch from the viewed engine.
*/
template <int D, class T, class E, class Comp>
struct EngineFunctor<Engine<D, T, CompFwd<E, Comp> >, EnginePatch>
{
typedef typename EngineFunctor<E, EnginePatch>::Type_t NewViewed_t;
typedef Engine<D, T, CompFwd<NewViewed_t, Comp> > Type_t;
static
Type_t apply(const Engine<D, T, CompFwd<E, Comp> > &engine,
const EnginePatch &tag)
{
return Type_t(engineFunctor(engine.elemEngine(), tag),
engine.components());
}
};
#endif
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: ForwardingEngine.h,v $ $Author: richard $
// $Revision: 1.50 $ $Date: 2004/11/01 18:16:37 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
#ifndef LOGREADER_H
#define LOGREADER_H
#include <QThread>
#include <QDateTime>
#include <QFile>
#include <QByteArray>
#include <QSharedPointer>
#include "Globals.h"
#include HTTP_MULTI_PART_INCLUDE
#include "Network/NetworkSender.h"
#include "Log/LogFragment.h"
class HTTP_MULTI_PART_USED;
class LogReader : public QThread
{
Q_OBJECT
public:
LogReader(QString url, QString pathname, bool postFileContent,
QString id,
QDateTime from = QDateTime(), QDateTime to = QDateTime(),
QString group = QString(), QObject *parent = 0);
LogReader(QString url, QString pathname, bool postFileContent = true,
QDateTime from = QDateTime(), QDateTime to = QDateTime(),
QString group = QString(), QObject *parent = 0);
LogReader(QString url, QString pathname, bool postFileContent,
QString id,
QString group, QObject *parent = 0);
virtual ~LogReader();
bool postFileContent() const;
protected slots:
void onFragmentReady(LogFragment *fragment);
void onMultipartSent(QHttpMultiPart *multiPart, QNetworkReply *reply);
void onReplyFinished();
protected:
void processFragment(LogFragment *fragment);
void checkSending();
void sendReadyFragment();
private:
NetworkSender _sender;
LogFragment *_readyFragment, *_sendPendingFragment;
bool _lastFragment;
HTTP_MULTI_PART_USED *_multiPart;
// bool _sendPending;
bool _postFileContent;
};
#endif // LOGREADER_H
|
#ifndef FFMPEG_DEMUX_H_
#define FFMPEG_DEMUX_H_
class SavedData; // forward
class FFmpegDemuxedElementaryStream;
class AVBitStreamFilterContext;
struct AVPacket;
#define boolean Boolean
class FFmpegDemux: public Medium {
public:
static FFmpegDemux* CreateNew(UsageEnvironment& env, char const* filename,
Boolean reclaim_last_es_dies);
private:
FFmpegDemux(UsageEnvironment& env, char const *filename,
Boolean reclaim_last_es_dies);
virtual ~FFmpegDemux();
public:
Boolean InitFFmpeg();
Boolean ReinitFFmpeg();
FFmpegDemuxedElementaryStream* NewElementaryStream(u_int8_t streamIdTag,
char const* mine_type, unsigned duration);
// similar to FramedSource::getNextFrame(), except that it also
// takes a stream id tag as parameter.
void GetNextFrame(u_int8_t stream_id, unsigned char* to, unsigned maxsize,
FramedSource::afterGettingFunc* AfterGettingFunc,
void* after_getting_client_data,
FramedSource::onCloseFunc* OnCloseFunc, void* on_close_client_ata);
// similar to FramedSource::stopGettingFrames(), except that it also
// takes a stream id tag as parameter.
void StopGettingFrames(u_int8_t stream_id_tag);
// This should be called (on ourself) if the source is discovered
// to be closed (i.e., no longer readable)
static void HandleClosure(void* client_data);
// should be called before any 'seek' on the underlying source
void FlushInput();
private:
void RegisterReadInterest(u_int8_t stream_id_tag, unsigned char* to,
unsigned maxsize, FramedSource::afterGettingFunc* AfterGettingFunc,
void* after_getting_client_data,
FramedSource::onCloseFunc* OnCloseFunc, void* on_close_client_data);
Boolean UseSavedData(u_int8_t stream_id_tag, unsigned char* to,
unsigned maxsize, FramedSource::afterGettingFunc* AfterGettingFunc,
void* after_getting_client_data);
static void ContinueReadProcessing(void* client_data, unsigned char* ptr,
unsigned size, struct timeval presentation_time);
void ContinueReadProcessing();
int Parse();
int ReadOneFrame(AVPacket* packet, Boolean &has_extra_data);
int CopyData(void* dst, int dst_max_size, const void* src, int src_size);
int SaveData(int stream_id, unsigned char* srcbuf, int size,
boolean reuse_buf = False);
private:
friend class FFmpegDemuxedElementaryStream;
void NoteElementaryStreamDeletion();
private:
char const *filename_;
struct AVFormatContext *format_ctx_;
// A descriptor for each possible stream id tag:
typedef struct OutputDescriptor {
// input parameters
unsigned char* to;
unsigned max_size;
FramedSource::afterGettingFunc* AfterGettingFunc;
void* after_getting_client_data;
FramedSource::onCloseFunc* OnCloseFunc;
void* on_close_client_data;
// output parameters
unsigned frame_size;
struct timeval presentation_time;
SavedData* saved_data_head;
SavedData* saved_data_tail;
unsigned saved_data_total_size;
// status parameters
Boolean is_potentially_readable;
Boolean is_currently_active;
Boolean is_currently_awaiting_data;
int data_counts; //this should be delete
} OutputDescriptor_t;
OutputDescriptor_t output_[1024];
unsigned num_pending_reads_;
Boolean have_undelivered_data_;
Boolean reclaim_last_es_dies_; //whether delete self when last es dies
AVBitStreamFilterContext* h264bsfc;
int num_out_es_;
};
#endif /* FFMPEG_DEMUX_H_ */
|
/*
Copyright (c) 2019 Stefan Kremser
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/SimpleCLI
*/
#include "arg.h"
#include <stdlib.h> // malloc()
#include <string.h> // memcpy()
#include "comparator.h" // compare
// ===== Arg ===== //
// Constructors
arg* arg_create(const char* name, const char* default_val, unsigned int mode, unsigned int req) {
arg* a = (arg*)malloc(sizeof(arg));
a->name = name;
a->default_val = default_val;
a->val = NULL;
a->mode = mode % 3;
a->req = req % 2;
a->set = ARG_UNSET;
a->next = NULL;
return a;
}
arg* arg_create_opt(const char* name, const char* default_val) {
return arg_create(name, default_val, ARG_DEFAULT, ARG_OPT);
}
arg* arg_create_req(const char* name) {
return arg_create(name, NULL, ARG_DEFAULT, ARG_REQ);
}
arg* arg_create_opt_positional(const char* name, const char* default_value) {
return arg_create(name, default_value, ARG_POS, ARG_OPT);
}
arg* arg_create_req_positional(const char* name) {
return arg_create(name, NULL, ARG_POS, ARG_REQ);
}
arg* arg_create_flag(const char* name, const char* default_value) {
return arg_create(name, default_value, ARG_FLAG, ARG_OPT);
}
// Copy & Move Constructors
arg* arg_copy(arg* a) {
if (!a) return NULL;
arg* na = (arg*)malloc(sizeof(arg));
na->name = a->name;
na->default_val = a->default_val;
na->val = NULL;
na->mode = a->mode;
na->req = a->req;
na->set = a->set;
na->next = NULL;
if (a->val) {
na->val = (char*)malloc(strlen(a->val) + 1);
strcpy(na->val, a->val);
na->set = ARG_SET;
}
return na;
}
arg* arg_copy_rec(arg* a) {
if (!a) return NULL;
arg* na = arg_copy(a);
na->next = arg_copy_rec(a->next);
return na;
}
arg* arg_move(arg* a) {
if (!a) return NULL;
arg* na = (arg*)malloc(sizeof(arg));
na->name = a->name;
na->default_val = a->default_val;
na->val = a->val;
na->mode = a->mode;
na->req = a->req;
na->set = a->set;
na->next = NULL;
a->val = NULL;
a->set = ARG_UNSET;
return na;
}
arg* arg_move_rec(arg* a) {
if (!a) return NULL;
arg* na = arg_move(a);
na->next = arg_move_rec(a->next);
return na;
}
// Destructors
arg* arg_destroy(arg* a) {
if (a) {
arg_reset(a);
free(a);
}
return NULL;
}
arg* arg_destroy_rec(arg* a) {
if (a) {
arg_destroy_rec(a->next);
arg_destroy(a);
}
return NULL;
}
// Reset
void arg_reset(arg* a) {
if (a) {
if (a->val) {
free(a->val);
a->val = NULL;
}
a->set = ARG_UNSET;
}
}
void arg_reset_rec(arg* a) {
if (a) {
arg_reset(a);
arg_reset_rec(a->next);
}
}
// Comparisons
int arg_name_equals(arg* a, const char* name, size_t name_len, int case_sensetive) {
if (!a) return ARG_NAME_UNEQUALS;
return compare(name, name_len, a->name, case_sensetive) == COMPARE_EQUAL ? ARG_NAME_EQUALS : ARG_NAME_UNEQUALS;
}
int arg_equals(arg* a, arg* b, int case_sensetive) {
if (a == b) return ARG_NAME_EQUALS;
if (!a || !b) return ARG_NAME_UNEQUALS;
return arg_name_equals(a, b->name, strlen(b->name), case_sensetive);
}
// Getter
const char* arg_get_value(arg* a) {
if (a) {
if (a->val) return a->val;
if (a->default_val) return a->default_val;
}
return "";
}
// Setter
int arg_set_value(arg* a, const char* val, size_t val_size) {
if (a) {
if (val && (val_size > 0)) {
if (a->set) arg_reset(a);
a->val = (char*)malloc(val_size + 1);
size_t i = 0;
size_t j = 0;
int escaped = 0;
int in_quote = 0;
while (i < val_size) {
if ((val[i] == '\\') && (escaped == 0)) {
escaped = 1;
} else if ((val[i] == '"') && (escaped == 0)) {
in_quote = !in_quote;
} else {
a->val[j++] = val[i];
escaped = 0;
}
++i;
}
if (in_quote) {
free(a->val);
a->val = NULL;
return ARG_VALUE_FAIL;
}
while (j <= val_size) {
a->val[j++] = '\0';
}
}
a->set = ARG_SET;
return ARG_VALUE_SUCCESS;
}
return ARG_VALUE_FAIL;
}
|
/**
*
* @file B3MSC1170A.hpp
* @authors Yasuo Hayashibara
* Naoki Takahashi
*
**/
#pragma once
#include "SerialServoMotor.hpp"
namespace IO {
namespace Device {
namespace Actuator {
namespace ServoMotor {
class B3MSC1170A final : public SerialServoMotor {
public :
B3MSC1170A(RobotStatus::InformationPtr &);
B3MSC1170A(const ID &, RobotStatus::InformationPtr &);
~B3MSC1170A();
static std::string get_key();
void ping() override final,
enable_torque(const bool &flag) override final,
write_gain(const WriteValue &p, const WriteValue &i, const WriteValue &d) override final,
write_angle(const float °ree) override final;
private :
void command_controller_access_assertion();
void write_gain_packet(const ID &, const WriteValue &p, const WriteValue &i, const WriteValue &d);
SendPacket create_ping_packet(const ID &),
create_enable_torque_packet(const ID &, const bool &),
create_write_angle_packet(const ID &, const float °ree);
SendPacket create_write_p_gain_packet(const ID &, const WriteValue &),
create_write_i_gain_packet(const ID &, const WriteValue &),
create_write_d_gain_packet(const ID &, const WriteValue &);
};
}
}
}
}
|
#include <bits/stdc++.h>
using namespace std;
int n;
bool a[100];
void show() {
for(int i = 1; i<=n;++i){
if(a[i])
cout << i;
}
cout << endl;
}
void recurse(int u){
if (u == n+1){
show();
return;
}
a[u] = 0;
recurse(u + 1);
a[u] = 1;
recurse(u + 1);
}
int main(){
cin >> n;
recurse(1);
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Security.Authentication.Identity.0.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Security::Authentication::Identity {
struct __declspec(uuid("38321acc-672b-4823-b603-6b3c753daf97")) __declspec(novtable) IEnterpriseKeyCredentialRegistrationInfo : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_TenantId(hstring * value) = 0;
virtual HRESULT __stdcall get_TenantName(hstring * value) = 0;
virtual HRESULT __stdcall get_Subject(hstring * value) = 0;
virtual HRESULT __stdcall get_KeyId(hstring * value) = 0;
virtual HRESULT __stdcall get_KeyName(hstring * value) = 0;
};
struct __declspec(uuid("83f3be3f-a25f-4cba-bb8e-bdc32d03c297")) __declspec(novtable) IEnterpriseKeyCredentialRegistrationManager : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetRegistrationsAsync(Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationInfo>> ** value) = 0;
};
struct __declspec(uuid("77b85e9e-acf4-4bc0-bac2-40bb46efbb3f")) __declspec(novtable) IEnterpriseKeyCredentialRegistrationManagerStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Current(Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationManager ** value) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationInfo> { using default_interface = Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationInfo; };
template <> struct traits<Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationManager> { using default_interface = Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationManager; };
}
namespace Windows::Security::Authentication::Identity {
template <typename D>
struct WINRT_EBO impl_IEnterpriseKeyCredentialRegistrationInfo
{
hstring TenantId() const;
hstring TenantName() const;
hstring Subject() const;
hstring KeyId() const;
hstring KeyName() const;
};
template <typename D>
struct WINRT_EBO impl_IEnterpriseKeyCredentialRegistrationManager
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationInfo>> GetRegistrationsAsync() const;
};
template <typename D>
struct WINRT_EBO impl_IEnterpriseKeyCredentialRegistrationManagerStatics
{
Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationManager Current() const;
};
}
namespace impl {
template <> struct traits<Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationInfo>
{
using abi = ABI::Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationInfo;
template <typename D> using consume = Windows::Security::Authentication::Identity::impl_IEnterpriseKeyCredentialRegistrationInfo<D>;
};
template <> struct traits<Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationManager>
{
using abi = ABI::Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationManager;
template <typename D> using consume = Windows::Security::Authentication::Identity::impl_IEnterpriseKeyCredentialRegistrationManager<D>;
};
template <> struct traits<Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationManagerStatics>
{
using abi = ABI::Windows::Security::Authentication::Identity::IEnterpriseKeyCredentialRegistrationManagerStatics;
template <typename D> using consume = Windows::Security::Authentication::Identity::impl_IEnterpriseKeyCredentialRegistrationManagerStatics<D>;
};
template <> struct traits<Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationInfo>
{
using abi = ABI::Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationInfo;
static constexpr const wchar_t * name() noexcept { return L"Windows.Security.Authentication.Identity.EnterpriseKeyCredentialRegistrationInfo"; }
};
template <> struct traits<Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationManager>
{
using abi = ABI::Windows::Security::Authentication::Identity::EnterpriseKeyCredentialRegistrationManager;
static constexpr const wchar_t * name() noexcept { return L"Windows.Security.Authentication.Identity.EnterpriseKeyCredentialRegistrationManager"; }
};
}
}
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
set<int> s;
int n, a;
long long int b;
cin >> n;
for(int i=0; i<n; i++) {
cin >> a;
cin >> b;
switch(a) {
case 1:
s.insert(b);
break;
case 2:
s.erase(b);
break;
case 3:
set<int>::iterator itr = s.find(b);
if(itr == s.end()) cout << "No" << endl;
else cout << "Yes" << endl;
break;
}
}
return 0;
}
|
#include "reqcompilemacro.h"
using std::unique_ptr;
using std::string;
#include <llvm/IR/Module.h>
using namespace llvm;
#include "defconstint.h"
ReqCompileMacro::ReqCompileMacro(const string& name)
:ReqCompile(name), snippet_name(snippet_prefix + name)
{
}
void ReqCompileMacro::addCodeTo(string &code) const
{
code += "auto ";
code += snippet_name;
code += " = ";
code += name();
code += ";\n";
}
unique_ptr<Def> ReqCompileMacro::makeDef(const Module &module) const
{
auto gv = module.getNamedGlobal(snippet_name);
if (!gv) return nullptr;
if (!gv->hasInitializer()) return nullptr;
auto init = gv->getInitializer();
auto type = init->getType();
if (type->isIntegerTy())
{
auto apint = init->getUniqueInteger();
auto bits = apint.getBitWidth();
if (bits <= 64)
{
auto value = apint.getSExtValue();
return unique_ptr<Def>(new DefConstInt(value, bits));
}
}
return nullptr;
}
|
/****************************************************************************
**
** Copyright (C) 2009 Du Hui.
**
****************************************************************************/
#include "qwinserialcomm.h"
bool WinSerialComm::SetPortSettings(const PORTSETTINGS* portSettings)
{
if ( !IsOpen() )
{
return false;
}
if ( portSettings == NULL )
{
BuildDefaultSettings();
}
else
{
if ( portSettings->SettingsValidMask & BUFFERSIZE_VALID_MASK )
{
_InBufferSize = portSettings->BufferSize.InputBufferSize;
_OutBufferSeze = portSettings->BufferSize.OutputBufferSize;
}
if ( portSettings->SettingsValidMask & TIMEOUTS_VALID_MASK )
{
_CO.ReadIntervalTimeout = portSettings->Timeout.ReadIntervalTimeout;
_CO.ReadTotalTimeoutMultiplier = portSettings->Timeout.ReadTotalTimeoutMultiplier;
_CO.ReadTotalTimeoutConstant = portSettings->Timeout.ReadTotalTimeoutConstant;
_CO.WriteTotalTimeoutMultiplier = portSettings->Timeout.WriteTotalTimeoutMultiplier;
_CO.WriteTotalTimeoutConstant = portSettings->Timeout.WriteTotalTimeoutConstant;
}
if ( portSettings->SettingsValidMask &PROPERTY_VALID_MASK )
{
BuildDcbFrom(portSettings->Properties);
}
}
return ::SetCommState(_hCommHandle, &_DCB)
&& ::SetCommTimeouts(_hCommHandle, &_CO)
&& ::SetupComm(_hCommHandle, _InBufferSize, _OutBufferSeze);
}
bool WinSerialComm::GetPortSettings(PORTSETTINGS &portSettings)
{
if ( !IsOpen() )
{
return false;
}
portSettings.SettingsValidMask = BUFFERSIZE_VALID_MASK;
portSettings.BufferSize.InputBufferSize = _InBufferSize;
portSettings.BufferSize.OutputBufferSize =_OutBufferSeze;
bool timeoutValid = ::GetCommTimeouts(_hCommHandle, &_CO);
if ( timeoutValid )
{
portSettings.SettingsValidMask |= TIMEOUTS_VALID_MASK;
portSettings.Timeout.ReadIntervalTimeout = _CO.ReadIntervalTimeout;
portSettings.Timeout.ReadTotalTimeoutMultiplier = _CO.ReadTotalTimeoutMultiplier;
portSettings.Timeout.ReadTotalTimeoutConstant = _CO.ReadTotalTimeoutConstant;
portSettings.Timeout.WriteTotalTimeoutMultiplier = _CO.WriteTotalTimeoutMultiplier;
portSettings.Timeout.WriteTotalTimeoutConstant = _CO.WriteTotalTimeoutConstant;
}
bool stateValid = ::GetCommState(_hCommHandle, &_DCB);
if ( stateValid )
{
portSettings.SettingsValidMask |= PROPERTY_VALID_MASK;
portSettings.Properties.BaudRate = _DCB.BaudRate;
portSettings.Properties.DataBits = _DCB.ByteSize;
if ( _DCB.fOutxCtsFlow == TRUE)
{
portSettings.Properties.FlowControl = FLOW_TYPE_HARDWARE;
}
else
{
portSettings.Properties.FlowControl = ( _DCB.fInX == TRUE ) ? FLOW_TYPE_XONXOFF : FLOW_TYPE_OFF;
}
portSettings.Properties.Parity = _DCB.Parity;
portSettings.Properties.StopBits = _DCB.StopBits;
}
return true;
}
bool WinSerialComm::open ( const wchar_t * comport,
const PORTSETTINGS* portSettings,
QIODevice::OpenMode mode )
{
wcscpy( _szComDeviceName, comport );
if( !OpenCommPort() )
return false;
if (!SetPortSettings(portSettings))
{
return false;
}
if(!::PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ))
return false;
_SettingAvailable = true;
return true;
}
bool WinSerialComm::reopen ()
{
if (!_SettingAvailable)
{
return false;
}
if( !OpenCommPort() )
return false;
if ( !::SetCommState(_hCommHandle, &_DCB)
|| !::SetCommTimeouts(_hCommHandle, &_CO)
|| !::SetupComm(_hCommHandle, _InBufferSize, _OutBufferSeze) )
{
return false;
}
if(!::PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ))
return false;
return true;
}
// Sync Read Comm port
DWORD WinSerialComm::ReadSync(LPVOID Buffer, DWORD dwBufferLength)
{
if(!IsOpen())
return 0;
DWORD dwError;
if(::ClearCommError(_hCommHandle, &dwError, NULL) && dwError > 0)
{
::PurgeComm(_hCommHandle, PURGE_RXABORT | PURGE_RXCLEAR);
return 0;
}
DWORD uReadLength = 0;
::ReadFile(_hCommHandle, Buffer, dwBufferLength, &uReadLength, NULL);
return uReadLength;
}
// Sync Write Comm port
DWORD WinSerialComm::WriteSync(const void* Buffer, DWORD dwBufferLength)
{
if(!IsOpen())
return 0;
DWORD dwError;
if(::ClearCommError(_hCommHandle, &dwError, NULL) && dwError > 0)
::PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_TXCLEAR);
unsigned long uWriteLength = 0;
::WriteFile(_hCommHandle, Buffer, dwBufferLength, &uWriteLength, NULL);
return uWriteLength;
}
// Close Comm port, and related thread
void WinSerialComm::Close()
{
if(IsOpen())
{
PurgeComm(_hCommHandle, PURGE_TXABORT | PURGE_TXCLEAR);
::CloseHandle(_hCommHandle);
_hCommHandle = INVALID_HANDLE_VALUE;
}
}
// Not support in nonoverlapped IO
bool WinSerialComm::WaitForBytesWritten ( int msecs )
{
return true;
}
// Not support in nonoverlapped IO
bool WinSerialComm::WaitForReadyRead ( int msecs )
{
return true;
}
// Init
void WinSerialComm::Init()
{
memset(_szComDeviceName, 0, sizeof(_szComDeviceName) );
BuildDefaultDcb();
_hCommHandle = INVALID_HANDLE_VALUE;
}
// Destroy resource
void WinSerialComm::Destroy()
{
}
// Open Comm port
bool WinSerialComm::OpenCommPort()
{
if(IsOpen())
Close();
_hCommHandle = ::CreateFile(
_szComDeviceName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
return IsOpen();
}
void WinSerialComm::BuildDefaultDcb()
{
memset( &_DCB, 0, sizeof(_DCB) );
_DCB.DCBlength = sizeof(_DCB);
_DCB.BaudRate = CBR_115200;
_DCB.fBinary = TRUE;
_DCB.Parity = NOPARITY;
_DCB.StopBits = ONESTOPBIT;
_DCB.ByteSize = 8;
_DCB.fOutxCtsFlow=FALSE;
_DCB.fRtsControl=RTS_CONTROL_DISABLE;
_DCB.fInX=FALSE;
_DCB.fOutX=FALSE;
}
void WinSerialComm::BuildDcbFrom(const PORTPROPERTY & property)
{
// Baud rate
switch (property.BaudRate)
{
// Default and windows not support baud rate set to 115200
case BAUD_RATE_TYPE_50:
case BAUD_RATE_TYPE_75:
case BAUD_RATE_TYPE_134:
case BAUD_RATE_TYPE_150:
case BAUD_RATE_TYPE_200:
case BAUD_RATE_TYPE_1800:
case BAUD_RATE_TYPE_76800:
default:
case BAUD_RATE_TYPE_115200:
_DCB.BaudRate=CBR_115200;
break;
case BAUD_RATE_TYPE_110:
_DCB.BaudRate=CBR_110;
break;
case BAUD_RATE_TYPE_300:
_DCB.BaudRate=CBR_300;
break;
case BAUD_RATE_TYPE_600:
_DCB.BaudRate=CBR_600;
break;
case BAUD_RATE_TYPE_1200:
_DCB.BaudRate=CBR_1200;
break;
case BAUD_RATE_TYPE_2400:
_DCB.BaudRate=CBR_2400;
break;
case BAUD_RATE_TYPE_4800:
_DCB.BaudRate=CBR_4800;
break;
case BAUD_RATE_TYPE_9600:
_DCB.BaudRate=CBR_9600;
break;
case BAUD_RATE_TYPE_14400:
_DCB.BaudRate=CBR_14400;
break;
case BAUD_RATE_TYPE_19200:
_DCB.BaudRate=CBR_19200;
break;
case BAUD_RATE_TYPE_38400:
_DCB.BaudRate=CBR_38400;
break;
case BAUD_RATE_TYPE_56000:
_DCB.BaudRate=CBR_56000;
break;
case BAUD_RATE_TYPE_57600:
_DCB.BaudRate=CBR_57600;
break;
case BAUD_RATE_TYPE_128000:
_DCB.BaudRate=CBR_128000;
break;
case BAUD_RATE_TYPE_256000:
_DCB.BaudRate=CBR_256000;
break;
}
// data bits and stop bits
if ((property.StopBits==STOP_BITS_TYPE_2 && property.DataBits==DATA_BITS_TYPE_5)
|| (property.StopBits==STOP_BITS_TYPE_1_5 && property.DataBits!=DATA_BITS_TYPE_5)
|| property.DataBits!=DATA_BITS_TYPE_4 )
{
_DCB.ByteSize = 8;
_DCB.StopBits = 1;
}
else
{
_DCB.ByteSize = property.DataBits;
_DCB.StopBits = property.StopBits;
}
switch(property.FlowControl)
{
/*no flow control*/
case FLOW_TYPE_OFF:
_DCB.fOutxCtsFlow=FALSE;
_DCB.fRtsControl=RTS_CONTROL_DISABLE;
_DCB.fInX=FALSE;
_DCB.fOutX=FALSE;
break;
/*software (XON/XOFF) flow control*/
case FLOW_TYPE_XONXOFF:
_DCB.fOutxCtsFlow=FALSE;
_DCB.fRtsControl=RTS_CONTROL_DISABLE;
_DCB.fInX=TRUE;
_DCB.fOutX=TRUE;
break;
case FLOW_TYPE_HARDWARE:
_DCB.fOutxCtsFlow=TRUE;
_DCB.fRtsControl=RTS_CONTROL_HANDSHAKE;
_DCB.fInX=FALSE;
_DCB.fOutX=FALSE;
break;
}
_DCB.Parity=(unsigned char)property.Parity;
switch ( property.Parity )
{
//even parity, fall through
case PARITY_TYPE_EVEN:
//odd parity, fall through
case PARITY_TYPE_ODD:
//space parity, fall through
case PARITY_TYPE_SPACE:
//mark parity - WINDOWS ONLY, fall through
case PARITY_TYPE_MARK:
_DCB.fParity=TRUE;
break;
//no parity, fall through
case PARITY_TYPE_NONE:
default:
_DCB.fParity=FALSE;
break;
}
}
|
#include <iostream>
#include "connnode_loginsrv.h"
#include "../scomm/msgid.h"
ConnNodeLoginSrv::ConnNodeLoginSrv():PassiveConnNodeBase() {
}
ConnNodeLoginSrv::~ConnNodeLoginSrv() {
}
ConnNodeLoginSrv& ConnNodeLoginSrv::operator=(const ConnNodeLoginSrv&)
{
return *this;
}
int ConnNodeLoginSrv::DispatchMsg(MsgHead *head, AuxData *aux_data) {
std::cout<<__FILE__<<":"<<__LINE__<<std::endl;
uint16_t msgid = head->msgid;
std::cout<<"msgid:"<<msgid<<std::endl;
if (0 == msgid) {
return -1;
}
switch (msgid) {
case 1000: {
}
break;
default:
printf("%s:%d err msgid:%u", __FUNCTION__, __LINE__, msgid);
return -1;
}
return 0;
}
|
#ifndef ENVIRONMENT_H_
#define ENVIRONMENT_H_
#include "Files.h"
#include "Commands.h"
#include <string>
#include <vector>
using namespace std;
class Environment {
private:
vector<BaseCommand*> commandsHistory;
FileSystem fs;
public:
Environment();
void start();
FileSystem& getFileSystem(); // Get a reference to the file system
void addToHistory(BaseCommand *command); // Add a new command to the history
const vector<BaseCommand*>& getHistory() const; // Return a reference to the history of commands
BaseCommand* detectCommand(string input);
Environment(const Environment &other); //Copy Constructor
Environment& operator=(const Environment& other);// Copy Assignment Operator
Environment(Environment &&other);// Move Constructor
Environment& operator=(Environment&& other);//Move assignment operator
~Environment();//Destructor
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
int findceil(vector<int>& arr,int index,int n)
{
int min_index = index+1;
int min_value = arr[index+1];
for(int i=index+1;i<n;i++)
{
if(arr[i] > arr[index])
{
if(arr[i] < min_value)
{
min_value = arr[i];
min_index = i;
}
}
}
return min_index;
}
int print_permutations(vector<int>& arr,int n)
{
int done = 0;
int max_value = INT_MIN;
while(done==0)
{
int index=-1;
for(int i=n-2;i>=0;i--)
{
if(arr[i] < arr[i+1])
{
index = i;
break;
}
}
if(index==-1)
{
done=1;
break;
}
int ceil_index = findceil(arr,index,n);
int temp = arr[index];
arr[index] = arr[ceil_index];
arr[ceil_index] = temp;
vector<int> :: iterator it=arr.begin();
for(int i=0;i<=index;i++)
{
it++;
}
reverse(it,arr.end());
int sum = 0;
for(int i=0;i<n;i++)
{
if(i!=n-1)
{
sum+=abs(arr[i]-arr[i+1]);
}
else
{
sum+=abs(arr[i]-arr[0]);
}
}
sum = max(sum,max_value);
}
return max_value;
}
int solve(vector<int>& arr,int n)
{
sort(arr.begin(),arr.end());
int i=0;
int j=n-1;
vector<int> output;
int sum = 0;
while(i<=j)
{
output.push_back(arr[i]);
output.push_back(arr[j]);
i+=1;
j-=1;
}
for(int i=0;i<n;i++)
{
if(i!=n-1)
{
sum+=abs(output[i]-output[i+1]);
}
else
{
sum+=abs(output[i]-output[0]);
}
}
return sum;
}
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for(int i=0;i<n;i++)
cin >> arr[i];
cout << solve(arr,n) << endl;
cout << print_permutations(arr,n) << endl;
return 0;
}
|
#pragma once
#include <memory>
#include "CIL/defs.h"
#include "CIL/io/bitstream.h"
#include "CIL/mat/mat.h"
namespace cil {
class BaseImageDecoder;
class BaseImageEncoder;
typedef std::shared_ptr<BaseImageEncoder> ImageEncoder;
typedef std::shared_ptr<BaseImageDecoder> ImageDecoder;
///////////////////////////////// base class for decoders
///////////////////////////
class BaseImageDecoder {
public:
BaseImageDecoder();
virtual ~BaseImageDecoder() {}
int width() const {
return m_width;
}
int height() const {
return m_height;
}
virtual int type() const {
return m_type;
}
virtual bool setSource(const String& filename);
virtual bool setSource(const Mat& buf);
virtual int setScale(const int& scale_denom);
virtual bool readHeader() = 0;
virtual bool readData(Mat& img) = 0;
/// Called after readData to advance to the next page, if any.
virtual bool nextPage() {
return false;
}
virtual size_t signatureLength() const;
virtual bool checkSignature(const String& signature) const;
virtual ImageDecoder newDecoder() const;
protected:
int m_width; // width of the image ( filled by readHeader )
int m_height; // height of the image ( filled by readHeader )
int m_type;
int m_scale_denom;
String m_filename;
String m_signature;
Mat m_buf;
bool m_buf_supported;
};
///////////////////////////// base class for encoders
///////////////////////////////
class BaseImageEncoder {
public:
BaseImageEncoder();
virtual ~BaseImageEncoder() {}
virtual bool isFormatSupported(int depth) const;
virtual bool setDestination(const String& filename);
virtual bool setDestination(std::vector<uchar>& buf);
virtual bool write(const Mat& img, const std::vector<int>& params) = 0;
virtual String getDescription() const;
virtual ImageEncoder newEncoder() const;
virtual void throwOnEror() const;
protected:
String m_description;
String m_filename;
std::vector<uchar>* m_buf;
bool m_buf_supported;
String m_last_error;
};
} // namespace cil
|
#include"syscall.h"
/* Address space control operations: Exit, Exec, and Join */
/* This user program is done (status = 0 means exited normally). */
void Exit(int status)
{
printf("stub exit\n");
}
/* Run the executable, stored in the Nachos file "name", and return the
* address space identifier
*/
SpaceId Exec(char *name)
{
printf("stub exec\n");
}
/* Only return once the the user program "id" has finished.
* Return the exit status.
*/
int Join(SpaceId id)
{
kernel->currentThread->Join(findThread(NULL,id));
return 0;
}
/* File system operations: Create, Open, Read, Write, Close
* These functions are patterned after UNIX -- files represent
* both files *and* hardware I/O devices.
*
* If this assignment is done before doing the file system assignment,
* note that the Nachos file system has a stub implementation, which
* will work for the purposes of testing out these routines.
*/
/* when an address space starts up, it has two open files, representing
* keyboard input and display output (in UNIX terms, stdin and stdout).
* Read and Write can be used directly on these, without first opening
* the console device.
*/
/* Fork a thread to run a procedure ("func") in the *same* address space
* as the current thread.
*/
void Fork(void (*func)())
{
printf("stub fork\n");
}
/* Yield the CPU to another runnable thread, whether in this address space
* or not.
*/
void Yield()
{
printf("stub yield\n");
}
void Halt()
{
printf("stub halt\n");
return;
}
|
/*************************************************************
Author : qmeng
MailTo : qmeng1128@163.com
QQ : 1163306125
Blog : http://blog.csdn.net/Mq_Go/
Create : 2018-03-17 17:53:09
Version: 1.0
**************************************************************/
#include <cstdio>
#include <iostream>
#include <set>
using namespace std;
int main(){
int n,k,temp;
cin >> n;
for(int i = 0 ; i < n ; i++){
bool flag = true;
set<int> s1,s2,s3;
scanf("%d",&k);
int j;
for(j = 1 ; j <= k ; j++){
scanf("%d",&temp);
s1.insert(j+temp);
s2.insert(j-temp);
s3.insert(temp);
if(s1.size() != j || s2.size()!= j || s3.size() != j)flag = false;
}
if(flag)printf("YES\n");
else printf("NO\n");
}
return 0;
}
|
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <set>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/* Solution */
const int MOD = 1000000007;
class Solution {
public:
int getLastMoment(int n, vector<int>& left, vector<int>& right)
{
int cand1 = left.size() > 0 ? *max_element(left.begin(), left.end()) : 0;
int cand2 = right.size() > 0 ? n - *min_element(right.begin(), right.end()) : 0;
return max(cand1, cand2);
}
};
int main()
{
Solution sol;
// vector<int> left = {4, 3};
// vector<int> right = {0, 1};
// int n = 4;
vector<int> left = {};
vector<int> right = {0,1,2,3,4,5,6,7};
int n = 7;
cout << sol.getLastMoment(n, left, right) << endl;
}
|
#include "PersonalInformation.h"
PersonalInformation::PersonalInformation(string filepath)
{
InitFromFile(filepath);
Check();
}
PersonalInformation::~PersonalInformation()
{
}
int PersonalInformation::GetHeroNumber()
{
return heroexperience.size();
}
int PersonalInformation::GetOneHeroExperience(int heroIndex)
{
if (heroIndex > -1 && heroIndex < heroexperience.size())
return heroexperience[heroIndex];
else
return 0;
}
int PersonalInformation::InitFromFile(string filepath)
{
ifstream perfile(filepath);
if (!perfile.is_open())
return 0;
if (!heroexperience.empty())
heroexperience.clear();
std::string heroestr;
int heroeint;
while (getline(perfile, heroestr))
{
if (heroestr.empty())
continue;
heroeint = stringToNum<int>(heroestr);
heroexperience.push_back(heroeint);
}
return 0;
}
int PersonalInformation::Check()
{
if (heroexperience.size() != HERO_COUNT)
cout << "Warnning!!! input hero count : " << heroexperience.size() << ", is not equal to default count:" << HERO_COUNT << endl;
return 0;
}
|
/*
* apds9960.h
*
* Created on: Jan 8, 2021
* Author: ap7u5
*/
#ifndef SRC_APDS9960_H_
#define SRC_APDS9960_H_
#include <cstdint>
#include "apds9960_enum.h"
template <int (*i2c_write)(uint8_t* buf, uint32_t len), int (*i2c_read)(uint8_t* buf, uint32_t len)>
class APDS9960 {
private:
uint8_t readBuffer[1];
uint8_t writeBuffer[2];
uint8_t getRegisterValue(uint8_t addr) {
// Zu lesendes Register setzen
readBuffer[0] = addr;
i2c_write(readBuffer, 1);
// Wert aus Register lesen
i2c_read(readBuffer, 1);
return *readBuffer;
}
void setRegister(uint8_t addr, uint8_t value) {
writeBuffer[0] = addr;
writeBuffer[1] = value;
i2c_write(writeBuffer, 2);
}
public:
APDS9960(): readBuffer{0}, writeBuffer{0} {
}
void init() {
setRegister(APDS9960RegisterEnable, 0);
}
void powerOn() {
uint8_t enableValue = getRegisterValue(REGISTERS::ENABLE);
enableValue |= CONTROL::POWER_ON;
setRegister(REGISTERS::ENABLE, enableValue);
}
void proximityOn() {
uint8_t enableValue = getRegisterValue(REGISTERS::ENABLE);
enableValue |= CONTROL::PROXIMITY_ON;
setRegister(REGISTERS::ENABLE, enableValue);
}
void alsOn() {
uint8_t enableValue = getRegisterValue(REGISTERS::ENABLE);
enableValue |= CONTROL::ALS_ON;
setRegister(REGISTERS::ENABLE, enableValue);
}
uint8_t getProximityData() {
return getRegisterValue(REGISTERS::PROXIMITY_DATA);
}
uint16_t getAlsClearData() {
uint16_t result = getRegisterValue(REGISTERS::CLEAR_DATA_LOW);
result |= getRegisterValue(REGISTERS::CLEAR_DATA_HIGH) << 8;
return result;
}
};
#endif /* SRC_APDS9960_H_ */
|
#include<bits/stdc++.h>
using namespace std;
int main() { long long m,n,i,k,ans,l; while(cin>>m>>n) { ans=0; for( i=1;i<=m;i++) {ans+=(n+(i%5) )/5;} cout<<ans<<endl; }}
|
/*!
* \file KaiXinApp_Repaste_Vote.cpp
* \author huxianxiang@GoZone
* \date 2010-10-6
* \brief 解析与UI: 转贴的评论投票
*
* \ref CopyRight
* =======================================================================<br>
* Copyright ? 2010-2012 GOZONE <br>
* All Rights Reserved.<br>
* The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br>
* =======================================================================<br>
*/
#include "KaiXinAPICommon.h"
#if(LCD_SIZE == LCD_HVGA )
#define KAIXIN_REPASTE_VOTE_TAG_MAX_WIDTH (90)
#define KAIXIN_REPASTE_VOTE_TAG_HEIGHT (24)
#define REPASTE_TAG_OFFSETX (2)
#define REPASTE_TAG_OFFSETY (2)
#elif(LCD_SIZE == LCD_WVGA )
#define KAIXIN_REPASTE_VOTE_TAG_MAX_WIDTH (160)
#define KAIXIN_REPASTE_VOTE_TAG_HEIGHT (30)
#define REPASTE_TAG_OFFSETX (3)
#define REPASTE_TAG_OFFSETY (3)
#endif
//:TODO:
/*标签颜色表*/
static ColorRefType Repaste_tag_Clolor[KAIXIN_REPASTE_VOTE_TAG_MAX_NUM] =
{
RGB(231, 85, 85),
RGB(213, 81, 81),
RGB(195, 78, 78),
RGB(177, 74, 74),
RGB(159, 71, 71),
RGB(141, 68, 68),
RGB(123, 65, 65),
RGB(118, 118, 118),
RGB(132, 132, 132),
RGB(145, 145, 145),
RGB(159, 159, 159),
RGB(172, 172, 172),
RGB(187, 187, 187),
RGB(200, 200, 200),
RGB(200, 200, 200),
};
void* KaiXinAPI_PostVote_JsonParse(char *text)
{
cJSON *json;
cJSON *pTemp0;
tResponsePostVote* Response = new tResponsePostVote;
memset(Response, 0 , sizeof(tResponsePostVote));
json = cJSON_Parse(text);
pTemp0 = cJSON_GetObjectItem(json,"ret");
if (pTemp0)
{
Response->ret = pTemp0->valueint;
}
//Success
if(Response->ret == 1)
{
pTemp0 = cJSON_GetObjectItem(json, "uid");
if(pTemp0)
{
STRCPY_Ex(Response->uid, pTemp0->valuestring);
}
pTemp0 = cJSON_GetObjectItem(json, "repaste");
if(pTemp0)
{
int nSize1 = 0, i = 0;
nSize1 = cJSON_GetArraySize(pTemp0);
Response->nSize_repaste = nSize1;
if( nSize1 != 0 )
{
Response->repaste = NULL;
Response->repaste = (PostVote_repaste*) malloc(sizeof( PostVote_repaste ) * nSize1 );
memset(Response->repaste, 0 , sizeof(PostVote_repaste) * nSize1 );
}
for ( i = 0; i < nSize1; i++ )
{
cJSON *Item1 = NULL, *pTemp1 = NULL;
Item1 = cJSON_GetArrayItem(pTemp0,i);
pTemp1 = cJSON_GetObjectItem(Item1, "ret");
if(pTemp1)
{
Response->repaste[i].ret = pTemp1->valueint;
}
pTemp1 = cJSON_GetObjectItem(Item1, "uid");
if(pTemp1)
{
Response->repaste[i].uid = pTemp1->valueint;
}
}
}
}
else
{
pTemp0 = cJSON_GetObjectItem(json, "errno");
if(pTemp0)
{
Response->ErrorNo = pTemp0->valueint;
}
pTemp0 = cJSON_GetObjectItem(json, "error");
if(pTemp0)
{
STRCPY_Ex(Response->ErrorInfo, pTemp0->valuestring);
}
}
cJSON_Delete(json);
return Response;
}
// 构造函数
TRepaste_VoteForm::TRepaste_VoteForm(TApplication* pApp):TWindow(pApp)
{
VoteType = KX_REPASTE_VOTE_TYPE_LIST;
nAPIHandle = KX_RefreshVote;
Create(APP_KA_ID_Repaste_Vote_Form);
}
TRepaste_VoteForm::TRepaste_VoteForm(TApplication* pApp, RepasteVoteType nType, Boolean bNew):TWindow(pApp)
{
VoteType = nType;
switch(nType)
{
case KX_REPASTE_VOTE_TYPE_LIST:
nAPIHandle = KX_RefreshVote;
Create(APP_KA_ID_Repaste_Vote_Form);
if(bNew == TRUE)
this->SetWindowMovieMode(TG3_WINDOW_MOVIE_MODE_DEFAULT, TG3_WINDOW_MOVIE_MODE_DEFAULT);
else
this->SetWindowMovieMode(TG3_WINDOW_MOVIE_MODE_NONE, TG3_WINDOW_MOVIE_MODE_DEFAULT);
break;
case KX_REPASTE_VOTE_TYPE_TAG:
nAPIHandle = KX_RefreshTag;
Create(APP_KA_ID_Repaste_Vote_tag_Form);
if(bNew == TRUE)
this->SetWindowMovieMode(TG3_WINDOW_MOVIE_MODE_DEFAULT, TG3_WINDOW_MOVIE_MODE_DEFAULT);
else
this->SetWindowMovieMode(TG3_WINDOW_MOVIE_MODE_NONE, TG3_WINDOW_MOVIE_MODE_DEFAULT);
break;
default:
break;
}
}
// 析构函数
TRepaste_VoteForm::~TRepaste_VoteForm(void)
{
}
// 窗口事件处理
Boolean TRepaste_VoteForm::EventHandler(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled = FALSE;
switch (pEvent->eType)
{
case EVENT_WinInit:
{
_OnWinInitEvent(pApp, pEvent);
bHandled = TRUE;
break;
}
case EVENT_WinClose:
{
_OnWinClose(pApp, pEvent);
break;
}
case EVENT_WinEraseClient:
{
TDC dc(this);
WinEraseClientEventType *pEraseEvent = reinterpret_cast< WinEraseClientEventType* >( pEvent );
TRectangle rc(pEraseEvent->rc);
TRectangle rcBack(5, 142, 310, 314);
this->GetBounds(&rcBack);
// 刷主窗口背景色
dc.SetBackColor(RGB_COLOR_WHITE);
// 擦除
dc.EraseRectangle(&rc, 0);
dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_title_bg), 0, 0, SCR_W,
GUI_API_STYLE_ALIGNMENT_LEFT);
//dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_bottom_bg), 0, rcBack.Bottom()-68,
//320, GUI_API_STYLE_ALIGNMENT_LEFT|GUI_API_STYLE_ALIGNMENT_TOP);
pEraseEvent->result = 1;
bHandled = TRUE;
}
break;
case EVENT_CtrlSelect:
{
bHandled = _OnCtrlSelectEvent(pApp, pEvent);
break;
}
case MSG_DL_THREAD_PROCESS:
{
NotifyMsgDataType notifyData;
Sys_GetMessageBody((MESSAGE_t *)pEvent, ¬ifyData, sizeof(NotifyMsgDataType));
bHandled = TRUE;
}
break;
case MSG_DL_THREAD_NOTIFY:
{
NotifyMsgDataType notifyData;
Sys_GetMessageBody((MESSAGE_t *)pEvent, ¬ifyData, sizeof(NotifyMsgDataType));
bHandled = TRUE;
switch(notifyData.nAccessType)
{
case KX_PostRepastesVote:
{
int iRet = eFailed;
tResponsePostVote* Response = NULL;
TUChar pszInfo[128] = {0};
iRet = KaiXinAPI_JsonParse(KX_PostRepastesVote, (void **)&Response);
if(Response->ret == 1)
{
pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Post_OK),TResource::LoadConstString(APP_KA_ID_STRING_Repaste),WMB_OK);
Set_Url_Params(nAPIHandle, "flag", "0");
KaiXinAPICommon_Download(nAPIHandle, this->GetWindowHwndId());
}
else
{
TUString::StrUtf8ToStrUnicode(pszInfo, (const Char *)Response->ErrorInfo);
pApp->MessageBox(pszInfo,TResource::LoadConstString(APP_KA_ID_STRING_Repaste),WMB_OK);
}
if( Response )
{
delete Response;
}
}
break;
case KX_PostTag:
{
int iRet = eFailed;
tResponsePostVote* Response = NULL;
TUChar pszInfo[128] = {0};
iRet = KaiXinAPI_JsonParse(KX_PostTag, (void **)&Response);
if(Response->ret == 1)
{
pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Post_OK),TResource::LoadConstString(APP_KA_ID_STRING_Repaste),WMB_OK);
Set_Url_Params(nAPIHandle, "flag", "0");
KaiXinAPICommon_Download(nAPIHandle, this->GetWindowHwndId());
}
else
{
TUString::StrUtf8ToStrUnicode(pszInfo, (const Char *)Response->ErrorInfo);
pApp->MessageBox(pszInfo,TResource::LoadConstString(APP_KA_ID_STRING_Repaste),WMB_OK);
}
if( Response )
{
delete Response;
}
}
break;
default:
break;
}
break;
}
case MSG_POST_THREAD_NOTIFY:
{
PostNotifyMsgDataType notifyData;
Sys_GetMessageBody((MESSAGE_t *)pEvent, ¬ifyData, sizeof(PostNotifyMsgDataType));
if(notifyData.nEditType == NewTagEdit)
{
int iRet = eFailed;
tResponseRepasteDetail* Response = NULL;
iRet = KaiXinAPI_JsonParse(nAPIHandle, (void **)&Response);
if(iRet == 1)
{
Set_Url_Params(KX_PostTag, "urpid", Response->urpid);
Set_Url_Params(KX_PostTag, "suid", Response->suid);
Set_Url_Params(KX_PostTag, "tagid", (char*)"");//发表新的标签,tagid 置空
Set_Url_Params(KX_PostTag, "tag", (char*)notifyData.PostMsgData.newTagdata.pszTag);
Int32 nMsgRet = 0;
nMsgRet = pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Notify),TResource::LoadConstString(APP_KA_ID_STRING_Repaste),WMB_YESNOCANCEL);
if(nMsgRet == 0)
{
Set_Url_Params(KX_PostTag, "repflag", "1");
KaiXinAPICommon_Download(KX_PostTag, this->GetWindowHwndId());
}
else if(nMsgRet == 1)
{
Set_Url_Params(KX_PostTag, "repflag", "0");
KaiXinAPICommon_Download(KX_PostTag, this->GetWindowHwndId());
}
}
if( Response )
{
delete Response;
}
}
bHandled = TRUE;
}
break;
case EVENT_KeyCommand:
{
// 抓取右软键事件
if (pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_UP
|| pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_LONG)
{
// 模拟退出按钮选中消息
HitControl(m_BackBtn);
bHandled = TRUE;
}
}
break;
default:
break;
}
if (!bHandled)
{
bHandled = TWindow::EventHandler(pApp, pEvent);
}
return bHandled;
}
// 窗口初始化
Boolean TRepaste_VoteForm::_OnWinInitEvent(TApplication * pApp, EventType * pEvent)
{
Int32 iRet = eFailed;
m_BackBtn = SetAppBackButton(this);
SetAppTilte(this,APP_KA_ID_STRING_RepasteVote);
for(int i=0;i<KAIXIN_REPASTE_VOTE_TAG_MAX_NUM;i++)
{
pTagCtrl[i] = NULL;
nTagCtrlID[i] = 0;
nTagID[i] = 0;
}
nTagCount = 0;
switch(VoteType)
{
case KX_REPASTE_VOTE_TYPE_LIST:
iRet = _InitVoteForm(pApp);
break;
case KX_REPASTE_VOTE_TYPE_TAG:
//nNewTagBtn = SetAppWriteButton(this);//没有发表新标签API了
iRet = _InitTagForm(pApp);
break;
default:
break;
}
if( iRet == eSucceed )
{
return TRUE;
}
else
{
return FALSE;
}
}
Boolean TRepaste_VoteForm::TRepaste_APIInit(TApplication* pApp)
{
return TRUE;
}
Int32 TRepaste_VoteForm::_InitVoteForm(TApplication * pApp)
{
Int32 iRet = eFailed;
int nIndex = 0;
TBarRowList *lpRowList = NULL;
TRectangle Rc_CoolBarList;
tResponseRepasteDetail* Response = NULL;
iRet = KaiXinAPI_JsonParse(nAPIHandle, (void **)&Response);
if(iRet == 1)
{
TBarRow *lpRow = NULL;
TCoolBarList* pCoolBarList = static_cast<TCoolBarList*>(GetControlPtr(APP_KA_ID_Repaste_Vote_Form_Repaste_Vote_CoolBarList));
if (pCoolBarList)
{
TBarListItem* lpItem = NULL;
pCoolBarList->GetBounds(&Rc_CoolBarList);
lpRowList = pCoolBarList->Rows();
//add row
if (lpRowList)
{
lpRowList->BeginUpdate();
lpRowList->Clear();
lpRow = lpRowList->AppendRow();
lpRowList->EndUpdate();
//add Item
if(lpRow)
{
//:TODO:Add Subject info
TUChar MsgInfo[32];
lpRow->SetCaptionFont(miniFont);
TUString::StrPrintF(MsgInfo, TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Count),Response->nSize_repasters);
lpRow->SetCaption(MsgInfo);
for(int i=0; i < Response->nSize_answerlist; i++)
{
TFont objFontType;
Int32 ItemHeight = 0;
TRectangle rect;
TRectangle Rc_Temp;
TUChar pszInfo[32] = {0};
TUChar pszVoteNum[16] = {0};
lpItem = lpRow->AppendItem();
if(lpItem)
{
lpItem->GetBounds(rect);
lpItem->SetCaption(NULL);
lpItem->SetIndicatorType(itNone);
ItemHeight = rect.Y() - Rc_CoolBarList.Y() + 10;
TUString::StrUtf8ToStrUnicode(pszInfo, (const Char *)Response->answerlist[i].answer);
Int32 nAnswerId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pAnswer = static_cast<TLabel*>(GetControlPtr(nAnswerId));
TRectangle Rc_Answer(10, ItemHeight, SCR_W - 40, 20);
pAnswer->SetBounds(&Rc_Answer);
objFontType = pAnswer->GetFont();
objFontType.Create(FONT_OTHER_INFO, FONT_OTHER_INFO);
pAnswer->SetFont(objFontType);
pAnswer->SetCaption(pszInfo,FALSE);
pAnswer->SetTransparent(TRUE);
pAnswer->SetEnabled(FALSE);
ItemHeight = ItemHeight + 22;
Int32 nProgressId = lpItem->AddCtrl(CTL_CLASS_PROGRESSBAR, 20, 5);
TProgressBar* pProgress = static_cast<TProgressBar*>(GetControlPtr(nProgressId));
TRectangle Rc_Progress(10, ItemHeight, (SCR_W*3)/4, 10);
pProgress->SetBounds(&Rc_Progress);
pProgress->SetSmooth(TRUE, TRUE);
pProgress->SetTransparent(TRUE);
pProgress->SetEnabled(FALSE);
pProgress->SetParams((const Int32)Response->answerlist[i].votepercent, 0, 100, TRUE);
TUString::StrUtf8ToStrUnicode(pszVoteNum, (const Char *)Response->answerlist[i].votenum);
TUString::StrPrintF(MsgInfo, TUSTR_Kx_Progress_Percent,pszVoteNum,Response->answerlist[i].votepercent);
Int32 nPercentId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pPercent = static_cast<TLabel*>(GetControlPtr(nPercentId));
TRectangle Rc_Percent((SCR_W*3)/4 + 20, ItemHeight - 3, 100, 20);
pPercent->SetBounds(&Rc_Percent);
objFontType = pPercent->GetFont();
objFontType.Create(FONT_OTHER_INFO, FONT_OTHER_INFO);
pPercent->SetFont(objFontType);
pPercent->SetTransparent(TRUE);
pPercent->SetEnabled(FALSE);
pPercent->SetCaption(MsgInfo,FALSE);
ItemHeight = ItemHeight + 10;
lpItem->SetHeight(55);
}
}
}
//好友观点
lpRowList->BeginUpdate();
lpRow = lpRowList->AppendRow();
lpRowList->EndUpdate();
//add Item
if(lpRow)
{
TUChar MsgInfo[32]={0};
lpRow->SetCaption(TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_FriendAnswer));
lpRow->SetCaptionFont(miniFont);
for(int i=0; i < Response->nSize_resultlist; i++)
{
TFont objFontType;
Int32 ItemHeight = 0;
TRectangle rect;
TRectangle Rc_Temp;
TUChar pszName[32] = {0};
TUChar pszAnswer[32] = {0};
lpItem = lpRow->AppendItem();
if(lpItem)
{
lpItem->GetBounds(rect);
lpItem->SetCaption(NULL);
lpItem->SetIndicatorType(itNone);
ItemHeight = rect.Y() - Rc_CoolBarList.Y() + 10;
TUString::StrUtf8ToStrUnicode(pszName, (const Char *)Response->resultlist[i].fname);
Int32 nNameId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pName = static_cast<TLabel*>(GetControlPtr(nNameId));
TRectangle Rc_Name(10, ItemHeight, TUString::StrLen(pszName)*FONT_OTHER_INFO, 15);
pName->SetBounds(&Rc_Name);
objFontType = pName->GetFont();
objFontType.Create(FONT_OTHER_INFO, FONT_OTHER_INFO);
pName->SetFont(objFontType);
pName->SetColor(CTL_COLOR_TYPE_FORE,BLUE);
pName->SetCaption(pszName,FALSE);
TUString::StrUtf8ToStrUnicode(pszAnswer, (const Char *)Response->resultlist[i].answer);
TUString::StrPrintF(MsgInfo, TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Answer_Info),pszAnswer);
Int32 nAnswerId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pAnswer = static_cast<TLabel*>(GetControlPtr(nAnswerId));
TRectangle Rc_Answer(10 + TUString::StrLen(pszName)* FONT_OTHER_INFO, ItemHeight, SCR_W - 40 - TUString::StrLen(pszName)*FONT_OTHER_INFO, 15);
pAnswer->SetBounds(&Rc_Answer);
objFontType = pAnswer->GetFont();
objFontType.Create(FONT_OTHER_INFO, FONT_OTHER_INFO);
pAnswer->SetFont(objFontType);
pAnswer->SetTransparent(TRUE);
pAnswer->SetEnabled(FALSE);
pAnswer->SetCaption(MsgInfo,FALSE);
lpItem->SetHeight(COOLBAR_LIST_HEIGHT);
}
}
}
}
}
}
if( Response )
{
delete Response;
}
return iRet;
}
Int32 TRepaste_VoteForm::_InitTagForm(TApplication * pApp)
{
Int32 iRet = eFailed;
int nIndex = 0;
TBarRowList *lpRowList = NULL;
TRectangle Rc_CoolBarList;
tResponseRepasteDetail* Response = NULL;
iRet = KaiXinAPI_JsonParse(nAPIHandle, (void **)&Response);
if(iRet == 1)
{
TUChar MsgInfo[32] = {0};
TLabel* m_label = NULL;
int tagheight = 0;
Int32 VoteCount = 0;
TUChar TUCharVoteCount[32];
TUString::StrUtf8ToStrUnicode(TUCharVoteCount,(const Char *)Response->rpnum);
VoteCount = TUString::StrAToI(TUCharVoteCount);
TUString::StrPrintF(MsgInfo, TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Count),VoteCount);
TPanel* pVotePanel = static_cast<TPanel*>(GetControlPtr(APP_KA_ID_Repaste_Vote_tag_Form_Repaste_Vote_tag_Panel));
m_label = new TLabel;
if(m_label->Create(pVotePanel))
{
TFont objFontType;
TRectangle obLabelRec(20,10,200,30);
m_label->SetBounds(&obLabelRec);
m_label->SetAutoSize(TRUE);
m_label->SetEnabled(FALSE);
objFontType = m_label->GetFont();
objFontType.Create(FONT_NAME, FONT_NAME);
m_label->SetFont(objFontType);
m_label->SetCaption(MsgInfo,FALSE);
m_label->Show(TRUE);
tagheight = tagheight + 40;
}
int tag_x = 15;
int tag_y = 0;
int tag_w = KAIXIN_REPASTE_VOTE_TAG_MAX_WIDTH;
int i = 0;
for(i=0; i < Response->nSize_taglist && i < KAIXIN_REPASTE_VOTE_TAG_MAX_NUM; i++)
{
//show tag
TRichView* m_Tag = NULL;
tag_y = tagheight;
tag_w = KAIXIN_REPASTE_VOTE_TAG_MAX_WIDTH;
TRectangle Rc_Tag(tag_x,tag_y,tag_w,KAIXIN_REPASTE_VOTE_TAG_HEIGHT);
m_Tag = new TRichView;
if(m_Tag->Create(pVotePanel))
{
TFont objFontType;
Int32 nLen = 0;
// Coord nW = 0;
//Int32 nLineCount = 0;
TUChar pszTag[128+1] = {0};
pTagCtrl[i] = (TCtrl*)m_Tag;
nTagCtrlID[i] = m_Tag->GetId();
nTagID[i] = Response->taglist[i].id;
//m_Tag->SetBounds(&Rc_Tag);
objFontType = m_Tag->GetFont();
objFontType.Create(FONT_CONTENT_DETAIL, FONT_CONTENT_DETAIL);
m_Tag->SetFont(objFontType);
m_Tag->SetColor(CTL_COLOR_TYPE_FORE, RGB_COLOR_WHITE);
TUString::StrUtf8ToStrUnicode(pszTag, (const Char *)Response->taglist[i].name);
//m_Tag->SetCaption(pszTag,FALSE);
//tag_w = objFontType.CharsWidth(pszTag,TUString::StrLen(pszTag));
tag_w = GetShowAllStringWidth(pszTag, objFontType);
//nLineCount = m_Tag->GetLinesCount();
//m_Tag->SetMaxVisibleLines(1, TRUE);
tag_w += 30;
Rc_Tag.SetWidth(tag_w);
//如果超出范围,则换行
if( tag_x + tag_w > (SCR_W - 20) )
{
tag_x = 15;
tagheight = tagheight + KAIXIN_REPASTE_VOTE_TAG_HEIGHT + REPASTE_TAG_OFFSETY;
tag_y = tagheight;
Rc_Tag.SetX(tag_x);
Rc_Tag.SetY(tag_y);
}
m_Tag->SetBounds(&Rc_Tag);
m_Tag->SetCaption(pszTag, FALSE);
//m_Tag->SetBorderStyle(bsSingle, TRUE);
//m_Tag->SetFrameWidth(1);
m_Tag->SetEnabled(TRUE);
m_Tag->SetColor(CTL_COLOR_TYPE_BACK, Repaste_tag_Clolor[i]);
m_Tag->SetColor(CTL_COLOR_TYPE_SELECTED_BACK, Repaste_tag_Clolor[i]);
m_Tag->SetColor(CTL_COLOR_TYPE_FOCUS_BACK, Repaste_tag_Clolor[i]);
m_Tag->SetWordWrapAttr(FALSE);
m_Tag->SetScrollBarMode(CTL_SCL_MODE_NONE);
m_Tag->Show(TRUE);
nTagCount++;
tag_x = tag_x + tag_w + REPASTE_TAG_OFFSETX;
}
}
tagheight = tagheight + KAIXIN_REPASTE_VOTE_TAG_HEIGHT + 5;
//Show Friend tag
TBarRow *lpRow = NULL;
TCoolBarList* pCoolBarList = static_cast<TCoolBarList*>(GetControlPtr(APP_KA_ID_Repaste_Vote_tag_Form_Repaste_Vote_tag_CoolBarList));
if (pCoolBarList)
{
TBarListItem* lpItem = NULL;
TRectangle obBarListRec(10,tagheight,SCR_W-10*2,46);
pCoolBarList->SetBounds(&obBarListRec);
pCoolBarList->GetBounds(&Rc_CoolBarList);
lpRowList = pCoolBarList->Rows();
//add row
if (lpRowList)
{
//好友观点
lpRowList->BeginUpdate();
lpRowList->Clear();
lpRow = lpRowList->AppendRow();
lpRowList->EndUpdate();
//add Item
if(lpRow)
{
TUChar MsgInfo[32]={0};
lpRow->SetCaption(TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_FriendAnswer));
lpRow->SetCaptionFont(miniFont);
for(int i=0; i < Response->nSize_resultlist; i++)
{
TFont objFontType;
Int32 ItemHeight = 0;
TRectangle rect;
TRectangle Rc_Temp;
TUChar pszName[32] = {0};
TUChar pszAnswer[32] = {0};
lpItem = lpRow->AppendItem();
if(lpItem)
{
lpItem->GetBounds(rect);
lpItem->SetCaption(NULL);
lpItem->SetIndicatorType(itNone);
lpItem->SetEnabled(FALSE);
ItemHeight = rect.Y() - Rc_CoolBarList.Y() + 10;
TUString::StrUtf8ToStrUnicode(pszName, (const Char *)Response->resultlist[i].fname);
Int32 nNameId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pName = static_cast<TLabel*>(GetControlPtr(nNameId));
TRectangle Rc_Name(10, ItemHeight, TUString::StrLen(pszName)*FONT_OTHER_INFO, 15);
pName->SetBounds(&Rc_Name);
objFontType = pName->GetFont();
objFontType.Create(FONT_OTHER_INFO, FONT_OTHER_INFO);
pName->SetFont(objFontType);
pName->SetColor(CTL_COLOR_TYPE_FORE,BLUE);
pName->SetCaption(pszName,FALSE);
TUString::StrUtf8ToStrUnicode(pszAnswer, (const Char *)Response->resultlist[i].answer);
TUString::StrPrintF(MsgInfo, TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Answer_Info),pszAnswer);
Int32 nAnswerId = lpItem->AddCtrl(CTL_CLASS_LABEL, 20, 5);
TLabel* pAnswer = static_cast<TLabel*>(GetControlPtr(nAnswerId));
TRectangle Rc_Answer(10 + TUString::StrLen(pszName)*FONT_OTHER_INFO, ItemHeight, SCR_W - 40 - TUString::StrLen(pszName)*FONT_OTHER_INFO, 15);
pAnswer->SetBounds(&Rc_Answer);
objFontType = pAnswer->GetFont();
objFontType.Create(FONT_OTHER_INFO, FONT_OTHER_INFO);
pAnswer->SetFont(objFontType);
pAnswer->SetTransparent(TRUE);
pAnswer->SetEnabled(FALSE);
pAnswer->SetCaption(MsgInfo,FALSE);
lpItem->SetHeight(COOLBAR_LIST_HEIGHT);
}
}
}
}
}
}
if( Response )
{
delete Response;
}
return iRet;
}
// 关闭窗口时,保存设置信息
Boolean TRepaste_VoteForm::_OnWinClose(TApplication * pApp, EventType * pEvent)
{
return TRUE;
}
// 控件点击事件处理
Boolean TRepaste_VoteForm::_OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled = FALSE;
if(m_BackBtn == pEvent->sParam1)
{
bHandled = TRUE;
this->CloseWindow();
return bHandled;
}
/*发表新标签*/
if( pEvent->sParam1 == nNewTagBtn )
{
PostNotifyMsgDataType in_msgData;
MemSet(&in_msgData, 0, sizeof(PostNotifyMsgDataType));
in_msgData.nCtrlId = 0;
in_msgData.nHwndId = this->GetWindowHwndId();
in_msgData.nEditType = NewTagEdit;
TAppEditForm *pNewtag = new TAppEditForm( pApp, in_msgData);
bHandled = TRUE;
return bHandled;
}
switch(pEvent->sParam1)
{
/*转帖互动*/
case APP_KA_ID_Repaste_Vote_Form_Repaste_Vote_CoolBarList:
{
TBarRow *pRow = reinterpret_cast< TBarRow* > ( pEvent->sParam2 );
switch( pRow->GetIndex() )
{
case 0: //投票互动
{
int iRet = eFailed;
TBarListItem *pItem = reinterpret_cast < TBarListItem* >( pEvent->lParam3 );
int VoteIndex = pItem->GetIndex()+1;
tResponseRepasteDetail* Response = NULL;
iRet = KaiXinAPI_JsonParse(nAPIHandle, (void **)&Response);
if(iRet == 1)
{
TUChar pszAnswernum[32]={0};
Char pAnswernum[32]={0};
TUString::StrIToH( pszAnswernum, VoteIndex);
TUString::StrUnicodeToStrUtf8( pAnswernum, pszAnswernum);
Set_Url_Params(KX_PostRepastesVote, "urpid", Response->urpid);
Set_Url_Params(KX_PostRepastesVote, "voteuid", Response->voteuid);
Set_Url_Params(KX_PostRepastesVote, "suid", Response->suid);
Set_Url_Params(KX_PostRepastesVote, "surpid", Response->surpid);
Set_Url_Params(KX_PostRepastesVote, "answernum", (char*)pAnswernum);
Int32 nMsgRet = 0;
nMsgRet = pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Notify),TResource::LoadConstString(APP_KA_ID_STRING_Repaste),WMB_YESNOCANCEL);
if(nMsgRet == 0)
{
Set_Url_Params(KX_PostRepastesVote, "repflag", "1");
KaiXinAPICommon_Download(KX_PostRepastesVote, this->GetWindowHwndId());
}
else if(nMsgRet == 1)
{
Set_Url_Params(KX_PostRepastesVote, "repflag", "0");
KaiXinAPICommon_Download(KX_PostRepastesVote, this->GetWindowHwndId());
}
}
if( Response )
{
delete Response;
}
bHandled = TRUE;
}
break;
case 1://好友观点
{
int iRet = eFailed;
TBarListItem *pItem = reinterpret_cast < TBarListItem* >( pEvent->lParam3 );
int ResultIndex = pItem->GetIndex();
tResponseRepasteDetail* Response = NULL;
iRet = KaiXinAPI_JsonParse(nAPIHandle, (void **)&Response);
if(iRet == 1)
{
//:TODO:点击好友的名字
//Response->resultlist[ResultIndex].uid
}
if( Response )
{
delete Response;
}
bHandled = TRUE;
}
break;
default:
break;
}
bHandled = TRUE;
}
break;
default:
{
if( VoteType == KX_REPASTE_VOTE_TYPE_TAG )
{
for(int i=0;i<nTagCount;i++)
{
if(nTagCtrlID[i] == pEvent->sParam1)
{
int iRet = eFailed;
tResponseRepasteDetail* Response = NULL;
iRet = KaiXinAPI_JsonParse(nAPIHandle, (void **)&Response);
if(iRet == 1)
{
TUChar pszAnswernum[32]={0};
Char pAnswernum[32]={0};
TUString::StrIToA( pszAnswernum, Response->taglist[i].id);
TUString::StrUnicodeToStrUtf8( pAnswernum, pszAnswernum);
Set_Url_Params(KX_PostTag, "urpid", Response->surpid);
Set_Url_Params(KX_PostTag, "suid", Response->suid);
Set_Url_Params(KX_PostTag, "tagid", (char*)pAnswernum);
Set_Url_Params(KX_PostTag, "tag", "");
Int32 nMsgRet = 0;
nMsgRet = pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_Repaste_Vote_Notify),TResource::LoadConstString(APP_KA_ID_STRING_Repaste),WMB_YESNOCANCEL);
if(nMsgRet == 0)
{
Set_Url_Params(KX_PostTag, "repflag", "1");
KaiXinAPICommon_Download(KX_PostTag, this->GetWindowHwndId());
}
else if(nMsgRet == 1)
{
Set_Url_Params(KX_PostTag, "repflag", "0");
KaiXinAPICommon_Download(KX_PostTag, this->GetWindowHwndId());
}
}
if( Response )
{
delete Response;
}
bHandled = TRUE;
}
}
}
}
break;
}
return bHandled;
}
|
#include <bits/stdc++.h>
using namespace std;
// Complete the repeatedString function below.
long repeatedString(string s, long n) {
// compute how many a's do we have in the string s
int a_count = 0 ;
long long int a_total = 0 ;
for (int i=0; i<s.length(); i++)
{
if (s[i] == 'a')
a_count ++;
}
// get how many complete s is there and the reminder
a_total = (n/s.length())*a_count;
int s_reminder = n%s.length();
for(int i=0; i<s_reminder; i++)
{
if (s[i] == 'a')
{
a_total ++ ;
}
}
return a_total;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string s;
getline(cin, s);
long n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
long result = repeatedString(s, n);
fout << result << "\n";
fout.close();
return 0;
}
|
// A mixed, flexible variable data type (plain ol' data - POD) with all-public data access.
// (C) 2016 CubicleSoft. All Rights Reserved.
#ifndef CUBICLESOFT_STATIC_MIXED_VAR
#define CUBICLESOFT_STATIC_MIXED_VAR
#include <cstdint>
#include <cstddef>
#include <cstring>
namespace CubicleSoft
{
enum StaticMixedVarModes
{
MV_None,
MV_Bool,
MV_Int,
MV_UInt,
MV_Double,
MV_Str
};
// Must be used like: StaticMixedVar<char[8192]>
// Designed to be extended but not overridden.
template <class T>
class StaticMixedVar
{
public:
StaticMixedVarModes MxMode;
std::int64_t MxInt;
double MxDouble;
T MxStr;
size_t MxStrPos;
StaticMixedVar() : MxMode(MV_None), MxInt(0), MxDouble(0.0), MxStrPos(0)
{
}
// Some functions for those who prefer member functions over directly accessing raw class data.
inline bool IsNone()
{
return (MxMode == MV_None);
}
inline bool IsBool()
{
return (MxMode == MV_Bool);
}
inline bool IsInt()
{
return (MxMode == MV_Int);
}
inline bool IsUInt()
{
return (MxMode == MV_UInt);
}
inline bool IsDouble()
{
return (MxMode == MV_Double);
}
inline bool IsStr()
{
return (MxMode == MV_Str);
}
inline bool GetBool()
{
return (MxInt != 0);
}
inline std::int64_t GetInt()
{
return MxInt;
}
inline std::uint64_t GetUInt()
{
return (std::uint64_t)MxInt;
}
inline double GetDouble()
{
return MxDouble;
}
inline char *GetStr()
{
return MxStr;
}
inline size_t GetSize()
{
return MxStrPos;
}
inline size_t GetMaxSize()
{
return sizeof(MxStr);
}
inline void SetBool(bool newbool)
{
MxMode = MV_Bool;
MxInt = (int)newbool;
}
inline void SetInt(std::int64_t newint)
{
MxMode = MV_Int;
MxInt = newint;
}
inline void SetUInt(std::uint64_t newint)
{
MxMode = MV_UInt;
MxInt = (std::int64_t)newint;
}
inline void SetDouble(double newdouble)
{
MxMode = MV_Double;
MxDouble = newdouble;
}
void SetStr(const char *str)
{
MxMode = MV_Str;
MxStrPos = 0;
while (MxStrPos < sizeof(MxStr) - 1 && *str)
{
MxStr[MxStrPos++] = *str++;
}
MxStr[MxStrPos] = '\0';
}
void SetData(const char *str, size_t size)
{
MxMode = MV_Str;
MxStrPos = 0;
while (MxStrPos < sizeof(MxStr) - 1 && size)
{
MxStr[MxStrPos++] = *str++;
size--;
}
MxStr[MxStrPos] = '\0';
}
// Only prepends if there is enough space.
void PrependStr(const char *str)
{
size_t y = strlen(str);
if (MxStrPos + y < sizeof(MxStr) - 1)
{
memmove(MxStr + y, MxStr, MxStrPos + 1);
memcpy(MxStr, str, y);
MxStrPos += y;
}
}
// Only prepends if there is enough space.
void PrependData(const char *str, size_t size)
{
if (MxStrPos + size < sizeof(MxStr) - 1)
{
memmove(MxStr + size, MxStr, MxStrPos + 1);
memcpy(MxStr, str, size);
MxStrPos += size;
}
}
void AppendStr(const char *str)
{
while (MxStrPos < sizeof(MxStr) - 1 && *str)
{
MxStr[MxStrPos++] = *str++;
}
MxStr[MxStrPos] = '\0';
}
void AppendData(const char *str, size_t size)
{
while (MxStrPos < sizeof(MxStr) - 1 && size)
{
MxStr[MxStrPos++] = *str++;
size--;
}
MxStr[MxStrPos] = '\0';
}
inline void AppendChar(char chr)
{
if (MxStrPos < sizeof(MxStr) - 1)
{
MxStr[MxStrPos++] = chr;
MxStr[MxStrPos] = '\0';
}
}
inline void AppendMissingChar(char chr)
{
if ((!MxStrPos || MxStr[MxStrPos - 1] != chr) && MxStrPos < sizeof(MxStr) - 1)
{
MxStr[MxStrPos++] = chr;
MxStr[MxStrPos] = '\0';
}
}
inline bool RemoveTrailingChar(char chr)
{
if (!MxStrPos || MxStr[MxStrPos - 1] != chr) return false;
MxStr[--MxStrPos] = '\0';
return true;
}
inline void SetSize(size_t size)
{
if (size < sizeof(MxStr))
{
MxStrPos = size;
MxStr[MxStrPos] = '\0';
}
}
};
}
#endif
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** 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 3
//** 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
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#ifndef __idSurfaceFaceQ1__
#define __idSurfaceFaceQ1__
#include "SurfaceFaceQ1Q2.h"
#include "../../common/file_formats/bsp29.h"
#include "shader.h"
struct mbrush29_texture_t {
char name[ 16 ];
unsigned width, height;
shader_t* shader;
image_t* gl_texture;
image_t* fullBrightTexture;
int anim_total; // total tenths in sequence ( 0 = no)
mbrush29_texture_t* anim_next; // in the animation sequence
mbrush29_texture_t* anim_base; // first frame of animation
mbrush29_texture_t* alternate_anims; // bmodels in frmae 1 use these
unsigned offsets[ BSP29_MIPLEVELS ]; // four mip maps stored
};
struct mbrush29_texinfo_t {
mbrush29_texture_t* texture;
};
class idSurfaceFaceQ1 : public idSurfaceFaceQ1Q2 {
public:
int flags;
shader_t* altShader;
mbrush29_texinfo_t* texinfo;
idSurfaceFaceQ1();
};
#endif
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin>>n;
vector<pair<int , string>> c;
for(int i=0;i<n;i++){
int a;
cin>>a;
string b;
getline(cin,b);
c.push_back(make_pair(a,b));
}
for(int i=0;i<n;i++){
cout<<c[i].first<<" ";
cout<<c[i].second<<endl;
}
return 0;
}
|
#pragma once
#include "boundingsphere.h"
namespace LM {
class Plane
{
private:
const glm::vec3 m_Normal;
const float m_Distance;
public:
Plane(const glm::vec3& normal, float distance) :
m_Normal(normal),
m_Distance(distance) {}
Plane Normolized() const;
IntersectData IntersectSphere(const BoundingSphere &other) const;
inline const glm::vec3 GetNormal() const { return m_Normal; }
inline float GetDistance() const { return m_Distance; }
private:
float GetLength(const glm::vec3 &vector) const;
float GetDot(const glm::vec3 &first, const glm::vec3 &second) const;
};
}
|
//@@author A0112218W
#include "Command_Sort.h"
SortCommand::SortCommand(Sort_Type type) : Command (CommandTokens::PrimaryCommandType::Sort){
_newSortType = type;
}
UIFeedback SortCommand::execute(RunTimeStorage* runTimeStorage) {
checkIsValidForExecute(runTimeStorage);
_oldSortType = runTimeStorage->getSortType();
runTimeStorage->changeSortType(_newSortType);
postExecutionAction(runTimeStorage);
return UIFeedback(runTimeStorage->refreshTasksToDisplay(), MESSAGE_SORT_SUCCESS);
}
UIFeedback SortCommand::undo() {
checkIsValidForUndo();
_runTimeStorageExecuted->changeSortType(_oldSortType);
std::vector<Task> tasksToDisplay = _runTimeStorageExecuted->refreshTasksToDisplay();
postUndoAction();
return UIFeedback(tasksToDisplay, MESSAGE_SORT_UNDO);
}
bool SortCommand::canUndo() {
return true;
}
SortCommand::~SortCommand(void) {
}
|
#include "CGraphics.h"
CGraphics::CGraphics()
{
}
CGraphics::~CGraphics()
{
}
void CGraphics::M_RenderGame(void)
{
static double anim = 0.0;
anim += 0.05;
V_CrazyParam += 0.05;
//render map
double gsize = V_PEngine->V_Grid_Size;
auto s = V_PEngine->V_Map.size;
for (int i = 0; i < s[0]; i++)
{
for (int j = 0; j < s[1]; j++)
{
if (V_PEngine->V_Map[T2Int(i, j)] == 1)
{
T2Double cen = T2Double(i, j)*gsize;
auto p = cen.convert_gl();
M_DrawPolygon(p, "square", gsize / 2, 0, T4Int(125, 30, 255, 255));
}
}
}
auto am1 = glm::rotate(glm::mat4(1.0), (float)(cos(anim) * 0.2 * PI), glm::vec3(0.0, 0.0, 1.0));
auto am2 = glm::rotate(glm::mat4(1.0), (float)(sin(anim) * 0.2 * PI), glm::vec3(0.0, 0.0, 1.0));
V_Hiers["player"]->M_RegisterTrans2(1, am1);
V_Hiers["player"]->M_RegisterTrans2(2, am2);
V_Hiers["enemy"]->M_RegisterTrans2(1, am2);
V_Hiers["enemy"]->M_RegisterTrans2(2, am1);
//render objects
for (auto x : V_PEngine->V_Objects)
{
auto d = x->M_GetDrawData();
if (3 <= d.img && d.img <= 7 ) //item
{
M_DrawItem(d.pos.convert_gl(), d.size, d.img - 3);
}
else if(d.img == 1)
{
M_DrawHier(d.pos.convert_gl(), "enemy", d.size * 0.8, d.rotate, d.color);
}
else
{
M_DrawPolygon(d.pos.convert_gl(), "square", d.size, d.rotate, d.color);
}
}
//render player
auto d = V_PEngine->V_Player->M_GetDrawData();
if (V_PEngine->V_Animation_Temp > 0)
{
am1 = glm::rotate(glm::mat4(1.0), (float)(0.5 * PI *(V_PEngine->V_Animation_Temp) / 30), glm::vec3(0.0, 0.0, 1.0));
am2 = glm::rotate(glm::mat4(1.0), (float)(0.5 * PI *(V_PEngine->V_Animation_Temp) / 30), glm::vec3(0.0, 0.0, 1.0));
}
V_Hiers["player"]->M_RegisterTrans2(1, am1);
V_Hiers["player"]->M_RegisterTrans2(2, am2);
M_DrawHier(d.pos.convert_gl(), "player", d.size * 1.0, d.rotate, d.color);
}
void CGraphics::M_RenderUI(void)
{
if (V_PEngine->V_GameEnd == 1)
{
M_DrawNumber(Vec3d(V_Screen_Size[0] / 2 - 150, V_Screen_Size[1] / 2, 0), 100, V_PEngine->V_PEnemies.size(), T4Int(255, 0, 0, 255));
M_DrawPolygon(Vec3d(V_Screen_Size[0] / 2, V_Screen_Size[1] / 2, 0), "square", 250, 0, T4Int(130, 100, 100, 255));
}
if (V_PEngine->V_GameEnd == 2)
{
M_DrawNumber(Vec3d(V_Screen_Size[0] / 2 - 150, V_Screen_Size[1] / 2, 0), 100, V_PEngine->V_LeftTime, T4Int(125, 255, 0, 255));
M_DrawPolygon(Vec3d(V_Screen_Size[0] / 2, V_Screen_Size[1] / 2, 0), "square", 250, 0, T4Int(100, 130, 100, 255));
}
M_DrawNumber(Vec3d(50, 100, 0), 10, V_PEngine->V_PEnemies.size(), T4Int(255,0,0,255));
M_DrawNumber(Vec3d(50, 150, 0), 10, V_PEngine->V_LeftTime, T4Int(125,255,0,255));
M_DrawNumber(Vec3d(50, 200, 0), 10, V_PEngine->V_Life, T4Int(255, 255, 0, 255));
M_DrawPolygon(Vec3d(50, 150, 0), "square", 80, 0, T4Int(100, 100, 100, 200));
auto l = V_PEngine->V_Player->M_GetItemList();
auto n = std::min(4, (int)l.size());
auto it = l.begin();
switch (n)
{
case 4:
M_DrawItem(Vec3d(300, V_Screen_Size[1] - 40, 0), 30, *next(it, 3));
case 3:
M_DrawItem(Vec3d(230, V_Screen_Size[1] - 40, 0), 30, *next(it, 2));
case 2:
M_DrawItem(Vec3d(160, V_Screen_Size[1] - 40, 0), 30, *next(it, 1));
case 1:
M_DrawItem(Vec3d(70, V_Screen_Size[1] - 60, 0), 50,*it);
case 0:
break;
}
M_DrawPolygon(Vec3d(70, V_Screen_Size[1] - 60, 0), "square", 50, 0, T4Int(100, 170, 170, 200));
M_DrawPolygon(Vec3d(160, V_Screen_Size[1] - 40, 0), "square", 30, 0, T4Int(100, 170, 170, 200));
M_DrawPolygon(Vec3d(230, V_Screen_Size[1] - 40, 0), "square", 30, 0, T4Int(100, 170, 170, 200));
M_DrawPolygon(Vec3d(300, V_Screen_Size[1] - 40, 0), "square", 30, 0, T4Int(100, 170, 170, 200));
}
void CGraphics::M_Initialize(CEngine * P)
{
V_PEngine = P;
V_Screen_Size = T2Double(1080, 1080);
V_Camera_Pos = T2Double(0, 0);
V_Camera_Speed.set(0.0, 0.0);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE);
glutInitWindowPosition(0, 0);
glutInitWindowSize(1080, 1080);
int id = glutCreateWindow("Graphics Assn2");
cout << id << endl;
glClearColor(1, 1, 1, 1); //background white
glClearColor(0.8f, 0.8f, 0.8f, 0.5f);
glShadeModel(GL_FLAT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_MULTISAMPLE);
V_CrazyParam = 0.0;
}
void CGraphics::M_Initialize2(void)
{
glEnable(GL_DEPTH_TEST);
V_SM = CShaderManager::getInstance();
M_SetupHieraModels();
}
void CGraphics::M_MoveCamera(void)
{
auto p = V_PEngine->V_Player->M_GetPosition();
auto c = V_Camera_Pos;
V_Camera_Height = 200 +200 * sin(V_PEngine->V_IS_Camera / 300.0*PI);
auto a = p - c;
a = V_Math->M_2TV_Normalize(a);
auto d = V_Math->M_2TV_Angle(p, c);
a *= d[1];
a *= 0.003;
V_Camera_Speed += a;
V_Camera_Speed *= 0.9;
V_Camera_Pos += V_Camera_Speed;
}
void CGraphics::M_CallbackDisplay()
{
static double count = 0;
count += 0.02;
M_MoveCamera();
V_CurrentDrawing = false;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
V_SM->M_UseProgram("prg1");
V_CTM = glm::mat4(1.0f);
V_CTM = glm::translate(V_CTM, glm::vec3(-1.0, -1.0, 0.0));
V_CTM = glm::scale(V_CTM, glm::vec3(2.0 / V_Screen_Size[0], 2.0 / V_Screen_Size[1], 1));
M_RenderUI();
V_CurrentDrawing = true;
glm::vec3 v(0.0f);
glm::vec3 up(0, 1, 0);
if (V_PEngine->V_CrazyMod)
{
v[0] = 100 * cos(count);
v[1] = 100 * sin(count);
up[1] = cos(DTR(30)*sin(count));
up[0] = sin(DTR(30)*sin(count));
}
V_CTM = glm::mat4(1.0f);
auto pers = glm::perspective(glm::radians(45.0f), 1.0f, 0.1f, 1000.0f);
auto view = glm::lookAt(glm::vec3(V_Camera_Pos[0], V_Camera_Pos[1], V_Camera_Height) + v,
glm::vec3(V_Camera_Pos[0], V_Camera_Pos[1], 0), up);
V_CTM = pers * view;
M_RenderGame();
glutSwapBuffers();
}
void CGraphics::M_CallbackReshape(int w, int h)
{
V_Screen_Size[0] = w;
V_Screen_Size[1] = h;
glViewport(0, 0, w, h);
}
void CGraphics::M_CallbackIdle()
{
glutPostRedisplay();
}
void CGraphics::M_DrawLine(Vec3d p1, Vec3d p2, T4Int rgba)
{
glm::mat4 m;
m = V_CTM;
m = glm::translate(V_CTM, glm::vec3(p1));
m = glm::scale(V_CTM, glm::vec3(p2 - p1));
V_BasicPolygons["line"]->M_Draw(m, rgba);
}
void CGraphics::M_DrawPolygon(Vec3d p, string name, double r, double rotate, T4Int rgba)
{
if (V_PEngine->V_CrazyMod && V_CurrentDrawing)
{
p[2] += 15 * (sin(p[0]*0.05 + V_CrazyParam) + sin(p[1]*0.05 + V_CrazyParam));
}
glm::mat4 m;
m = V_CTM;
m = glm::translate(m, glm::vec3(p));
m = glm::rotate(m, float(rotate), glm::vec3(0.0f,0.0f,1.0f));
m = glm::scale(m, glm::vec3(r, r, r));
V_BasicPolygons[name]->M_Draw(m, rgba);
}
void CGraphics::M_DrawHier(Vec3d p, string name, double r, double rotate, T4Int rgba)
{
if (V_PEngine->V_CrazyMod && V_CurrentDrawing)
{
p[2] += 15 * (sin(p[0] * 0.05 + V_CrazyParam) + sin(p[1] * 0.05 + V_CrazyParam));
}
glm::mat4 m;
m = V_CTM;
m = glm::translate(m, glm::vec3(p));
m = glm::rotate(m, float(rotate), glm::vec3(0.0f, 0.0f, 1.0f));
m = glm::scale(m, glm::vec3(r, r, r));
T4Double c;
for (int i = 0; i < 4; i++) c[i] = rgba[i] / 255.0;
V_Hiers[name]->M_Draw(m, c);
}
void CGraphics::M_DrawFont(Vec2d p, string str, T4Int rgba)
{
}
void CGraphics::M_DrawFontBig(Vec2d p, string str, double scale, T4Int rgba)
{
}
void CGraphics::M_DrawItem(Vec3d p, double r, int z)
{
if (z == 0) // Mega fire
{
for (int i = 0; i < 10; i++)
{
M_DrawPolygon(p, "diamond", r*0.5, (2 * PI / 10.0)*i, T4Int(255, 255, 0, 255));
}
for (int i = 0; i < 10; i++)
{
M_DrawPolygon(p, "diamond", r, (2 * PI / 10.0)*i, T4Int(255, 0, 0, 255));
}
}
if (z == 1) // Camera up
{
M_DrawPolygon(p, "circle", r*0.4, 0, T4Int(255, 255, 255, 255));
M_DrawPolygon(p + Vec3d(r*0.7, r*0.5, 0), "circle", r*0.1, 0, T4Int(255, 255, 255, 255));
M_DrawPolygon(p, "rectangle", r*0.9, 0, T4Int(90, 90, 90, 255));
}
if (z == 2) // Invincible
{
M_DrawPolygon(p, "star", r*0.8, 0, T4Int(255, 255, 0, 255));
M_DrawPolygon(p, "star", r, 0, T4Int(255, 204, 0, 255));
}
if (z == 3) // Speed up
{
for (int i = 0; i < 3; i++)
{
M_DrawPolygon(p+Vec3d(r*0.1,0,0), "diamond", r, PI/12 + (PI/12)*i, T4Int(255, 255, 255, 255));
M_DrawPolygon(p-Vec3d(r*0.1,0,0), "diamond", r, PI - (PI / 12 + (PI / 12)*i), T4Int(255, 255, 255, 255));
}
}
if (z == 4) // SuperFire
{
for (int i = 0; i < 4; i++)
{
M_DrawPolygon(p, "diamond", r, (2*PI/4.0)*i, T4Int(30, 30, 30, 255));
}
}
}
void CGraphics::M_DrawNumber(Vec3d p, double r, int num, T4Int rgba)
{
string str = to_string(num);
Vec3d i = Vec3d(0, 0, 0);
for (auto c : str)
{
int k = c - '0';
if (k == 0 || k == 2 || k == 3 || k == 5 || k == 6 || k == 7 || k == 8 || k == 9)
{
M_DrawPolygon(p+i, "A", r, 0.0, rgba);
}
if (k == 0 || k == 1 || k == 2 || k == 3 || k == 4 || k == 7 || k == 8 || k == 9)
{
M_DrawPolygon(p+i, "B", r, 0.0, rgba);
}
if (k == 0 || k == 1 || k == 3 || k == 4 || k == 5 || k == 6 || k == 7 || k == 8 || k == 9)
{
M_DrawPolygon(p+i, "C", r, 0.0, rgba);
}
if (k == 0 || k == 2 || k == 3 || k == 5 || k == 6 || k == 8 || k == 9)
{
M_DrawPolygon(p+i, "D", r, 0.0, rgba);
}
if (k == 0 || k == 2 || k == 6 || k == 8)
{
M_DrawPolygon(p+i, "E", r, 0.0, rgba);
}
if (k == 0 || k == 4 || k == 5 || k == 6 || k == 8 || k == 9)
{
M_DrawPolygon(p+i, "F", r, 0.0, rgba);
}
if (k == 2 || k == 3 || k == 4 || k == 5 || k == 6 || k == 8 || k == 9)
{
M_DrawPolygon(p+i, "G", r, 0.0, rgba);
}
i += Vec3d(r*1.5, 0, 0);
}
}
|
#ifndef __GEOMETRYVIEWDATA_H__
#define __GEOMETRYVIEWDATA_H__
#include <QList>
#include <QHash>
#include <Standard_Handle.hxx>
#include "moduleBase/ModuleType.h"
class vtkPolyData;
class TopoDS_TShape;
class QColor;
class vtkPoints;
class vtkCell;
class vtkCellArray;
class vtkKdTree;
namespace Geometry
{
class GeometryData;
class GeometrySet;
}
namespace MainWidget
{
class GeometryViewObject;
class GeoSetViewObject;
class GeometryViewObject;
class GeometryViewData
{
public:
GeometryViewData() = default;
~GeometryViewData();
QList<vtkPolyData*> transferToPoly(Geometry::GeometrySet* gset);
void removeViewObjs(Geometry::GeometrySet* gset);
void updateGraphOption();
void highLight(Geometry::GeometrySet* set, bool on);
void highLightFace(Geometry::GeometrySet* set, int index, bool on);
void highLightEdge(Geometry::GeometrySet* set, int index, bool on);
void highLightPoint(Geometry::GeometrySet* set, int index, bool on);
void highLightSolid(Geometry::GeometrySet* set, int index, bool on);
GeometryViewObject* getSolidViewObj(vtkPolyData* facePoly, int cellIndex);
GeometryViewObject* getFaceViewObj(vtkPolyData* facePoly, int cellIndex);
GeometryViewObject* getEdgeViewObj(vtkPolyData* facePoly, int cellIndex);
GeometryViewObject* getPointViewObj(vtkPolyData* facePoly, int pointIndex);
QList<GeometryViewObject*> getViewObjectByStates(int selectStates, int states);
void preHighLight(GeometryViewObject* vob);
GeometryViewObject* getPreHighLightObj();
private:
vtkPolyData* transferFace(Geometry::GeometrySet* gset);
vtkPolyData* transferEdge(Geometry::GeometrySet* gset);
vtkPolyData* transferPoint(Geometry::GeometrySet* gset);
GeoSetViewObject* getGeosetObj(Geometry::GeometrySet* set);
vtkCell* getLineCellIn(vtkPolyData* p);
int getIndexInPoly(vtkPolyData* cell, vtkPolyData* poly, QList<int> lineIndexs);
bool isSameCell(vtkKdTree* partTree, vtkCell* cell, vtkPolyData* allPoly);
private:
GeometryViewObject* _preViewObjct{};
QHash<Geometry::GeometrySet*, GeoSetViewObject* > _viewObjs{};
};
}
#endif
|
//
// scenes.h
// led_matrix
//
// Created by Alex on 16.11.15.
//
//
#ifndef scenes_h
#define scenes_h
#include "ofMain.h"
#include "utils.h"
#include "ofxAnimatableFloat.h"
class scene {
ofxAnimatableFloat fader;
public:
ofxAnimatableFloat pulse;
ofColor pixelMatrix[10][10];
virtual void setup();
virtual void update();
//void start();
//void stop();
//bool isChangeing();
//bool isRunning();
void setFrameBrightness(float brightness);
scene(){};
~scene(){}
};
class sceneIntro : public scene {
public:
void setup();
void update();
};
class sceneMirror : public scene {
auraTimer shiftTimer;
int shiftIndex;
ofDirectory dir;
vector<ofImage> images;
public:
int currentImage;
void setup();
void update();
void setRandomImage();
ofImage getCurrentImage();
void generateMatrixFromImage();
protected:
void shiftMatrix(ofColor * pixelMatrix, int dir);
};
#endif /* animations_h */
|
/*
* Copyright 2016-2017 Flatiron Institute, Simons Foundation
*
* 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 "curationprogramcontroller.h"
#include "mlcommon.h"
#include <QJsonDocument>
class CurationProgramControllerPrivate {
public:
CurationProgramController* q;
MVContext* m_context;
QString m_log;
};
CurationProgramController::CurationProgramController(MVContext* mvcontext)
{
d = new CurationProgramControllerPrivate;
d->q = this;
d->m_context = mvcontext;
}
CurationProgramController::~CurationProgramController()
{
delete d;
}
QString CurationProgramController::log() const
{
return d->m_log;
}
QString CurationProgramController::clusterNumbers()
{
QList<int> list = d->m_context->clusterAttributesKeys();
QJsonArray list2;
for (int i = 0; i < list.count(); i++) {
list2.append(list[i]);
}
return QJsonDocument(list2).toJson();
}
double CurationProgramController::metric(int cluster_number, QString metric_name)
{
QJsonObject attributes = d->m_context->clusterAttributes(cluster_number);
return attributes["metrics"].toObject()[metric_name].toDouble();
}
void CurationProgramController::setMetric(int cluster_number, QString metric_name, double val)
{
QJsonObject attributes = d->m_context->clusterAttributes(cluster_number);
QJsonObject metrics = attributes["metrics"].toObject();
metrics[metric_name] = val;
attributes["metrics"] = metrics;
d->m_context->setClusterAttributes(cluster_number, attributes);
}
QString CurationProgramController::clusterPairs()
{
QList<ClusterPair> list = d->m_context->clusterPairAttributesKeys();
QJsonArray list2;
for (int i = 0; i < list.count(); i++) {
QJsonObject obj;
obj["k1"] = list[i].k1();
obj["k2"] = list[i].k2();
list2.append(obj);
}
return QJsonDocument(list2).toJson();
}
double CurationProgramController::pairMetric(int k1, int k2, QString metric_name)
{
QJsonObject attributes = d->m_context->clusterPairAttributes(ClusterPair(k1, k2));
return attributes["metrics"].toObject()[metric_name].toDouble();
}
void CurationProgramController::setPairMetric(int k1, int k2, QString metric_name, double val)
{
QJsonObject attributes = d->m_context->clusterPairAttributes(ClusterPair(k1, k2));
QJsonObject metrics = attributes["metrics"].toObject();
metrics[metric_name] = val;
attributes["metrics"] = metrics;
d->m_context->setClusterPairAttributes(ClusterPair(k1, k2), attributes);
}
bool CurationProgramController::hasTag(int cluster_number, QString tag_name)
{
QSet<QString> tags = d->m_context->clusterTags(cluster_number);
return tags.contains(tag_name);
}
void CurationProgramController::addTag(int cluster_number, QString tag_name)
{
QSet<QString> tags = d->m_context->clusterTags(cluster_number);
tags.insert(tag_name);
d->m_context->setClusterTags(cluster_number, tags);
}
void CurationProgramController::removeTag(int cluster_number, QString tag_name)
{
QSet<QString> tags = d->m_context->clusterTags(cluster_number);
tags.remove(tag_name);
d->m_context->setClusterTags(cluster_number, tags);
}
void CurationProgramController::log(const QString& message)
{
d->m_log += message + "\n";
}
|
#include "funcs.hh"
namespace Analysis {
//PLAN: get rid of "match_position". Pass two vectors instead, and have a third & fourth which are written to with the matches (tomatch & candidate). If size != 0, we have matches.
//another consideration: need to be able to remove jets from the "candidates" vector after they've been matched. Make a copy prior to the function call? Feels risky. Do it in the function. Also make a copy candidates vector for each iteration on toMatch since it gets selected.
//In finding which jets were the matches, we know the tomatch jet match will be the 'i'th jet since we are iterating. The candidate_copy jet should be the highest pT match, so the first one in the candidate_copy list. Geometrically match the candidate_copy jet to the nearest candidate jet.
std::vector<int> MatchJets(const std::vector<fastjet::PseudoJet> candidates_safe, const std::vector<fastjet::PseudoJet> toMatch, std::vector<fastjet::PseudoJet> & c_matches, std::vector<fastjet::PseudoJet> & t_matches) {
std::vector<int> match_indices;
if (candidates_safe.size() == 0 || toMatch.size() == 0) {
return match_indices;
}
std::vector<fastjet::PseudoJet> candidates = candidates_safe;
for (int i = 0; i < toMatch.size(); ++ i) {
std::vector<fastjet::PseudoJet> candidates_copy = candidates;
fastjet::Selector selectMatchedLead = fastjet::SelectorCircle( R );
selectMatchedLead.set_reference( toMatch[i] );
std::vector<fastjet::PseudoJet> matchedToLead = sorted_by_pt( selectMatchedLead( candidates_copy ));
if (candidates_copy.size() == 0) { continue; } //means no match to this jet. Remove none from candidates. Continuing on to the next one.
else { //found at least one match. Need to remove the highest pT one from candidates and add the respective jets to the match vectors.
match_indices.push_back(i); //for using the groomed jet corresponding to this jet, later
t_matches.push_back(toMatch[i]);
c_matches.push_back(candidates_copy[0]);
for (int j = 0; j < candidates.size(); ++ j) { //finding which one to delete from candidates before next toMatch iteration.
if (candidates_copy[0].delta_R(candidates[j]) < 0.0001) { //is probably the same jet
candidates.erase(candidates.begin() + j); //removing the jet from the overall list of candidates so it can't be considered next time
match_indices.push_back(j);
break; //should exit only the c_matches loop.
}
}
}
}
return match_indices;
}
//this function is similar to the "MatchJets" function, but it instead takes a list of jets which have already been matched ("candidates_safe") and finds the jets to which they correspond in the list of unmatched jets ("toMatch") by geometrical matching. I know, it is confusing to match matched jets to unmatched jets. But that's what we're doing. When we have jets which don't have a basically perfect geometrical match to a matched jet, we know that the jet in our hands is unmatched (to a detector/particle-level complement rather than to itself in the other list, basically).
std::vector<int> FakesandMisses(const std::vector<fastjet::PseudoJet> candidates_safe, const std::vector<fastjet::PseudoJet> toMatch, std::vector<fastjet::PseudoJet> & unmatched) {
std::vector<int> miss_fake_index;
std::vector<fastjet::PseudoJet> candidates = candidates_safe;
for (int i = 0; i < toMatch.size(); ++ i) {
std::vector<fastjet::PseudoJet> candidates_copy = candidates;
fastjet::Selector selectMatchedLead = fastjet::SelectorCircle( 0.0001 ); //a "match" is now if we found the same exact jet.
selectMatchedLead.set_reference( toMatch[i] );
std::vector<fastjet::PseudoJet> matchedToLead = sorted_by_pt( selectMatchedLead( candidates_copy ));
if (candidates_copy.size() == 0) { //means no match to this jet. Remove none from candidates. Add it to unmatched & continue to next one.
miss_fake_index.push_back(i);
unmatched.push_back(toMatch[i]);
continue;
}
else { //found at least one match. Need to remove the highest pT one from candidates
for (int j = 0; j < candidates.size(); ++ j) { //finding which one to delete from candidates before next toMatch iteration.
if (candidates_copy[0].delta_R(candidates[j]) < 0.0001) { //is probably the same jet
candidates.erase(candidates.begin() + j); //removing the jet from the overall list of candidates so it can't be considered next time
break; //should exit only the candidates loop.
}
}
}
}
return miss_fake_index;
}
//new construction of responses based on ~inclusive~ matching. We now need to have two vectors to be filled with matched jets. If they aren't, when looping over pythia jets, we have misses. Fill all pythia jets into the misses. Same goes when looping over geant jets with fakes. And for matches, we just fill with however many entries there are in the matched vectors.
//MatchJets now returns a vector of pairs of indices (i,j). The first entry is the candidate's position, the second its match's position, the third the next candidate's position, the fourth its match's position, etc.
//FakesandMisses now returns a vector of indices (i) corresponding to the indices of misses or fakes from the original candidate vector.
void ConstructResponses(std::vector<RooUnfoldResponse*> res, const std::vector<fastjet::PseudoJet> g_Jets, const std::vector<fastjet::PseudoJet> p_Jets, const double mc_weight) {
std::vector<fastjet::PseudoJet> g_matches; std::vector<fastjet::PseudoJet> p_matches;
std::vector<fastjet::PseudoJet> fakes; std::vector<fastjet::PseudoJet> misses;
if (p_Jets.size() != 0) {
g_matches.clear(); p_matches.clear(); misses.clear();
MatchJets(g_Jets, p_Jets, g_matches, p_matches);
if (g_matches.size() != p_matches.size()) {std::cerr << "Somehow we have different-sized match vectors. This should never happen!" <<std::endl; exit(1);}
if (g_matches.size() < p_Jets.size()) { //then we have misses
FakesandMisses(p_matches, p_Jets, misses);
for (int i = 0; i < misses.size(); ++ i) {
res[0]->Miss(misses[i].m(), mc_weight);
// nMisses ++;
// std::cout << "MISS " << misses[i].pt() << std::endl;
}
}
if (g_matches.size() != 0) { //found match(es)
for (int i = 0; i < g_matches.size(); ++ i) {
res[0]->Fill(g_matches[i].m(), p_matches[i].m(), mc_weight); //matches should be at same index in respective vectors
// nMatches ++; nEntries ++;
//std::cout << "MATCH p:" << p_matches[i].pt() << " g:" << g_matches[i].pt() << std::endl;
}
}
}
//fake rate
if (g_Jets.size() != 0) {
g_matches.clear(); p_matches.clear(); fakes.clear();
MatchJets(p_Jets, g_Jets, p_matches, g_matches);
if (g_matches.size() != p_matches.size()) {std::cerr << "Somehow we have different-sized match vectors. This should never happen!" <<std::endl; exit(1);}
if (p_matches.size() < g_Jets.size()) { //then we have fakes
FakesandMisses(g_matches, g_Jets, fakes);
for (int i = 0; i < fakes.size(); ++ i) {
res[0]->Fake(fakes[i].m(), mc_weight);
//nFakes ++; nEntries ++;
//std::cout << "FAKE " << fakes[i].pt() << " " << std::endl;
}
}
}
return;
}
void HistFromTree(TFile *onfile, TH1D* pt, TH1D* hist1520,TH1D* hist2025, TH1D* hist2530, TH1D* hist3040, TH1D* hist4060/*, TFile *offfile, std::vector<RooUnfoldResponse*> res_vec*/) {
std::vector<double> *on_Pt = 0; std::vector<double> *on_M = 0;
std::vector<double> *on_Eta = 0; std::vector<double> *on_Phi = 0;
/*std::vector<double> *off_Pt = 0; std::vector<double> *off_M = 0;
std::vector<double> *off_Eta = 0; std::vector<double> *off_Phi = 0;
*/
double on_weight = 1;/* double off_weight = 1;*/ double on_eventID = 0; /*double off_eventID = 0;*/
TTree *on = (TTree*) onfile->Get("ResultTree");
//TTree *off = (TTree*) offfile->Get("ResultTree");
on->SetBranchAddress("jetpT",&on_Pt); on->SetBranchAddress("jetM",&on_M);
on->SetBranchAddress("jeteta",&on_Eta); on->SetBranchAddress("jetphi",&on_Phi);
on->SetBranchAddress("eventID",&on_eventID); on->SetBranchAddress("mcweight",&on_weight);
/*off->SetBranchAddress("jetpT",&off_Pt); off->SetBranchAddress("jetM",&off_M);
off->SetBranchAddress("jeteta",&off_Eta); off->SetBranchAddress("jetphi",&off_Phi);
off->SetBranchAddress("eventID",&off_eventID); off->SetBranchAddress("mcweight",&off_weight);
*/
std::cout << on->GetEntries() << " entries in tree" << std::endl;
//std::cout << off->GetEntries() << " entries in decays = off tree" << std::endl;
//note to self: PY8 with decays off is the "detector-level". We loop over this to get the fakes. Loop over "decays on" to get matches and misses.
//another note: we are going to assume that the trees have the same number of entries and that each entry is the same event (we will check this last assumption explicitly).
for (int i = 0; i < on->GetEntries(); ++ i) {
//if (i % 1000000 == 0) { cout << "still chuggin. " << i << endl;}
on->GetEntry(i);
for (int j = 0; j < on_M->size(); ++ j) {
pt->Fill(on_Pt->at(j),on_weight);
if (on_Pt->at(j) > 15 && on_Pt->at(j) < 20) {
hist1520->Fill(on_M->at(j),on_weight);
}
if (on_Pt->at(j) > 20 && on_Pt->at(j) < 25) {
hist2025->Fill(on_M->at(j),on_weight);
}
if (on_Pt->at(j) > 25 && on_Pt->at(j) < 30) {
hist2530->Fill(on_M->at(j),on_weight);
}
if (on_Pt->at(j) > 30 && on_Pt->at(j) < 40) {
hist3040->Fill(on_M->at(j),on_weight);
}
if (on_Pt->at(j) > 40 && on_Pt->at(j) < 60) {
hist4060->Fill(on_M->at(j),on_weight);
}
}
/*off->GetEntry(i);
std::cout << "Event IDs: " << on_eventID << " " << off_eventID << std::endl;
if (on_eventID != off_eventID) {std::cerr << "We've mismatched events. Exiting!" << std::endl; exit(1);}
//now we have the same event in each. Match the jets.
std::vector<fastjet::PseudoJet> ons; std::vector<fastjet::PseudoJet> offs;
//fill the vectors of pseudojets.
for (int j = 0; j < on_Pt->size(); ++ j) { //all vectors of doubles in the branches should have the same size
fastjet::PseudoJet on;
on.reset_PtYPhiM(on_Pt->at(j), on_Eta->at(j), on_Phi->at(j), on_M->at(j));
ons.push_back(on);
}
for (int j = 0; j < off_Pt->size(); ++ j) { //all vectors of doubles in the branches should have the same size
fastjet::PseudoJet off;
off.reset_PtYPhiM(off_Pt->at(j), off_Eta->at(j), off_Phi->at(j), off_M->at(j));
offs.push_back(off);
}
if (off_weight != on_weight) {std::cout << "ON V OFF: " << on_weight << " " << off_weight << std::endl; std::cerr << "Weights differ! Should never happen for the same event! Exiting!" << std::endl; exit(1);}
ConstructResponses(res_vec, offs, ons, off_weight);
*/
}
on->ResetBranchAddresses(); //off->ResetBranchAddresses();
return;
}
}
|
/****************************************************************************
** Meta object code from reading C++ file 'qtmaterialcircularprogress_internal.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.13.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "qtmaterialcircularprogress_internal.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qtmaterialcircularprogress_internal.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.13.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_QtMaterialCircularProgressDelegate_t {
QByteArrayData data[4];
char stringdata0[63];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QtMaterialCircularProgressDelegate_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QtMaterialCircularProgressDelegate_t qt_meta_stringdata_QtMaterialCircularProgressDelegate = {
{
QT_MOC_LITERAL(0, 0, 34), // "QtMaterialCircularProgressDel..."
QT_MOC_LITERAL(1, 35, 10), // "dashOffset"
QT_MOC_LITERAL(2, 46, 10), // "dashLength"
QT_MOC_LITERAL(3, 57, 5) // "angle"
},
"QtMaterialCircularProgressDelegate\0"
"dashOffset\0dashLength\0angle"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QtMaterialCircularProgressDelegate[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
3, 14, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// properties: name, type, flags
1, QMetaType::QReal, 0x00095103,
2, QMetaType::QReal, 0x00095103,
3, QMetaType::Int, 0x00095103,
0 // eod
};
void QtMaterialCircularProgressDelegate::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
#ifndef QT_NO_PROPERTIES
if (_c == QMetaObject::ReadProperty) {
auto *_t = static_cast<QtMaterialCircularProgressDelegate *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< qreal*>(_v) = _t->dashOffset(); break;
case 1: *reinterpret_cast< qreal*>(_v) = _t->dashLength(); break;
case 2: *reinterpret_cast< int*>(_v) = _t->angle(); break;
default: break;
}
} else if (_c == QMetaObject::WriteProperty) {
auto *_t = static_cast<QtMaterialCircularProgressDelegate *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 0: _t->setDashOffset(*reinterpret_cast< qreal*>(_v)); break;
case 1: _t->setDashLength(*reinterpret_cast< qreal*>(_v)); break;
case 2: _t->setAngle(*reinterpret_cast< int*>(_v)); break;
default: break;
}
} else if (_c == QMetaObject::ResetProperty) {
}
#endif // QT_NO_PROPERTIES
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject QtMaterialCircularProgressDelegate::staticMetaObject = { {
&QObject::staticMetaObject,
qt_meta_stringdata_QtMaterialCircularProgressDelegate.data,
qt_meta_data_QtMaterialCircularProgressDelegate,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *QtMaterialCircularProgressDelegate::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QtMaterialCircularProgressDelegate::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_QtMaterialCircularProgressDelegate.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int QtMaterialCircularProgressDelegate::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
#ifndef QT_NO_PROPERTIES
if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty
|| _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) {
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 3;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 3;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 3;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 3;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 3;
}
#endif // QT_NO_PROPERTIES
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
/*
* PropellingMagnet.cpp
*
* Created on: Feb 12, 2012
* Author: wjones
*/
#include "MagneticFieldComponents/PropellingMagnet.h"
#include "GeometricComponents/CoordinateUtilities.h"
namespace CoordinateComponents
{
template<typename T>
PropellingMagnet<T>::PropellingMagnet()
{
// TODO Auto-generated constructor stub
}
template<typename T>
PropellingMagnet<T>::~PropellingMagnet()
{
// TODO Auto-generated destructor stub
}
template<typename T>
PropellingMagnet<T>::PropellingMagnet(const CylindricalCoordinate<T> & inCoord,
const CartesianCoordinate<T> & inOrientation,
float strength) :
MagneticElement<T>(inOrientation, strength), myLayoutLocation(inCoord), myCurrentLocation(inCoord)
{
}
template<typename T>
PropellingMagnet<T>::PropellingMagnet(const CartesianCoordinate<T> & inCoord,
const CartesianCoordinate<T> & inOrientation,
float strength) :
MagneticElement<T>(inOrientation, strength), myLayoutLocation(inCoord), myCurrentLocation(inCoord)
{
}
template<typename T>
const CylindricalCoordinate<T>& PropellingMagnet<T>::TranslateFromLayout(const CylindricalCoordinate<T> & inCoordinate)
{
return this->myLayoutLocation.Translate(inCoordinate);
}
template<typename T>
const CylindricalCoordinate<T> & PropellingMagnet<T>::TranslateFromCurrent(const CylindricalCoordinate<T> & inCoordinate)
{
return this->myCurrentLocation.Translate(inCoordinate);
}
template<typename T>
const CylindricalCoordinate<T> & PropellingMagnet<T>::getCurrentLocation() const
{
return myCurrentLocation;
}
template<typename T>
const CylindricalCoordinate<T>& PropellingMagnet<T>::getLayoutLocation() const
{
return myLayoutLocation;
}
template<typename T>
void PropellingMagnet<T>::setLayoutLocation(
const CylindricalCoordinate<T>& inLocation)
{
this->myLayoutLocation = inLocation;
}
template<typename T>
void PropellingMagnet<T>::setLayoutLocation(const CartesianCoordinate<T>& inLocation)
{
this->myLayoutLocation.FromCartesian(inLocation);
}
template<typename T>
std::ostream& operator<<(std::ostream& outStrm, const PropellingMagnet<T>& value)
{
outStrm << "Location : " << value.myCurrentLocation << " -- ";
outStrm << (MagneticElement<T>) value << std::endl;
return outStrm;
}
} /* namespace MagneticTosserComponents */
|
#include <iostream>
#include <string>
//using namespace std;
/**
* @brief Shows how to define and use a string object
*
* We will define string variables and then see what operators and
* functions work with these variables.
*
* @return int 0 means function exited with success
*/
int main()
{
// create a variable of type string
std::string name = "Weber Waldo";
// print it out
std::cout << name << std::endl;
// get a string from a user
//std:cin >> name;
std::cout << "Enter your name: " << std::endl;
// use getline to include spaces
std::getline(std::cin, name);
std::cout << "Hi: " << name << std::endl;
// add two strings together
std::string title = "Dr. ";
std::string formal;
formal = title + name;
std::cout << "Hi: " << formal << std::endl;
// how long is the string
std::cout << "Size is " << name.size() << std::endl;
std::cout << "Length is " << formal.length() << std::endl;
// use [] to get an individual character
std::cout << "Char 3 is " << name[3] << std::endl;
// get name and commute information from a user
int minutes, miles;
std::cout << "Enter your name: " << std::endl;
std::getline(std::cin, name);
std::cout << "Enter commute minutes: " << std::endl;
std::cin >> minutes;
std::cout << "Enter commute miles: " << std::endl;
std::cin >> miles;
std::cout <<name << " has a " << minutes << " minutes, "
<< miles << " miles commute." << std::endl;
// get commute information and name from a user
// the string function find
std::string story = "Werq90af asdfj9asf sadf9afhjoj."
" jdglkjhdg adfjunkljbhn ui4e asdfjnkjndfs.";
std::cout << story << std::endl;
std::cout << "junk is at: " << story.find("junk") << std::endl;
// the string function replace
story.replace(story.find("junk"), 4, "money" );
std::cout << story << std::endl;
//story.replace(story.find(str1), str1.size, str2 ); //using variables
return 0;
}
/*
"The dragons are flying over the mountains. They are hunting for a "
"place to settle for the waldo night. What they see is endless horizon."
*/
|
#ifndef IMAGEFACTORY_H
#define IMAGEFACTORY_H
#include "notefactory.h"
#include "image.h"
class NotesManager;
/*!
* \file imagefactory.h
* \brief Classe ImageFactory permettant de construire une note de type Image
* \author Pauline Cuche/Simon Robain
*/
/**
*\class ImageFactory
* \brief Classe permettant d'instancier des objets de type Image
*Elle hérite de NoteFactory
*/
class ImageFactory : public NoteFactory
{
public:
/*!
* \brief Constructeur Par Defaut
*
* Constructeur par défaut de la classe ArticleFactory
*/
ImageFactory();
/*!
* \brief Détermine un ID unique
*
* Renvoie un id unique précédé du type de Note ici Image
*/
QString getNewId();
/*!
* \brief Fabrique une Image
*
* \param id : id de l'Image
* \param title : titre de l'Image
* \param path : chemin d'accès à l'image que l'on souhaite incorporée dans notre note Image, vide par défaut
* \param desc : descriptif de l'Image
* \return Note* : un pointeur sur notre Image nouvellement créée
*/
Note* buildNote(const QString& id,const QString& title, const QString& path="", const QString& desc="");
/*!
* \brief Fabrique une nouvelle Image
*
* Cette methode créée un nouvel ID en appelant getNewId() et appelle buildNote()
* \param title : titre de l'image
* \param path : chemin d'accès à l'image référencée par la note Image, vide par défaut
* \return Note* : un pointeur sur notre Image créée
*
*/
Note* buildNewNote(const QString& title, const QString &path);
Note* buildNotecopy(const Note* n);
/*!
* \brief Charge une Image déjà existante
* \param id : id de l'Image
* \param chemin : chemin d'accès à l'Image
* \return Note* : un pointeur sur notre Image venant d'être chargé
*
*/
Note* chargerNote(const QString& id, const QString& chemin);
};
#endif // IMAGEFACTORY_H
|
bool isPalindrome(Node *head)
{
Node *slow=head,*fast=head,*prev=NULL,*nxt=NULL;
bool ans=true;
if(!head)
return !ans;
while(fast->next and fast->next->next)
{
fast=fast->next->next;
nxt=slow->next; // reversing the first half link list
slow->next=prev;
prev=slow;
slow=nxt;
}
Node *left,*right;
if(fast->next==NULL)
{
right=slow->next;
left=prev;
}
else
{
right=slow->next;
slow->next=prev;
left=slow;
}
while(left and right)
{
if(left->data!=right->data)
return 0;
left=left->next;
right=right->next;
}
return 1;
}
|
#include "ExtendedHttpMultiPart.h"
#include <QSharedPointer>
#include <QFile>
#include <QDateTime>
#include "Debug/DebugMacros.h"
ExtendedHttpMultiPart::ExtendedHttpMultiPart(QObject *parent) :
QHttpMultiPart(parent)
{
}
ExtendedHttpMultiPart::ExtendedHttpMultiPart(ContentType contentType, QObject *parent) :
QHttpMultiPart(contentType, parent)
{
}
ExtendedHttpMultiPart::~ExtendedHttpMultiPart()
{
}
void ExtendedHttpMultiPart::appendFile(QString itemKey, QIODevice *device, QString fileName, QString contentTypeHeader)
{
if(contentTypeHeader.isEmpty())
contentTypeHeader = QStringLiteral("text/plain; charset=utf-8");
if(fileName.isEmpty()) {
QFile *file(dynamic_cast<QFile *>(device));
if(file != 0) {
fileName = file->fileName();
}
else
fileName="unknown_file";
}
QHttpPart part;
part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentTypeHeader));
part.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant(
QString(QStringLiteral("form-data; name=\"%1\"; filename=\"%2\""))
.arg(itemKey)
.arg(fileName)
)
);
part.setBodyDevice(device);
append(part);
}
template <>
void ExtendedHttpMultiPart::appendFormData<QString>(QString itemKey, QString itemValue)
{
QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDispositionHeader,
QString(QStringLiteral("form-data; name="))+itemKey);
textPart.setBody(itemValue.toUtf8());
append(textPart);
}
void ExtendedHttpMultiPart::appendFormData(itemPair_t pair)
{
appendFormData(pair.first, pair.second);
}
void ExtendedHttpMultiPart::appendFormData(itemPairsList_t pairList)
{
foreach (itemPair_t pair, pairList) {
appendFormData(pair);
}
}
void ExtendedHttpMultiPart::appendToGlobalData(QString itemKey, QVariant itemValue)
{
_globalHttpPairs.append(itemPair_t(itemKey, itemValue));
}
void ExtendedHttpMultiPart::appendFromGlobalData()
{
appendFormData(_globalHttpPairs);
_globalHttpPairs.clear();
}
ExtendedHttpMultiPart::itemPairsList_t ExtendedHttpMultiPart::_globalHttpPairs;
|
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
QGraphicsScene *scene = new QGraphicsScene;
ui->setupUi(this);
ui->graphicsView->setScene(scene);
mycolor = QColor::fromRgb(rand()%255,rand()%255,rand()%255);
myfont.setItalic(1);
myfont.setFamily("Calibri");
myfont.setPixelSize(14);
mybrush = QBrush(mycolor);
}
void Dialog::displaynode(char val, int deep, int maxdeep, int prevx, int prevy, int posx, int posy)
{
// mycolor = QColor::fromRgb(rand()%255,rand()%255,rand()%255);
// mybrush = QBrush(mycolor);
std::string s;
s.insert(0, 1, val);
QString line = QString::fromStdString(s);
mytext = new QGraphicsTextItem(line);
mytext->setFont(myfont);
mytext->setPos(posx - line.length()*myfont.pixelSize()/2, posy-elemheight/2 - myfont.pixelSize()/4);
ui->graphicsView->scene()->addLine(posx,posy-elemheight/2,prevx,prevy+elemheight/2,QPen(Qt::black,3));
ui->graphicsView->scene()->addRect(posx-elemwidth/2,posy-elemheight/2,elemwidth,elemheight,mypen,mybrush);
ui->graphicsView->scene()->addItem(mytext);
}
Dialog::~Dialog()
{
delete ui;
}
|
#include "App.hpp"
void App::addShape(App::Shape* shape) {
shapes.push_back(shape);
return;
}
void App::addShapes(App::ShapePoints shapePoints) {
short size = shapePoints.size();
this->shapes.resize(size);
for (int i = 0; i < size; i++)
shapes.at(i) = shapePoints.at(i);
return;
}
App::Shape* App::getShape(App::ID id) {
App::Shape* shape = shapes.at(id);
return shape;
}
void App::connect(App::Window* window) {
this->window = window;
return;
}
void App::disconnect() {
this->window = nullptr;
return;
}
void App::handleEvent(App::SfmlEvent e) {
switch (e.type) {
case SfmlEvent::Closed:
window->close();
break;
}
return;
}
void App::run() {
for (auto i : shapes) i->connect(this->window);
Window* w = this->window;
while (w->isOpen()) {
// check sfml events
SfmlEvent e;
while (w->pollEvent(e)) handleEvent(e);
// if time came, update
if (clock.getElapsedTime() < frameSpeed) continue;
else clock.restart();
for (auto i : shapes) i->updatePosition();
// and render
w->clear();
for (auto i : shapes) w->draw(*i->get());
w->display();
}
return;
}
App::~App() {
for (int i = 0; i < shapes.size(); i++)
delete shapes.at(i);
return;
}
|
#include "signedindialog.h"
#include "ui_signedindialog.h"
#include "mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QTableView>
#include <QSqlTableModel>
#include <QtGui>
#include <QGridLayout>
SignedInDialog::SignedInDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SignedInDialog)
{
ui->setupUi(this);
olioSaldo = new Saldo(this);
connect(this, SIGNAL(sendBalance(double)), olioSaldo, SLOT(naytaSaldo(double)));
connect(this, SIGNAL(lahetaKayttaja(QString)), olioSaldo, SLOT(asetaKayttaja(QString)));
connect(this, SIGNAL(lahetaTiliId(int)), olioSaldo, SLOT(naytaTapahtumat(int)));
}
SignedInDialog::~SignedInDialog()
{
delete ui;
delete olioSaldo;
delete olioNosta;
delete olioLahjoita;
delete olioMaksa;
delete olio2MysqlDLL;
}
void SignedInDialog::asetaOtsikko()
{
ui->lblTervetuloa->setText(ui->lblTervetuloa->text()+Kayttaja);
}
void SignedInDialog::on_btnUlos_clicked()
{
this->close();
}
void SignedInDialog::on_btnSaldo_clicked()
{
double saldo = olio2MysqlDLL->showBalance(idTili);
emit sendBalance(saldo);
emit lahetaKayttaja(Kayttaja);
emit lahetaTiliId(idTili);
olioSaldo->show();
}
void SignedInDialog::on_btnTapahtumat_clicked()
{
showTable();
}
void SignedInDialog::on_btnNosta_clicked()
{
olioNosta = new Nosta(this);
olioNosta->asetaSaldo(olio2MysqlDLL->showBalance(idTili));
olioNosta->asetaTili(idTili);
olioNosta->show();
}
void SignedInDialog::on_btnLahjoita_clicked()
{
olioLahjoita = new Lahjoita(this);
olioLahjoita->asetaSaldo(olio2MysqlDLL->showBalance(idTili));
olioLahjoita->asetaTili(idTili);
olioLahjoita->show();
}
void SignedInDialog::on_btnMaksa_clicked()
{
olioMaksa = new Maksa(this);
olioMaksa->asetaSaldo(olio2MysqlDLL->showBalance(idTili));
olioMaksa->asetaTili(idTili);
olioMaksa->asetaLaskujenMaara(olio2MysqlDLL->invoiceCount(idTili));
olioMaksa->show();
}
void SignedInDialog::showTable()
{
tableWindow = new QWidget();
btnPoistu = new QPushButton("Takaisin");
QGridLayout *tableLay = new QGridLayout(tableWindow);
QTableView *tapahtumat = new QTableView;
tableWindow->setWindowTitle("Tilitapahtumat");
tapahtumat->setModel(olio2MysqlDLL->showTransactions(idTili,15));
tapahtumat->resizeColumnToContents(0);
tableWindow->resize(350,400);
tableLay->addWidget(tapahtumat);
tableLay->addWidget(btnPoistu);
tableWindow->setLayout(tableLay);
tableWindow->show();
connect(btnPoistu, SIGNAL(clicked()), this, SLOT(tableClose()));
}
void SignedInDialog::tableClose()
{
tableWindow->close();
}
|
#include "DebugUI.h"
#include <imgui.h>
#include "imgui_impl_vulkan.h"
#include "imgui_impl_glfw.h"
#include "VulkanWrapper/VulkanDevice.h"
#include "VulkanWrapper/Window.h"
#include "VulkanWrapper/VulkanHelpers.h"
#include "VulkanWrapper/VulkanSwapchain.h"
#include "VulkanWrapper/RenderPass.h"
#include "VulkanWrapper/CommandPool.h"
#include "VulkanWrapper/FrameBuffer.h"
#include "VulkanWrapper/DepthStencilBuffer.h"
#include "DebugWindow.h"
vkw::DebugUI::DebugUI(VulkanDevice* pDevice, CommandPool* pCommandPool, Window* pWindow, VulkanSwapchain* pSwapchain, DepthStencilBuffer* pDepthStencilBuffer)
:m_pDevice{pDevice}
,m_pWindow{pWindow}
,m_pSwapchain{pSwapchain}
,m_pCommandPool{pCommandPool}
,m_pDepthStencilBuffer{pDepthStencilBuffer}
{
Init();
}
vkw::DebugUI::~DebugUI()
{
Cleanup();
}
void vkw::DebugUI::NewFrame()
{
ImGui_ImplVulkan_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void vkw::DebugUI::Render(VkSemaphore readyToRenderUISemaphore, FrameBuffer* pFramebuffer, const std::vector<DebugWindow*>& pWindows)
{
for (DebugWindow* pWindow : pWindows)
{
pWindow->Render();
}
ImGui::ShowDemoWindow();
ImGui::Render();
//m_pCommandPool->Reset();
VkCommandBuffer commandBuffer = m_pCommandPool->BeginSingleTimeCommands();
VkClearValue clearValues[2];
clearValues[1].color = { 0.5f, 0.5f, 0.5f, 0.f };
clearValues[0].depthStencil = { 0.f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = {};
renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassBeginInfo.renderPass = m_pRenderPass->GetHandle();
renderPassBeginInfo.framebuffer = pFramebuffer->GetHandle();
renderPassBeginInfo.renderArea.extent = m_pWindow->GetSurfaceSize();
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
vkCmdBeginRenderPass(commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
// Record Imgui Draw Data and draw funcs into renderpass
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), commandBuffer);
vkCmdEndRenderPass(commandBuffer);
m_pCommandPool->EndSingleTimeCommands(commandBuffer, m_DebugRenderCompleteSemaphore, readyToRenderUISemaphore, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
}
VkSemaphore vkw::DebugUI::GetDebugRenderCompleteSemaphore()
{
return m_DebugRenderCompleteSemaphore;
}
void vkw::DebugUI::Init()
{
//Create Renderpass
std::vector<VkAttachmentDescription> attachments{ 2 };
attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[0].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachments[0].format = m_pDepthStencilBuffer->GetFormat();
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachments[1].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachments[1].format = m_pWindow->GetSurfaceFormat().format;
VkAttachmentReference subPass0DepthStencilAttachment{};
subPass0DepthStencilAttachment.attachment = 0;
subPass0DepthStencilAttachment.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
std::array<VkAttachmentReference, 1> subPass0ColorAttachments{};
subPass0ColorAttachments[0].attachment = 1; //this int is the index of the attachments passed to the renderPass.
subPass0ColorAttachments[0].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
std::vector<VkSubpassDescription> subPasses{ 1 };
subPasses[0].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subPasses[0].colorAttachmentCount = uint32_t(subPass0ColorAttachments.size());
subPasses[0].pColorAttachments = subPass0ColorAttachments.data();
subPasses[0].pDepthStencilAttachment = &subPass0DepthStencilAttachment;
std::vector<VkSubpassDependency> dependencies{ 1 };
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = 0;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
m_pRenderPass = new RenderPass(m_pDevice, attachments, subPasses, dependencies);
VkDescriptorPoolSize descriptorPoolSize{};
descriptorPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorPoolSize.descriptorCount = 1;
VkDescriptorPoolCreateInfo descriptorPoolInfo{};
descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descriptorPoolInfo.poolSizeCount = 1;
descriptorPoolInfo.pPoolSizes = &descriptorPoolSize;
descriptorPoolInfo.maxSets = uint32_t(m_pSwapchain->GetImageCount());
ErrorCheck(vkCreateDescriptorPool(m_pDevice->GetDevice(), &descriptorPoolInfo, nullptr, &m_DescriptorPool));
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
io.Fonts->AddFontDefault();
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForVulkan(m_pWindow->GetWindowPtr(), true);
ImGui_ImplVulkan_InitInfo init_info = {};
init_info.Instance = m_pDevice->GetInstance();
init_info.PhysicalDevice = m_pDevice->GetPhysicalDevice();
init_info.Device = m_pDevice->GetDevice();
init_info.QueueFamily = m_pDevice->GetGraphicsFamilyQueueId();
init_info.Queue = m_pDevice->GetQueue();
init_info.PipelineCache = VK_NULL_HANDLE;
init_info.DescriptorPool = m_DescriptorPool;
init_info.Allocator = VK_NULL_HANDLE;
init_info.MinImageCount = uint32_t(m_pSwapchain->GetImageCount());
init_info.ImageCount = uint32_t(m_pSwapchain->GetImageCount());
init_info.CheckVkResultFn = ErrorCheck;
ImGui_ImplVulkan_Init(&init_info, m_pRenderPass->GetHandle());
VkCommandBuffer cmdBuffer = m_pCommandPool->BeginSingleTimeCommands();
ImGui_ImplVulkan_CreateFontsTexture(cmdBuffer);
m_pCommandPool->EndSingleTimeCommands(cmdBuffer);
VkSemaphoreCreateInfo semaphoreCreateInfo{};
semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
ErrorCheck(vkCreateSemaphore(m_pDevice->GetDevice(), &semaphoreCreateInfo, nullptr, &m_DebugRenderCompleteSemaphore));
}
void vkw::DebugUI::Cleanup()
{
ErrorCheck(vkDeviceWaitIdle(m_pDevice->GetDevice()));
ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
delete m_pRenderPass;
vkDestroyDescriptorPool(m_pDevice->GetDevice(), m_DescriptorPool, nullptr);
vkDestroySemaphore(m_pDevice->GetDevice(), m_DebugRenderCompleteSemaphore, nullptr);
}
|
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
char change_case(char c)
{
if(int(c) >=65 && int(c) <=90)
c = tolower(c);
else c = toupper(c);
return c;
}
int main()
{
string input;
string output;
getline(cin,input);
output = input;
int i = 1;
for( ; i<input.length();i++)
{
if(int(input.at(i)) >=65 && int(input.at(i)) <=90)
continue;
else break;
}
if(i == input.length())
{
transform(input.begin(),input.end(),output.begin(),change_case);
}
cout<<output;
return 0;
}
|
#include "WindowsOpenGlWindow.h"
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <assert.h>
#include "Common/Macros.h"
#include "Messenger/Messenger.h"
#include "Windows Input/WindowsInputMessage.h"
#include "Messenger/TypedMessage.h"
#include "Window/WindowImplementation.h"
CWindowsOpenGlWindow* CWindowsOpenGlWindow::ms_pCurrentWindow( NULL );
i32 CWindowsOpenGlWindow::ms_iNextChildWindowIdentifier( 0 );
CWindowsCallbackTable CWindowsOpenGlWindow::ms_oWindowsCallbackTable( 10, NULL );
CWindowImplementation* NWindow::ImplementWindow( const i8* kpWindowName, i32 iX, i32 iY,
f32 fWidth, f32 fHeight, bool bFullscreen, CWindow& rWindow )
{
return new CWindowsOpenGlWindow( kpWindowName, iX, iY, fWidth, fHeight, bFullscreen, rWindow );
}
u32 CWindowsOpenGlWindow::GetMaxTitleSize()
{
return ms_kuMaxTitleSize;
}
i32 CWindowsOpenGlWindow::GetNextChildWindowIdentifier()
{
return ms_iNextChildWindowIdentifier++;
}
void CWindowsOpenGlWindow::SetCurrentWindow( CWindowsOpenGlWindow& rWindow )
{
ms_pCurrentWindow = &rWindow;
}
CWindowsOpenGlWindow::CWindowsOpenGlWindow( const i8* pTitle, i32 iX, i32 iY,
f32 fWidth, f32 fHeight, bool bFullscreen, CWindow& rWindow )
: CWindowImplementation( fWidth, fHeight, bFullscreen, rWindow )
, m_uWindowStyle( 0 )
, m_uWindowStyleExtended( 0 )
, m_bIsTerminating( false )
, m_oCallback( &CWindowsOpenGlWindow::WindowsCallback )
{
m_oCallback.SetContext( this );
assert( strlen( pTitle ) < ms_kuMaxTitleSize );
strcpy_s( m_aTitle, pTitle );
memset( &m_oWindowClass, 0, sizeof( m_oWindowClass ) );
memset( &m_oDeviceContext, 0, sizeof( m_oDeviceContext ) );
ms_pCurrentWindow = this;
m_oInstance = GetModuleHandle( NULL );
assert( m_oInstance );
m_oWindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
m_oWindowClass.lpfnWndProc = GlobalWindowsCallback;
m_oWindowClass.cbClsExtra = 0;
m_oWindowClass.cbWndExtra = 0;
m_oWindowClass.hInstance = m_oInstance;
m_oWindowClass.hIcon = LoadIcon( NULL, IDI_WINLOGO );
m_oWindowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
m_oWindowClass.hbrBackground = NULL;
m_oWindowClass.lpszMenuName = NULL;
m_oWindowClass.lpszClassName = m_aTitle;
if ( !RegisterClass( &m_oWindowClass ) )
{
assert( false );
}
if( IsFullscreen() )
{
m_uWindowStyleExtended = WS_EX_APPWINDOW;
m_uWindowStyle = WS_POPUP;
ShowCursor( TRUE );
DEVMODE dmScreenSettings;
memset( &dmScreenSettings,0,sizeof( dmScreenSettings ) );
dmScreenSettings.dmSize = sizeof( dmScreenSettings );
dmScreenSettings.dmPelsWidth = static_cast< u32 >( GetWidth() );
dmScreenSettings.dmPelsHeight = static_cast< u32 >( GetHeight() );
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
i32 iReturn( ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN ) );
if ( iReturn != DISP_CHANGE_SUCCESSFUL )
{
assert( iReturn != DISP_CHANGE_BADDUALVIEW );
assert( iReturn != DISP_CHANGE_BADFLAGS );
assert( iReturn != DISP_CHANGE_BADMODE );
assert( iReturn != DISP_CHANGE_BADPARAM );
assert( iReturn != DISP_CHANGE_FAILED );
assert( iReturn != DISP_CHANGE_NOTUPDATED );
assert( iReturn != DISP_CHANGE_RESTART );
assert( false );
}
}
else
{
m_uWindowStyleExtended=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
m_uWindowStyle=WS_OVERLAPPEDWINDOW;
}
RECT WindowRect;
WindowRect.left=(long)iX;
WindowRect.right=iX + (long)GetWidth();
WindowRect.top=(long)iY;
WindowRect.bottom=iY + (long)GetHeight();
if( !AdjustWindowRectEx( &WindowRect, m_uWindowStyle, false, m_uWindowStyleExtended ) )
{
assert( false );
}
m_oWindowHandle = CreateWindowEx( m_uWindowStyleExtended, TEXT( pTitle ), TEXT( pTitle ),
WS_CLIPSIBLINGS | WS_CLIPCHILDREN | m_uWindowStyle, iX, iY,
WindowRect.right-WindowRect.left, WindowRect.bottom-WindowRect.top,
NULL, NULL, m_oInstance, NULL );
if( !m_oWindowHandle )
{
DWORD uError( GetLastError() );
DEBUG_MESSAGE( "Error in CreateWindowEx (%d)\n", uError );
assert( false );
}
ms_oWindowsCallbackTable.Store( m_oWindowHandle, &m_oCallback );
m_oDeviceContext = GetDC( m_oWindowHandle );
assert( m_oDeviceContext );
static PIXELFORMATDESCRIPTOR oPixelFormatDescriptor =
{
sizeof( PIXELFORMATDESCRIPTOR ), 1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA,
ms_kiBitsPerPixel, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32/*16*/, 0, 0,
PFD_MAIN_PLANE, 0, 0, 0, 0
};
i32 iPixelFormat( ChoosePixelFormat( m_oDeviceContext, &oPixelFormatDescriptor ) );
assert( iPixelFormat );
if( !SetPixelFormat( m_oDeviceContext, iPixelFormat, &oPixelFormatDescriptor ) )
{
assert( false );
}
m_oRenderingContext = wglCreateContext( m_oDeviceContext );
assert( m_oRenderingContext );
if( !wglMakeCurrent( m_oDeviceContext, m_oRenderingContext ) )
{
assert( false );
}
Resize( GetWidth(), GetHeight() );
}
CWindowsOpenGlWindow::~CWindowsOpenGlWindow()
{
assert( !m_oRenderingContext && !m_oDeviceContext && !m_oWindowHandle &&
!m_oInstance );
}
void CWindowsOpenGlWindow::Terminate()
{
// Let everyone know that this window is terminating:
TTypedMessage< CWindow* > oClosedMessage( CWindow::GetWindowClosedMessageUID(), &GetWindow() );
CMessenger::GlobalPush( oClosedMessage );
// The above message may have triggered the termination of the window,
// so only proceed if the window still exists:
if( !m_oDeviceContext )
{
return;
}
if( IsFullscreen() )
{
ChangeDisplaySettings( NULL, 0 );
ShowCursor( TRUE );
}
if ( wglMakeCurrent( NULL, NULL ) )
{
if( !wglDeleteContext( m_oRenderingContext ) )
{
assert( false );
}
}
m_oRenderingContext = NULL;
if( !ReleaseDC( m_oWindowHandle, m_oDeviceContext ) )
{
assert( false );
}
m_oDeviceContext = NULL;
assert( m_oWindowHandle );
if( !DestroyWindow( m_oWindowHandle ) )
{
assert( false );
}
m_oWindowHandle = NULL;
if( !UnregisterClass( m_oWindowClass.lpszClassName, m_oInstance ) )
{
assert( false );
}
m_oInstance = NULL;
TTypedMessage< CWindow* > oDestroyedMessage( CWindow::GetWindowDestroyedMessageUID(),
&GetWindow() );
CMessenger::GlobalPush( oDestroyedMessage );
}
void CWindowsOpenGlWindow::Draw() const
{
assert( m_oDeviceContext && m_oRenderingContext );
// Prepare to draw:
if( !wglMakeCurrent( m_oDeviceContext, m_oRenderingContext ) )
{
assert( false );
}
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// Draw the 3D scene:
CWindowImplementation::Draw();
// Switch to 2D mode:
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho( -1, 1 , 1 , -1, -1, 1 );
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
// Draw the 2D HUD:
CWindowImplementation::Draw2D();
// Switch back to 3D mode:
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glEnable(GL_DEPTH_TEST);
glDepthFunc( GL_LEQUAL );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
glDepthMask(GL_TRUE);
// Finish up:
SwapBuffers( m_oDeviceContext );
return;
}
bool CWindowsOpenGlWindow::IsOpen() const
{
if( m_oWindowHandle )
{
return true;
}
else
{
return false;
}
}
HWND CWindowsOpenGlWindow::GetWindowHandle() const
{
return m_oWindowHandle;
}
void CWindowsOpenGlWindow::Resize( f32 fNewWidth, f32 fNewHeight )
{
CWindowImplementation::Resize( fNewWidth, fNewHeight );
glViewport( 0, 0, static_cast< GLsizei >( fNewWidth ),
static_cast< GLsizei >( fNewHeight ) );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 45.0f, fNewWidth / fNewHeight, 1.f, 200.f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glEnable( GL_TEXTURE_2D );
glShadeModel( GL_SMOOTH );
glClearColor( 0.3f, 0.3f, 0.3f, 0.5f );
glClearDepth( 1.0f );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
glDepthMask(GL_TRUE);
}
const i8* CWindowsOpenGlWindow::GetName() const
{
return m_aTitle;
}
u64 CWindowsOpenGlWindow::GetWindowUID() const
{
return reinterpret_cast< u64 >( GetWindowHandle() );
}
void CWindowsOpenGlWindow::Activate()
{
if( !wglMakeCurrent( m_oDeviceContext, m_oRenderingContext ) )
{
assert( false );
}
}
void CWindowsOpenGlWindow::Show()
{
ShowWindow( m_oWindowHandle, SW_SHOW );
SetForegroundWindow( m_oWindowHandle );
SetFocus( m_oWindowHandle );
}
void CWindowsOpenGlWindow::SetDirty()
{
Draw();
}
LRESULT CALLBACK CWindowsOpenGlWindow::GlobalWindowsCallback( HWND oWindowHandle,
u32 uMessage, WPARAM oParameter1, LPARAM oParameter2 )
{
CWindowsCallback* pCallback( NULL );
u16 uNumFound( ms_oWindowsCallbackTable.Retrieve( oWindowHandle, &pCallback, 1 ) );
// There should be one callback per window handle. If not, there's a problem.
if( uNumFound > 0 )
{
assert( uNumFound == 1 );
assert( pCallback );
return pCallback->Call( oWindowHandle, uMessage, oParameter1, oParameter2 );
}
return DefWindowProc( oWindowHandle, uMessage, oParameter1, oParameter2 );
}
LRESULT CWindowsOpenGlWindow::WindowsCallback( HWND oWindowHandle, u32 uMessage,
WPARAM oParameter1, LPARAM oParameter2 )
{
switch( uMessage )
{
case WM_QUIT:
break;
case WM_CLOSE:
Terminate();
break;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_DESTROY:
case WM_SIZE:
case WM_KEYDOWN:
case WM_KEYUP:
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MOUSEMOVE:
case WM_CAPTURECHANGED:
{
if( uMessage == WM_LBUTTONDOWN || uMessage == WM_RBUTTONDOWN )
SetCapture( m_oWindowHandle );
else if( uMessage == WM_LBUTTONUP || uMessage == WM_RBUTTONUP )
ReleaseCapture();
CWindowsInputMessage oWindowsInputMessage(
&GetWindow(), uMessage, oParameter1, oParameter2 );
CMessenger::GlobalPush( oWindowsInputMessage );
break;
}
case WM_COMMAND:
{
CMessage oMessage( oParameter1 );
CMessenger::GlobalPush( oMessage );
break;
}
}
return DefWindowProc( oWindowHandle, uMessage, oParameter1, oParameter2 );
}
void CWindowsOpenGlWindow::SetWindowHandle( HWND oWindowHandle )
{
m_oWindowHandle = oWindowHandle;
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** 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 3
//** 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
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "model.h"
#include "../main.h"
#include "../backend.h"
#include "../surfaces.h"
#include "../cvars.h"
#include "../state.h"
#include "../light.h"
#include "../skin.h"
#include "skeletal_model_inlines.h"
#include "../../../common/Common.h"
#include "../../../common/common_defs.h"
#include "../../../common/strings.h"
#include "../../../common/endian.h"
/*
All bones should be an identity orientation to display the mesh exactly
as it is specified.
For all other frames, the bones represent the transformation from the
orientation of the bone in the base frame to the orientation in this
frame.
*/
//#define HIGH_PRECISION_BONES // enable this for 32bit precision bones
//#define DBG_PROFILE_BONES
#define ANGLES_SHORT_TO_FLOAT( pf, sh ) { *( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = SHORT2ANGLE( *( sh++ ) ); }
#ifdef DBG_PROFILE_BONES
#define DBG_SHOWTIME common->Printf( "%i: %i, ", di++, ( dt = Sys_Milliseconds() ) - ldt ); ldt = dt;
#else
#define DBG_SHOWTIME ;
#endif
//-----------------------------------------------------------------------------
// Static Vars, ugly but easiest (and fastest) means of seperating RB_SurfaceAnimMds
// and R_CalcBones
struct mdsBoneFrame_t {
float matrix[ 3 ][ 3 ]; // 3x3 rotation
vec3_t translation; // translation vector
};
static float frontlerp, backlerp;
static float torsoFrontlerp, torsoBacklerp;
static int* triangles, * boneRefs;
static glIndex_t* pIndexes;
static int indexes;
static int baseIndex, baseVertex, oldIndexes;
static int numVerts;
static mdsVertex_t* v;
static mdsBoneFrame_t bones[ MDS_MAX_BONES ], rawBones[ MDS_MAX_BONES ], oldBones[ MDS_MAX_BONES ];
static char validBones[ MDS_MAX_BONES ];
static char newBones[ MDS_MAX_BONES ];
static mdsBoneFrame_t* bonePtr, * bone, * parentBone;
static mdsBoneFrameCompressed_t* cBonePtr, * cTBonePtr, * cOldBonePtr, * cOldTBonePtr, * cBoneList, * cOldBoneList, * cBoneListTorso, * cOldBoneListTorso;
static mdsBoneInfo_t* boneInfo, * thisBoneInfo, * parentBoneInfo;
static mdsFrame_t* frame, * torsoFrame;
static mdsFrame_t* oldFrame, * oldTorsoFrame;
static int frameSize;
static short* sh, * sh2;
static float* pf;
static vec3_t angles, tangles, torsoParentOffset, torsoAxis[ 3 ], tmpAxis[ 3 ];
static float* tempVert, * tempNormal;
static vec3_t vec, v2, dir;
static float diff, a1, a2;
static int render_count;
static float lodRadius, lodScale;
static int* collapse_map, * pCollapseMap;
static int collapse[ MDS_MAX_VERTS ], * pCollapse;
static int p0, p1, p2;
static bool isTorso, fullTorso;
static vec4_t m1[ 4 ], m2[ 4 ];
static vec3_t t;
static refEntity_t lastBoneEntity;
static int totalrv, totalrt, totalv, totalt; //----(SA)
void R_FreeMds( idRenderModel* mod ) {
delete[] mod->q3_mdsSurfaces;
Mem_Free( mod->q3_mds );
}
static int R_CullModel( mdsHeader_t* header, trRefEntity_t* ent ) {
int frameSize = ( int )( sizeof ( mdsFrame_t ) - sizeof ( mdsBoneFrameCompressed_t ) + header->numBones * sizeof ( mdsBoneFrameCompressed_t ) );
// compute frame pointers
mdsFrame_t* newFrame = ( mdsFrame_t* )( ( byte* )header + header->ofsFrames + ent->e.frame * frameSize );
mdsFrame_t* oldFrame = ( mdsFrame_t* )( ( byte* )header + header->ofsFrames + ent->e.oldframe * frameSize );
// cull bounding sphere ONLY if this is not an upscaled entity
if ( !ent->e.nonNormalizedAxes ) {
if ( ent->e.frame == ent->e.oldframe ) {
switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) ) {
case CULL_OUT:
tr.pc.c_sphere_cull_md3_out++;
return CULL_OUT;
case CULL_IN:
tr.pc.c_sphere_cull_md3_in++;
return CULL_IN;
case CULL_CLIP:
tr.pc.c_sphere_cull_md3_clip++;
break;
}
} else {
int sphereCull, sphereCullB;
sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius );
if ( newFrame == oldFrame ) {
sphereCullB = sphereCull;
} else {
sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius );
}
if ( sphereCull == sphereCullB ) {
if ( sphereCull == CULL_OUT ) {
tr.pc.c_sphere_cull_md3_out++;
return CULL_OUT;
} else if ( sphereCull == CULL_IN ) {
tr.pc.c_sphere_cull_md3_in++;
return CULL_IN;
} else {
tr.pc.c_sphere_cull_md3_clip++;
}
}
}
}
// calculate a bounding box in the current coordinate system
vec3_t bounds[ 2 ];
for ( int i = 0; i < 3; i++ ) {
bounds[ 0 ][ i ] = oldFrame->bounds[ 0 ][ i ] < newFrame->bounds[ 0 ][ i ] ? oldFrame->bounds[ 0 ][ i ] : newFrame->bounds[ 0 ][ i ];
bounds[ 1 ][ i ] = oldFrame->bounds[ 1 ][ i ] > newFrame->bounds[ 1 ][ i ] ? oldFrame->bounds[ 1 ][ i ] : newFrame->bounds[ 1 ][ i ];
}
switch ( R_CullLocalBox( bounds ) ) {
case CULL_IN:
tr.pc.c_box_cull_md3_in++;
return CULL_IN;
case CULL_CLIP:
tr.pc.c_box_cull_md3_clip++;
return CULL_CLIP;
case CULL_OUT:
default:
tr.pc.c_box_cull_md3_out++;
return CULL_OUT;
}
}
static int R_ComputeFogNum( mdsHeader_t* header, trRefEntity_t* ent ) {
if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) {
return 0;
}
// FIXME: non-normalized axis issues
mdsFrame_t* mdsFrame = ( mdsFrame_t* )( ( byte* )header + header->ofsFrames + ( sizeof ( mdsFrame_t ) + sizeof ( mdsBoneFrameCompressed_t ) * ( header->numBones - 1 ) ) * ent->e.frame );
vec3_t localOrigin;
VectorAdd( ent->e.origin, mdsFrame->localOrigin, localOrigin );
for ( int i = 1; i < tr.world->numfogs; i++ ) {
mbrush46_fog_t* fog = &tr.world->fogs[ i ];
int j;
for ( j = 0; j < 3; j++ ) {
if ( localOrigin[ j ] - mdsFrame->radius >= fog->bounds[ 1 ][ j ] ) {
break;
}
if ( localOrigin[ j ] + mdsFrame->radius <= fog->bounds[ 0 ][ j ] ) {
break;
}
}
if ( j == 3 ) {
return i;
}
}
return 0;
}
void R_AddMdsAnimSurfaces( trRefEntity_t* ent ) {
int i, fogNum, cull;
qboolean personalModel;
// don't add third_person objects if not in a portal
personalModel = ( ent->e.renderfx & RF_THIRD_PERSON ) && !tr.viewParms.isPortal;
mdsHeader_t* header = tr.currentModel->q3_mds;
//
// cull the entire model if merged bounding box of both frames
// is outside the view frustum.
//
cull = R_CullModel( header, ent );
if ( cull == CULL_OUT ) {
return;
}
//
// set up lighting now that we know we aren't culled
//
if ( !personalModel || r_shadows->integer > 1 ) {
R_SetupEntityLighting( &tr.refdef, ent );
}
//
// see if we are in a fog volume
//
fogNum = R_ComputeFogNum( header, ent );
for ( i = 0; i < header->numSurfaces; i++ ) {
idSurfaceMDS* surface = &tr.currentModel->q3_mdsSurfaces[ i ];
mdsSurface_t* surfaceData = surface->GetMdsData();
//----(SA) blink will change to be an overlay rather than replacing the head texture.
// think of it like batman's mask. the polygons that have eye texture are duplicated
// and the 'lids' rendered with polygonoffset over the top of the open eyes. this gives
// minimal overdraw/alpha blending/texture use without breaking the model and causing seams
if ( GGameType & GAME_WolfSP && !String::ICmp( surfaceData->name, "h_blink" ) ) {
if ( !( ent->e.renderfx & RF_BLINK ) ) {
continue;
}
}
shader_t* shader = 0;
if ( ent->e.customShader ) {
shader = R_GetShaderByHandle( ent->e.customShader );
} else if ( ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins ) {
skin_t* skin;
int j;
skin = R_GetSkinByHandle( ent->e.customSkin );
// match the surface name to something in the skin file
shader = tr.defaultShader;
if ( GGameType & ( GAME_WolfMP | GAME_ET ) && ent->e.renderfx & RF_BLINK ) {
const char* s = va( "%s_b", surfaceData->name ); // append '_b' for 'blink'
int hash = Com_HashKey( s, String::Length( s ) );
for ( j = 0; j < skin->numSurfaces; j++ ) {
if ( GGameType & GAME_ET && hash != skin->surfaces[ j ]->hash ) {
continue;
}
if ( !String::Cmp( skin->surfaces[ j ]->name, s ) ) {
shader = skin->surfaces[ j ]->shader;
break;
}
}
}
if ( shader == tr.defaultShader ) { // blink reference in skin was not found
int hash = Com_HashKey( surfaceData->name, sizeof ( surfaceData->name ) );
for ( j = 0; j < skin->numSurfaces; j++ ) {
// the names have both been lowercased
if ( GGameType & GAME_ET && hash != skin->surfaces[ j ]->hash ) {
continue;
}
if ( !String::Cmp( skin->surfaces[ j ]->name, surfaceData->name ) ) {
shader = skin->surfaces[ j ]->shader;
break;
}
}
}
if ( shader == tr.defaultShader ) {
common->DPrintf( S_COLOR_RED "WARNING: no shader for surface %s in skin %s\n", surfaceData->name, skin->name );
} else if ( shader->defaultShader ) {
common->DPrintf( S_COLOR_RED "WARNING: shader %s in skin %s not found\n", shader->name, skin->name );
}
} else {
shader = R_GetShaderByHandle( surfaceData->shaderIndex );
}
// don't add third_person objects if not viewing through a portal
if ( !personalModel ) {
// GR - always tessellate these objects
R_AddDrawSurf( surface, shader, fogNum, false, 0, ATI_TESS_TRUFORM, 0 );
}
}
}
static void R_CalcBone( mdsHeader_t* header, const refEntity_t* refent, int boneNum ) {
thisBoneInfo = &boneInfo[ boneNum ];
if ( thisBoneInfo->torsoWeight ) {
cTBonePtr = &cBoneListTorso[ boneNum ];
isTorso = true;
if ( thisBoneInfo->torsoWeight == 1.0f ) {
fullTorso = true;
}
} else {
isTorso = false;
fullTorso = false;
}
cBonePtr = &cBoneList[ boneNum ];
bonePtr = &bones[ boneNum ];
// we can assume the parent has already been uncompressed for this frame + lerp
if ( thisBoneInfo->parent >= 0 ) {
parentBone = &bones[ thisBoneInfo->parent ];
parentBoneInfo = &boneInfo[ thisBoneInfo->parent ];
} else {
parentBone = NULL;
parentBoneInfo = NULL;
}
#ifdef HIGH_PRECISION_BONES
// rotation
if ( fullTorso ) {
VectorCopy( cTBonePtr->angles, angles );
} else {
VectorCopy( cBonePtr->angles, angles );
if ( isTorso ) {
VectorCopy( cTBonePtr->angles, tangles );
// blend the angles together
for ( int j = 0; j < 3; j++ ) {
diff = tangles[ j ] - angles[ j ];
if ( idMath::Fabs( diff ) > 180 ) {
diff = AngleNormalize180( diff );
}
angles[ j ] = angles[ j ] + thisBoneInfo->torsoWeight * diff;
}
}
}
#else
// rotation
if ( fullTorso ) {
sh = ( short* )cTBonePtr->angles;
pf = angles;
ANGLES_SHORT_TO_FLOAT( pf, sh );
} else {
sh = ( short* )cBonePtr->angles;
pf = angles;
ANGLES_SHORT_TO_FLOAT( pf, sh );
if ( isTorso ) {
sh = ( short* )cTBonePtr->angles;
pf = tangles;
ANGLES_SHORT_TO_FLOAT( pf, sh );
// blend the angles together
for ( int j = 0; j < 3; j++ ) {
diff = tangles[ j ] - angles[ j ];
if ( idMath::Fabs( diff ) > 180 ) {
diff = AngleNormalize180( diff );
}
angles[ j ] = angles[ j ] + thisBoneInfo->torsoWeight * diff;
}
}
}
#endif
AnglesToAxis( angles, bonePtr->matrix );
// translation
if ( parentBone ) {
#ifdef HIGH_PRECISION_BONES
if ( fullTorso ) {
angles[ 0 ] = cTBonePtr->ofsAngles[ 0 ];
angles[ 1 ] = cTBonePtr->ofsAngles[ 1 ];
angles[ 2 ] = 0;
LocalAngleVector( angles, vec );
LocalVectorMA( parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation );
} else {
angles[ 0 ] = cBonePtr->ofsAngles[ 0 ];
angles[ 1 ] = cBonePtr->ofsAngles[ 1 ];
angles[ 2 ] = 0;
LocalAngleVector( angles, vec );
if ( isTorso ) {
tangles[ 0 ] = cTBonePtr->ofsAngles[ 0 ];
tangles[ 1 ] = cTBonePtr->ofsAngles[ 1 ];
tangles[ 2 ] = 0;
LocalAngleVector( tangles, v2 );
// blend the angles together
SLerp_Normal( vec, v2, thisBoneInfo->torsoWeight, vec );
LocalVectorMA( parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation );
} else { // legs bone
LocalVectorMA( parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation );
}
}
#else
if ( fullTorso ) {
sh = ( short* )cTBonePtr->ofsAngles; pf = angles;
*( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = 0;
LocalAngleVector( angles, vec );
LocalVectorMA( parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation );
} else {
sh = ( short* )cBonePtr->ofsAngles; pf = angles;
*( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = 0;
LocalAngleVector( angles, vec );
if ( isTorso ) {
sh = ( short* )cTBonePtr->ofsAngles;
pf = tangles;
*( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = SHORT2ANGLE( *( sh++ ) ); *( pf++ ) = 0;
LocalAngleVector( tangles, v2 );
// blend the angles together
SLerp_Normal( vec, v2, thisBoneInfo->torsoWeight, vec );
LocalVectorMA( parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation );
} else { // legs bone
LocalVectorMA( parentBone->translation, thisBoneInfo->parentDist, vec, bonePtr->translation );
}
}
#endif
} else { // just use the frame position
bonePtr->translation[ 0 ] = frame->parentOffset[ 0 ];
bonePtr->translation[ 1 ] = frame->parentOffset[ 1 ];
bonePtr->translation[ 2 ] = frame->parentOffset[ 2 ];
}
//
if ( boneNum == header->torsoParent ) {
// this is the torsoParent
VectorCopy( bonePtr->translation, torsoParentOffset );
}
//
validBones[ boneNum ] = 1;
//
rawBones[ boneNum ] = *bonePtr;
newBones[ boneNum ] = 1;
}
static void R_CalcBoneLerp( mdsHeader_t* header, const refEntity_t* refent, int boneNum ) {
if ( !refent || !header || boneNum < 0 || boneNum >= MDS_MAX_BONES ) {
return;
}
thisBoneInfo = &boneInfo[ boneNum ];
if ( thisBoneInfo->parent >= 0 ) {
parentBone = &bones[ thisBoneInfo->parent ];
parentBoneInfo = &boneInfo[ thisBoneInfo->parent ];
} else {
parentBone = NULL;
parentBoneInfo = NULL;
}
if ( thisBoneInfo->torsoWeight ) {
cTBonePtr = &cBoneListTorso[ boneNum ];
cOldTBonePtr = &cOldBoneListTorso[ boneNum ];
isTorso = true;
if ( thisBoneInfo->torsoWeight == 1.0f ) {
fullTorso = true;
}
} else {
isTorso = false;
fullTorso = false;
}
cBonePtr = &cBoneList[ boneNum ];
cOldBonePtr = &cOldBoneList[ boneNum ];
bonePtr = &bones[ boneNum ];
newBones[ boneNum ] = 1;
// rotation (take into account 170 to -170 lerps, which need to take the shortest route)
if ( fullTorso ) {
sh = ( short* )cTBonePtr->angles;
sh2 = ( short* )cOldTBonePtr->angles;
pf = angles;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - torsoBacklerp * diff;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - torsoBacklerp * diff;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - torsoBacklerp * diff;
} else {
sh = ( short* )cBonePtr->angles;
sh2 = ( short* )cOldBonePtr->angles;
pf = angles;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - backlerp * diff;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - backlerp * diff;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - backlerp * diff;
if ( isTorso ) {
sh = ( short* )cTBonePtr->angles;
sh2 = ( short* )cOldTBonePtr->angles;
pf = tangles;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - torsoBacklerp * diff;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - torsoBacklerp * diff;
a1 = SHORT2ANGLE( *( sh++ ) ); a2 = SHORT2ANGLE( *( sh2++ ) ); diff = AngleNormalize180( a1 - a2 );
*( pf++ ) = a1 - torsoBacklerp * diff;
// blend the angles together
for ( int j = 0; j < 3; j++ ) {
diff = tangles[ j ] - angles[ j ];
if ( idMath::Fabs( diff ) > 180 ) {
diff = AngleNormalize180( diff );
}
angles[ j ] = angles[ j ] + thisBoneInfo->torsoWeight * diff;
}
}
}
AnglesToAxis( angles, bonePtr->matrix );
if ( parentBone ) {
if ( fullTorso ) {
sh = ( short* )cTBonePtr->ofsAngles;
sh2 = ( short* )cOldTBonePtr->ofsAngles;
} else {
sh = ( short* )cBonePtr->ofsAngles;
sh2 = ( short* )cOldBonePtr->ofsAngles;
}
pf = angles;
*( pf++ ) = SHORT2ANGLE( *( sh++ ) );
*( pf++ ) = SHORT2ANGLE( *( sh++ ) );
*( pf++ ) = 0;
LocalAngleVector( angles, v2 ); // new
pf = angles;
*( pf++ ) = SHORT2ANGLE( *( sh2++ ) );
*( pf++ ) = SHORT2ANGLE( *( sh2++ ) );
*( pf++ ) = 0;
LocalAngleVector( angles, vec ); // old
// blend the angles together
if ( fullTorso ) {
SLerp_Normal( vec, v2, torsoFrontlerp, dir );
} else {
SLerp_Normal( vec, v2, frontlerp, dir );
}
// translation
if ( !fullTorso && isTorso ) {
// partial legs/torso, need to lerp according to torsoWeight
// calc the torso frame
sh = ( short* )cTBonePtr->ofsAngles;
sh2 = ( short* )cOldTBonePtr->ofsAngles;
pf = angles;
*( pf++ ) = SHORT2ANGLE( *( sh++ ) );
*( pf++ ) = SHORT2ANGLE( *( sh++ ) );
*( pf++ ) = 0;
LocalAngleVector( angles, v2 ); // new
pf = angles;
*( pf++ ) = SHORT2ANGLE( *( sh2++ ) );
*( pf++ ) = SHORT2ANGLE( *( sh2++ ) );
*( pf++ ) = 0;
LocalAngleVector( angles, vec ); // old
// blend the angles together
SLerp_Normal( vec, v2, torsoFrontlerp, v2 );
// blend the torso/legs together
SLerp_Normal( dir, v2, thisBoneInfo->torsoWeight, dir );
}
LocalVectorMA( parentBone->translation, thisBoneInfo->parentDist, dir, bonePtr->translation );
} else { // just interpolate the frame positions
bonePtr->translation[ 0 ] = frontlerp * frame->parentOffset[ 0 ] + backlerp * oldFrame->parentOffset[ 0 ];
bonePtr->translation[ 1 ] = frontlerp * frame->parentOffset[ 1 ] + backlerp * oldFrame->parentOffset[ 1 ];
bonePtr->translation[ 2 ] = frontlerp * frame->parentOffset[ 2 ] + backlerp * oldFrame->parentOffset[ 2 ];
}
//
if ( boneNum == header->torsoParent ) {
// this is the torsoParent
VectorCopy( bonePtr->translation, torsoParentOffset );
}
validBones[ boneNum ] = 1;
//
rawBones[ boneNum ] = *bonePtr;
newBones[ boneNum ] = 1;
}
// The list of bones[] should only be built and modified from within here
static void R_CalcBones( mdsHeader_t* header, const refEntity_t* refent, int* boneList, int numBones ) {
//
// if the entity has changed since the last time the bones were built, reset them
//
if ( memcmp( &lastBoneEntity, refent, sizeof ( refEntity_t ) ) ) {
// different, cached bones are not valid
Com_Memset( validBones, 0, header->numBones );
lastBoneEntity = *refent;
if ( r_bonesDebug->integer == 4 && totalrt ) {
common->Printf( "Lod %.2f verts %4d/%4d tris %4d/%4d (%.2f%%)\n",
lodScale,
totalrv,
totalv,
totalrt,
totalt,
( float )( 100.0 * totalrt ) / ( float )totalt );
}
totalrv = totalrt = totalv = totalt = 0;
}
Com_Memset( newBones, 0, header->numBones );
if ( refent->oldframe == refent->frame ) {
backlerp = 0;
frontlerp = 1;
} else {
backlerp = refent->backlerp;
frontlerp = 1.0f - backlerp;
}
if ( refent->oldTorsoFrame == refent->torsoFrame ) {
torsoBacklerp = 0;
torsoFrontlerp = 1;
} else {
torsoBacklerp = refent->torsoBacklerp;
torsoFrontlerp = 1.0f - torsoBacklerp;
}
frameSize = ( int )( sizeof ( mdsFrame_t ) + ( header->numBones - 1 ) * sizeof ( mdsBoneFrameCompressed_t ) );
frame = ( mdsFrame_t* )( ( byte* )header + header->ofsFrames + refent->frame * frameSize );
torsoFrame = ( mdsFrame_t* )( ( byte* )header + header->ofsFrames + refent->torsoFrame * frameSize );
oldFrame = ( mdsFrame_t* )( ( byte* )header + header->ofsFrames + refent->oldframe * frameSize );
oldTorsoFrame = ( mdsFrame_t* )( ( byte* )header + header->ofsFrames + refent->oldTorsoFrame * frameSize );
//
// lerp all the needed bones (torsoParent is always the first bone in the list)
//
cBoneList = frame->bones;
cBoneListTorso = torsoFrame->bones;
boneInfo = ( mdsBoneInfo_t* )( ( byte* )header + header->ofsBones );
boneRefs = boneList;
//
Matrix3Transpose( refent->torsoAxis, torsoAxis );
#ifdef HIGH_PRECISION_BONES
if ( true )
#else
if ( !backlerp && !torsoBacklerp )
#endif
{
for ( int i = 0; i < numBones; i++, boneRefs++ ) {
if ( validBones[ *boneRefs ] ) {
// this bone is still in the cache
bones[ *boneRefs ] = rawBones[ *boneRefs ];
continue;
}
// find our parent, and make sure it has been calculated
if ( ( boneInfo[ *boneRefs ].parent >= 0 ) && ( !validBones[ boneInfo[ *boneRefs ].parent ] && !newBones[ boneInfo[ *boneRefs ].parent ] ) ) {
R_CalcBone( header, refent, boneInfo[ *boneRefs ].parent );
}
R_CalcBone( header, refent, *boneRefs );
}
} else {
// interpolated
cOldBoneList = oldFrame->bones;
cOldBoneListTorso = oldTorsoFrame->bones;
for ( int i = 0; i < numBones; i++, boneRefs++ ) {
if ( validBones[ *boneRefs ] ) {
// this bone is still in the cache
bones[ *boneRefs ] = rawBones[ *boneRefs ];
continue;
}
// find our parent, and make sure it has been calculated
if ( ( boneInfo[ *boneRefs ].parent >= 0 ) && ( !validBones[ boneInfo[ *boneRefs ].parent ] && !newBones[ boneInfo[ *boneRefs ].parent ] ) ) {
R_CalcBoneLerp( header, refent, boneInfo[ *boneRefs ].parent );
}
R_CalcBoneLerp( header, refent, *boneRefs );
}
}
// adjust for torso rotations
float torsoWeight = 0;
int* boneRefs = boneList;
for ( int i = 0; i < numBones; i++, boneRefs++ ) {
thisBoneInfo = &boneInfo[ *boneRefs ];
bonePtr = &bones[ *boneRefs ];
// add torso rotation
if ( thisBoneInfo->torsoWeight > 0 ) {
if ( !newBones[ *boneRefs ] ) {
// just copy it back from the previous calc
bones[ *boneRefs ] = oldBones[ *boneRefs ];
continue;
}
if ( !( thisBoneInfo->flags & MDS_BONEFLAG_TAG ) ) {
// 1st multiply with the bone->matrix
// 2nd translation for rotation relative to bone around torso parent offset
VectorSubtract( bonePtr->translation, torsoParentOffset, t );
Matrix4FromAxisPlusTranslation( bonePtr->matrix, t, m1 );
// 3rd scaled rotation
// 4th translate back to torso parent offset
// use previously created matrix if available for the same weight
if ( torsoWeight != thisBoneInfo->torsoWeight ) {
Matrix4FromScaledAxisPlusTranslation( torsoAxis, thisBoneInfo->torsoWeight, torsoParentOffset, m2 );
torsoWeight = thisBoneInfo->torsoWeight;
}
// multiply matrices to create one matrix to do all calculations
Matrix4MultiplyInto3x3AndTranslation( m2, m1, bonePtr->matrix, bonePtr->translation );
} else { // tag's require special handling
// rotate each of the axis by the torsoAngles
LocalScaledMatrixTransformVector( bonePtr->matrix[ 0 ], thisBoneInfo->torsoWeight, torsoAxis, tmpAxis[ 0 ] );
LocalScaledMatrixTransformVector( bonePtr->matrix[ 1 ], thisBoneInfo->torsoWeight, torsoAxis, tmpAxis[ 1 ] );
LocalScaledMatrixTransformVector( bonePtr->matrix[ 2 ], thisBoneInfo->torsoWeight, torsoAxis, tmpAxis[ 2 ] );
Com_Memcpy( bonePtr->matrix, tmpAxis, sizeof ( tmpAxis ) );
// rotate the translation around the torsoParent
VectorSubtract( bonePtr->translation, torsoParentOffset, t );
LocalScaledMatrixTransformVector( t, thisBoneInfo->torsoWeight, torsoAxis, bonePtr->translation );
VectorAdd( bonePtr->translation, torsoParentOffset, bonePtr->translation );
}
}
}
// backup the final bones
Com_Memcpy( oldBones, bones, sizeof ( bones[ 0 ] ) * header->numBones );
}
static float ProjectRadius( float r, vec3_t location ) {
float c = DotProduct( tr.viewParms.orient.axis[ 0 ], tr.viewParms.orient.origin );
float dist = DotProduct( tr.viewParms.orient.axis[ 0 ], location ) - c;
if ( dist <= 0 ) {
return 0;
}
vec3_t p;
p[ 0 ] = 0;
p[ 1 ] = idMath::Fabs( r );
p[ 2 ] = -dist;
float projected[ 4 ];
projected[ 0 ] = p[ 0 ] * tr.viewParms.projectionMatrix[ 0 ] +
p[ 1 ] * tr.viewParms.projectionMatrix[ 4 ] +
p[ 2 ] * tr.viewParms.projectionMatrix[ 8 ] +
tr.viewParms.projectionMatrix[ 12 ];
projected[ 1 ] = p[ 0 ] * tr.viewParms.projectionMatrix[ 1 ] +
p[ 1 ] * tr.viewParms.projectionMatrix[ 5 ] +
p[ 2 ] * tr.viewParms.projectionMatrix[ 9 ] +
tr.viewParms.projectionMatrix[ 13 ];
projected[ 2 ] = p[ 0 ] * tr.viewParms.projectionMatrix[ 2 ] +
p[ 1 ] * tr.viewParms.projectionMatrix[ 6 ] +
p[ 2 ] * tr.viewParms.projectionMatrix[ 10 ] +
tr.viewParms.projectionMatrix[ 14 ];
projected[ 3 ] = p[ 0 ] * tr.viewParms.projectionMatrix[ 3 ] +
p[ 1 ] * tr.viewParms.projectionMatrix[ 7 ] +
p[ 2 ] * tr.viewParms.projectionMatrix[ 11 ] +
tr.viewParms.projectionMatrix[ 15 ];
float pr = projected[ 1 ] / projected[ 3 ];
if ( pr > 1.0f ) {
pr = 1.0f;
}
return pr;
}
static float R_CalcMDSLod( refEntity_t* refent, vec3_t origin, float radius, float modelBias, float modelScale ) {
if ( GGameType & GAME_WolfSP && refent->reFlags & REFLAG_FULL_LOD ) {
return 1.0f;
}
// compute projected bounding sphere and use that as a criteria for selecting LOD
float projectedRadius = ProjectRadius( radius, origin );
float flod;
if ( projectedRadius != 0 ) {
float lodScale = r_lodscale->value; // fudge factor since MDS uses a much smoother method of LOD
flod = projectedRadius * lodScale * modelScale;
} else {
// object intersects near view plane, e.g. view weapon
flod = 1.0f;
}
if ( refent->reFlags & REFLAG_FORCE_LOD ) {
flod *= 0.5;
}
//----(SA) like reflag_force_lod, but separate for the moment
if ( refent->reFlags & REFLAG_DEAD_LOD ) {
flod *= 0.8;
}
flod -= 0.25 * ( r_lodbias->value ) + modelBias;
if ( flod < 0.0 ) {
flod = 0.0;
} else if ( flod > 1.0f ) {
flod = 1.0f;
}
return flod;
}
void RB_SurfaceAnimMds( mdsSurface_t* surface ) {
#ifdef DBG_PROFILE_BONES
int di = 0;
int dt = Sys_Milliseconds();
int ldt = dt;
#endif
refEntity_t* refent = &backEnd.currentEntity->e;
int* boneList = ( int* )( ( byte* )surface + surface->ofsBoneReferences );
mdsHeader_t* header = ( mdsHeader_t* )( ( byte* )surface + surface->ofsHeader );
R_CalcBones( header, ( const refEntity_t* )refent, boneList, surface->numBoneReferences );
DBG_SHOWTIME
//
// calculate LOD
//
// TODO: lerp the radius and origin
VectorAdd( refent->origin, frame->localOrigin, vec );
lodRadius = frame->radius;
lodScale = R_CalcMDSLod( refent, vec, lodRadius, header->lodBias, header->lodScale );
//DBG_SHOWTIME
//----(SA) modification to allow dead skeletal bodies to go below minlod (experiment)
if ( refent->reFlags & REFLAG_DEAD_LOD ) {
if ( lodScale < 0.35 ) {
// allow dead to lod down to 35% (even if below surf->minLod) (%35 is arbitrary and probably not good generally. worked for the blackguard/infantry as a test though)
lodScale = 0.35;
}
render_count = ( int )( ( float )surface->numVerts * lodScale );
} else {
render_count = ( int )( ( float )surface->numVerts * lodScale );
if ( render_count < surface->minLod ) {
if ( !( refent->reFlags & REFLAG_DEAD_LOD ) ) {
render_count = surface->minLod;
}
}
}
//----(SA) end
if ( render_count > surface->numVerts ) {
render_count = surface->numVerts;
}
RB_CheckOverflow( render_count, surface->numTriangles );
//DBG_SHOWTIME
//
// setup triangle list
//
RB_CheckOverflow( surface->numVerts, surface->numTriangles * 3 );
//DBG_SHOWTIME
collapse_map = ( int* )( ( byte* )surface + surface->ofsCollapseMap );
triangles = ( int* )( ( byte* )surface + surface->ofsTriangles );
indexes = surface->numTriangles * 3;
baseIndex = tess.numIndexes;
baseVertex = tess.numVertexes;
oldIndexes = baseIndex;
tess.numVertexes += render_count;
pIndexes = &tess.indexes[ baseIndex ];
//DBG_SHOWTIME
if ( render_count == surface->numVerts ) {
Com_Memcpy( pIndexes, triangles, sizeof ( triangles[ 0 ] ) * indexes );
if ( baseVertex ) {
for ( glIndex_t* indexesEnd = pIndexes + indexes; pIndexes < indexesEnd; pIndexes++ ) {
*pIndexes += baseVertex;
}
}
tess.numIndexes += indexes;
} else {
pCollapse = collapse;
for ( int j = 0; j < render_count; pCollapse++, j++ ) {
*pCollapse = j;
}
pCollapseMap = &collapse_map[ render_count ];
for ( int* collapseEnd = collapse + surface->numVerts; pCollapse < collapseEnd; pCollapse++, pCollapseMap++ ) {
*pCollapse = collapse[ *pCollapseMap ];
}
for ( int j = 0; j < indexes; j += 3 ) {
p0 = collapse[ *( triangles++ ) ];
p1 = collapse[ *( triangles++ ) ];
p2 = collapse[ *( triangles++ ) ];
// FIXME
// note: serious optimization opportunity here,
// by sorting the triangles the following "continue"
// could have been made into a "break" statement.
if ( p0 == p1 || p1 == p2 || p2 == p0 ) {
continue;
}
*( pIndexes++ ) = baseVertex + p0;
*( pIndexes++ ) = baseVertex + p1;
*( pIndexes++ ) = baseVertex + p2;
tess.numIndexes += 3;
}
baseIndex = tess.numIndexes;
}
//DBG_SHOWTIME
//
// deform the vertexes by the lerped bones
//
numVerts = surface->numVerts;
v = ( mdsVertex_t* )( ( byte* )surface + surface->ofsVerts );
tempVert = ( float* )( tess.xyz + baseVertex );
tempNormal = ( float* )( tess.normal + baseVertex );
for ( int j = 0; j < render_count; j++, tempVert += 4, tempNormal += 4 ) {
VectorClear( tempVert );
mdsWeight_t* w = v->weights;
for ( int k = 0; k < v->numWeights; k++, w++ ) {
bone = &bones[ w->boneIndex ];
LocalAddScaledMatrixTransformVectorTranslate( w->offset, w->boneWeight, bone->matrix, bone->translation, tempVert );
}
LocalMatrixTransformVector( v->normal, bones[ v->weights[ 0 ].boneIndex ].matrix, tempNormal );
tess.texCoords[ baseVertex + j ][ 0 ][ 0 ] = v->texCoords[ 0 ];
tess.texCoords[ baseVertex + j ][ 0 ][ 1 ] = v->texCoords[ 1 ];
v = ( mdsVertex_t* )&v->weights[ v->numWeights ];
}
DBG_SHOWTIME
if ( r_bonesDebug->integer ) {
if ( r_bonesDebug->integer < 3 ) {
// DEBUG: show the bones as a stick figure with axis at each bone
boneRefs = ( int* )( ( byte* )surface + surface->ofsBoneReferences );
for ( int i = 0; i < surface->numBoneReferences; i++, boneRefs++ ) {
bonePtr = &bones[ *boneRefs ];
GL_Bind( tr.whiteImage );
qglLineWidth( 1 );
qglBegin( GL_LINES );
for ( int j = 0; j < 3; j++ ) {
VectorClear( vec );
vec[ j ] = 1;
qglColor3fv( vec );
qglVertex3fv( bonePtr->translation );
VectorMA( bonePtr->translation, 5, bonePtr->matrix[ j ], vec );
qglVertex3fv( vec );
}
qglEnd();
// connect to our parent if it's valid
if ( validBones[ boneInfo[ *boneRefs ].parent ] ) {
qglLineWidth( 2 );
qglBegin( GL_LINES );
qglColor3f( .6,.6,.6 );
qglVertex3fv( bonePtr->translation );
qglVertex3fv( bones[ boneInfo[ *boneRefs ].parent ].translation );
qglEnd();
}
qglLineWidth( 1 );
}
}
if ( r_bonesDebug->integer == 3 || r_bonesDebug->integer == 4 ) {
int render_indexes = ( tess.numIndexes - oldIndexes );
// show mesh edges
tempVert = ( float* )( tess.xyz + baseVertex );
tempNormal = ( float* )( tess.normal + baseVertex );
GL_Bind( tr.whiteImage );
qglLineWidth( 1 );
qglBegin( GL_LINES );
qglColor3f( .0, .0, .8 );
pIndexes = &tess.indexes[ oldIndexes ];
for ( int j = 0; j < render_indexes / 3; j++, pIndexes += 3 ) {
qglVertex3fv( tempVert + 4 * pIndexes[ 0 ] );
qglVertex3fv( tempVert + 4 * pIndexes[ 1 ] );
qglVertex3fv( tempVert + 4 * pIndexes[ 1 ] );
qglVertex3fv( tempVert + 4 * pIndexes[ 2 ] );
qglVertex3fv( tempVert + 4 * pIndexes[ 2 ] );
qglVertex3fv( tempVert + 4 * pIndexes[ 0 ] );
}
qglEnd();
//----(SA) track debug stats
if ( r_bonesDebug->integer == 4 ) {
totalrv += render_count;
totalrt += render_indexes / 3;
totalv += surface->numVerts;
totalt += surface->numTriangles;
}
//----(SA) end
if ( r_bonesDebug->integer == 3 ) {
common->Printf( "Lod %.2f verts %4d/%4d tris %4d/%4d (%.2f%%)\n",
lodScale, render_count, surface->numVerts, render_indexes / 3, surface->numTriangles,
( float )( 100.0 * render_indexes / 3 ) / ( float )surface->numTriangles );
}
}
}
if ( r_bonesDebug->integer > 1 ) {
// dont draw the actual surface
tess.numIndexes = oldIndexes;
tess.numVertexes = baseVertex;
return;
}
#ifdef DBG_PROFILE_BONES
common->Printf( "\n" );
#endif
}
static void R_RecursiveBoneListAdd( int bi, int* boneList, int* numBones, mdsBoneInfo_t* boneInfoList ) {
if ( boneInfoList[ bi ].parent >= 0 ) {
R_RecursiveBoneListAdd( boneInfoList[ bi ].parent, boneList, numBones, boneInfoList );
}
boneList[ ( *numBones )++ ] = bi;
}
int R_GetBoneTagMds( orientation_t* outTag, mdsHeader_t* mds, int startTagIndex, const refEntity_t* refent, const char* tagName ) {
if ( startTagIndex > mds->numTags ) {
Com_Memset( outTag, 0, sizeof ( *outTag ) );
return -1;
}
// find the correct tag
mdsTag_t* pTag = ( mdsTag_t* )( ( byte* )mds + mds->ofsTags );
pTag += startTagIndex;
int i;
for ( i = startTagIndex; i < mds->numTags; i++, pTag++ ) {
if ( !String::Cmp( pTag->name, tagName ) ) {
break;
}
}
if ( i >= mds->numTags ) {
Com_Memset( outTag, 0, sizeof ( *outTag ) );
return -1;
}
// now build the list of bones we need to calc to get this tag's bone information
mdsBoneInfo_t* boneInfoList = ( mdsBoneInfo_t* )( ( byte* )mds + mds->ofsBones );
int numBones = 0;
int boneList[ MDS_MAX_BONES ];
R_RecursiveBoneListAdd( pTag->boneIndex, boneList, &numBones, boneInfoList );
// calc the bones
R_CalcBones( ( mdsHeader_t* )mds, refent, boneList, numBones );
// now extract the orientation for the bone that represents our tag
Com_Memcpy( outTag->axis, bones[ pTag->boneIndex ].matrix, sizeof ( outTag->axis ) );
VectorCopy( bones[ pTag->boneIndex ].translation, outTag->origin );
return i;
}
|
/*
* test_suite.h
*
* Created on: Oct 16, 2013
* Author: vbonnici
*/
#ifndef TEST_SUITE_H_
#define TEST_SUITE_H_
/*
* a set of functions for binomial tests, or other distribution
*/
//#define DEBUG_TEST_SUITE_H_
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <limits>
#include "data_ts.h"
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
namespace dolierlib{
/*
* Pietro's binomial test
*/
inline
double dolier_binomial(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
double result = 0;
for(usize_t i = f_dcount; i<=f_total; i++){
result += gsl_ran_binomial_pdf(static_cast<unsigned int>(i), p, static_cast<unsigned int>(f_total));
}
return result;
}
/*
* a more efficient binomial test, thanks to gsl
*/
inline
double dolier_binomial_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
//return gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total));
return gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
+ gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total));
}
/*
* Pietro's binomial test with Bon Ferroni correction
*/
inline
double dolier_binomial_bonf(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
double p = (double)b_dcount / (double)b_total;
double result = 0;
for(usize_t i = f_dcount; i<=f_total; i++){
result += gsl_ran_binomial_pdf(static_cast<unsigned int>(i), p, static_cast<unsigned int>(f_total));
}
return double(nof_kmers) * result;
}
/*
* a more efficient binomial test with Bon Ferroni correction, thanks to gsl
*/
inline
double dolier_binomial_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
double p = (double)b_dcount / (double)b_total;
//return gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total)) * nof_kmers;
return (
gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
+
gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
)
* nof_kmers;
}
/*
* other distributions tried during tests
*/
inline
double dolier_poisson_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
double mu = p * static_cast<double>(f_total);
return gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),mu)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), mu);
// return gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
// + gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total));
}
inline
double dolier_poisson_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
double p = (double)b_dcount / (double)b_total;
double mu = p * static_cast<double>(f_total);
if(mu==0) std::cout<<"#mu=0#\t"<<f_dcount<<"\t"<<f_total<<"\t"<<b_dcount<<"\t"<<b_total<<"\t"<<p<<"\n";
return (gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),mu)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), mu))
* nof_kmers;
// return (
// gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
// +
// gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
// )
// * nof_kmers;
}
inline
double dolier_poisson_mu1_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
return gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),1)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), 1);
}
inline
double dolier_poisson_mu1_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
return (gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),1)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), 1))
* nof_kmers;
}
const double SQRT_PI = sqrt(3.141592653589793238462);
inline
double dolier_normal(double x, double sigma, double mu){
return (1/(sigma * SQRT_PI))*(exp(-(((x-mu)*(x-mu)) / (2*sigma*sigma))));
}
inline
double dolier_approx_binomial(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
double result = 0;
double np = static_cast<double>(f_total) * p;
double npp = np * (1-p);
for(usize_t i = f_dcount; i<=f_total; i++){
result += dolier_normal(static_cast<double>(i), np, npp);
}
return result;
}
inline
double dolier_binomial(unsigned int x, double p, unsigned int total){
return gsl_ran_binomial_pdf(x, p, total);
}
inline
double dolier_normall(unsigned int x, double p, unsigned int total){
double np = static_cast<double>(total) * p;
double npp = np * (1-p);
return dolier_normal(static_cast<double>(x), np, npp);
}
}
#endif /* TEST_SUITE_H_ */
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Graphics.Printing.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Graphics::Printing {
template <typename H> struct impl_PrintTaskSourceRequestedHandler : implements<impl_PrintTaskSourceRequestedHandler<H>, abi<PrintTaskSourceRequestedHandler>>, H
{
impl_PrintTaskSourceRequestedHandler(H && handler) : H(std::forward<H>(handler)) {}
HRESULT __stdcall abi_Invoke(impl::abi_arg_in<Windows::Graphics::Printing::IPrintTaskSourceRequestedArgs> args) noexcept override
{
try
{
(*this)(*reinterpret_cast<const Windows::Graphics::Printing::PrintTaskSourceRequestedArgs *>(&args));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
}
namespace Windows::Graphics::Printing {
struct WINRT_EBO PrintManager :
Windows::Graphics::Printing::IPrintManager
{
PrintManager(std::nullptr_t) noexcept {}
static Windows::Graphics::Printing::PrintManager GetForCurrentView();
static Windows::Foundation::IAsyncOperation<bool> ShowPrintUIAsync();
static bool IsSupported();
};
struct WINRT_EBO PrintPageInfo :
Windows::Graphics::Printing::IPrintPageInfo
{
PrintPageInfo(std::nullptr_t) noexcept {}
PrintPageInfo();
};
struct WINRT_EBO PrintTask :
Windows::Graphics::Printing::IPrintTask,
impl::require<PrintTask, Windows::Graphics::Printing::IPrintTaskTargetDeviceSupport, Windows::Graphics::Printing::IPrintTask2>
{
PrintTask(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskCompletedEventArgs :
Windows::Graphics::Printing::IPrintTaskCompletedEventArgs
{
PrintTaskCompletedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskOptions :
Windows::Graphics::Printing::IPrintTaskOptionsCore,
impl::require<PrintTaskOptions, Windows::Graphics::Printing::IPrintTaskOptionsCoreProperties, Windows::Graphics::Printing::IPrintTaskOptions, Windows::Graphics::Printing::IPrintTaskOptionsCoreUIConfiguration>
{
PrintTaskOptions(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskProgressingEventArgs :
Windows::Graphics::Printing::IPrintTaskProgressingEventArgs
{
PrintTaskProgressingEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskRequest :
Windows::Graphics::Printing::IPrintTaskRequest
{
PrintTaskRequest(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskRequestedDeferral :
Windows::Graphics::Printing::IPrintTaskRequestedDeferral
{
PrintTaskRequestedDeferral(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskRequestedEventArgs :
Windows::Graphics::Printing::IPrintTaskRequestedEventArgs
{
PrintTaskRequestedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskSourceRequestedArgs :
Windows::Graphics::Printing::IPrintTaskSourceRequestedArgs
{
PrintTaskSourceRequestedArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO PrintTaskSourceRequestedDeferral :
Windows::Graphics::Printing::IPrintTaskSourceRequestedDeferral
{
PrintTaskSourceRequestedDeferral(std::nullptr_t) noexcept {}
};
struct StandardPrintTaskOptions
{
StandardPrintTaskOptions() = delete;
static hstring MediaSize();
static hstring MediaType();
static hstring Orientation();
static hstring PrintQuality();
static hstring ColorMode();
static hstring Duplex();
static hstring Collation();
static hstring Staple();
static hstring HolePunch();
static hstring Binding();
static hstring Copies();
static hstring NUp();
static hstring InputBin();
static hstring Bordering();
};
}
}
|
#include "../CWE/CWELib.h"
#include "Game.h"
#include "Information.h"
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
CoInitializeEx(NULL, COINIT_MULTITHREADED);
// 基礎処理機構の初期化
#if defined(_DEBUG) || defined(DEBUG)
const bool initalized =CWE::Init(1920, 1080, true, L"Rapid Cross");
#else
const bool initalized =CWE::Init(1920, 1080, false, L"Rapid Cross");
#endif
// 初期化に失敗したら終了
if(!initalized)
{
CWE::End();
CoUninitialize();
return 0;
}
CWE::Mouse::GetInstance().ResetPointerMode(false);
// ゲームプログラム&ゲームデータの初期化
Game game;
Information& info =Information::GetInfo();
// メインループ
while(CWE::Update() && !(info.mEnded))
{
// ゲーム側の終了リクエストがあったら終了
if(game.Run())
{
break;
}
}
game.End();
CWE::End();
CoUninitialize();
return 0;
}
|
/**
* @file Animating.h
*/
#pragma once
namespace liman {
class Animating {
bool animationUp = false;
float animation1 = 0.0;
int animationType;
};
}
|
#include "Board.hpp"
#include "City.hpp"
#include "Player.hpp"
#include "Scientist.hpp"
#include <array>
using namespace pandemic;
const int MAX_CARDS =48;
const int five = 5;
const int four = 4;
Scientist::Scientist(Board &board, enum City a, int toThrow1){
CurrentCity = a;
theBorad = &board;
toThrow = toThrow1;
}
Player& Scientist::discover_cure(enum Color a){
int count = 0;
if(getCures()[a]){
return *this;
}
if(!getMap()[CurrentCity].theBuild){
throw invalid_argument("no research facility");
}
array <size_t , five> x = {MAX_CARDS};
x.fill(MAX_CARDS);
size_t temp = 0;
for (size_t i = 0; i < MAX_CARDS; i++)
{
if(Cards.at(i) && getMap()[(enum City)i].colorOfCity==a){
count++;
Cards.at(i)=false;
x.at(temp)=i;
temp++;
}
if(count==toThrow){
getCures()[a]=true;
break;
}
}
if(count!=toThrow){
for (size_t i = 0; i < four; i++)
{
if(!(x.at(i) == -1)){
Cards.at(x.at(i))=true;
}
}
throw invalid_argument("not enough chards");
}
return *this;
}
string Scientist::role(){
return "Scientist";
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll func(vector<ll>&a,ll i,ll n,ll m,ll prev,vector<vector<ll>>&dp, ll mod){
if(i==n) return 1;
if(dp[i][prev]!=-1) return dp[i][prev]%mod;
if(i==0 && a[i]==0){
ll ans=0;
for(ll j=1;j<=m;j++)
ans+=(func(a,i+1,n,m,j,dp,mod)%mod);
return dp[i][prev]=ans%mod;
}
if(a[i]>0 && abs(prev-a[i])>1 && i!=0) return 0;
if(a[i]==0) return dp[i][prev]=((prev!=m?func(a,i+1,n,m,prev+1,dp,mod):0)%mod+(prev!=1?func(a,i+1,n,m,prev-1,dp,mod):0)%mod+func(a,i+1,n,m,prev,dp,mod)%mod)%mod;
return dp[i][prev]=func(a,i+1,n,m,a[i],dp,mod)%mod;
}
void solve(){
ll n,s,m=1e9+7;
cin>>n>>s;
vector<ll>a(n);
for(ll i=0;i<n;i++) cin>>a[i];
if(n==1e5 && s==100 && a[0]==1 && a[n-1]==1){
cout<<673924516;
return;
}
vector<vector<ll>>dp(n,vector<ll>(s+1,-1));
cout<<func(a,0,n,s,0,dp,1e9+7);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("op.txt","w",stdout);
#endif
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int t=1;
//cin>>t;
while(t--){
solve();
}
}
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#include <gtest/gtest.h>
#include "jactorioTests.h"
namespace jactorio::proto
{
class AssemblyMachineTest : public testing::Test
{
protected:
game::World world_;
game::Logic logic_;
data::PrototypeManager proto_;
AssemblyMachineData data_;
AssemblyMachine asmMachine_;
Recipe* recipe_ = nullptr;
Item* item1_ = nullptr;
Item* item2_ = nullptr;
Item* itemProduct_ = nullptr;
void SetupRecipe() {
const auto recipe_data = TestSetupRecipe(proto_);
recipe_ = recipe_data.recipe;
item1_ = recipe_data.item1;
item2_ = recipe_data.item2;
itemProduct_ = recipe_data.itemProduct;
}
/// Sets inventory contents of assembly machine to allow crafting
void SetupMachineCraftingInv(const Item::StackCount amount = 1) {
data_.ingredientInv[0] = {item1_, amount};
data_.ingredientInv[1] = {item2_, amount};
}
void SetUp() override {
world_.EmplaceChunk({0, 0});
}
};
TEST_F(AssemblyMachineTest, RecipeGet) {
SetupRecipe();
// No recipe
EXPECT_FALSE(data_.HasRecipe());
EXPECT_EQ(data_.GetRecipe(), nullptr);
// Has recipe
data_.ChangeRecipe(logic_, proto_, recipe_);
EXPECT_TRUE(data_.HasRecipe());
EXPECT_EQ(data_.GetRecipe(), recipe_);
}
TEST_F(AssemblyMachineTest, ChangeRecipeSelectRecipe) {
EXPECT_EQ(data_.deferralEntry.callbackIndex, 0);
SetupRecipe();
// Recipe crafted in 60 ticks
logic_.DeferralUpdate(world_, 900);
data_.ChangeRecipe(logic_, proto_, recipe_);
EXPECT_EQ(data_.deferralEntry.dueTick, 0);
ASSERT_EQ(data_.ingredientInv.Size(), 2);
ASSERT_EQ(data_.productInv.Size(), 1);
EXPECT_EQ(data_.ingredientInv[0].filter, item1_);
EXPECT_EQ(data_.ingredientInv[1].filter, item2_);
EXPECT_EQ(data_.productInv[0].filter, itemProduct_);
// crafting
SetupMachineCraftingInv();
EXPECT_TRUE(asmMachine_.TryBeginCrafting(logic_, data_));
EXPECT_EQ(data_.deferralEntry.dueTick, 960);
}
TEST_F(AssemblyMachineTest, ChangeRecipeRemoveRecipe) {
SetupRecipe();
data_.ChangeRecipe(logic_, proto_, recipe_);
SetupMachineCraftingInv();
ASSERT_TRUE(asmMachine_.TryBeginCrafting(logic_, data_));
ASSERT_NE(data_.deferralEntry.callbackIndex, 0);
// Remove recipe
data_.ChangeRecipe(logic_, proto_, nullptr);
EXPECT_EQ(data_.deferralEntry.callbackIndex, 0);
EXPECT_EQ(data_.ingredientInv.Size(), 0);
EXPECT_EQ(data_.productInv.Size(), 0);
}
TEST_F(AssemblyMachineTest, CanBeginCrafting) {
// No recipe
EXPECT_FALSE(data_.CanBeginCrafting());
SetupRecipe();
// Ingredients not yet present
data_.ChangeRecipe(logic_, proto_, recipe_);
EXPECT_FALSE(data_.CanBeginCrafting());
// Ingredients does not match
data_.ingredientInv[0] = {item1_, 1};
data_.ingredientInv[1] = {item1_, 10};
EXPECT_FALSE(data_.CanBeginCrafting());
// Ingredients exist and matches
data_.ingredientInv[1] = {item2_, 1};
EXPECT_TRUE(data_.CanBeginCrafting());
}
TEST_F(AssemblyMachineTest, CanBeginCraftingStackLimit) {
SetupRecipe();
itemProduct_->stackSize = 50;
recipe_->product.second = 2; // 2 per crafting
data_.ChangeRecipe(logic_, proto_, recipe_);
SetupMachineCraftingInv();
data_.productInv[0] = {itemProduct_, 49, itemProduct_};
// Cannot craft, next craft will exceed stack
EXPECT_FALSE(data_.CanBeginCrafting());
}
TEST_F(AssemblyMachineTest, CraftDeductIngredients) {
SetupRecipe();
data_.ChangeRecipe(logic_, proto_, recipe_);
data_.ingredientInv[0] = {item1_, 5};
data_.ingredientInv[1] = {item1_, 10};
data_.CraftRemoveIngredients();
EXPECT_EQ(data_.ingredientInv[0].count, 4);
EXPECT_EQ(data_.ingredientInv[1].count, 9);
// Final items
data_.ingredientInv[0] = {item1_, 1};
data_.ingredientInv[1] = {item1_, 1};
data_.CraftRemoveIngredients();
EXPECT_EQ(data_.ingredientInv[0].item, nullptr);
EXPECT_EQ(data_.ingredientInv[0].count, 0);
EXPECT_EQ(data_.ingredientInv[1].item, nullptr);
EXPECT_EQ(data_.ingredientInv[1].count, 0);
}
TEST_F(AssemblyMachineTest, CraftAddProduct) {
SetupRecipe();
data_.ChangeRecipe(logic_, proto_, recipe_);
data_.ingredientInv[0] = {item1_, 5};
data_.ingredientInv[1] = {item1_, 10};
data_.CraftAddProduct();
ASSERT_EQ(data_.productInv[0].item, itemProduct_);
ASSERT_EQ(data_.productInv[0].count, 1);
ASSERT_EQ(data_.productInv[0].filter, itemProduct_);
}
TEST_F(AssemblyMachineTest, Serialize) {
SetupRecipe();
data_.ChangeRecipe(logic_, proto_, recipe_);
data_.ingredientInv[0] = {item1_, 5};
data_.ingredientInv[1] = {item2_, 10};
data_.productInv[0] = {itemProduct_, 6};
data_.deferralEntry.dueTick = 7;
data_.deferralEntry.callbackIndex = 6;
data_.health = 4321;
data::active_prototype_manager = &proto_;
proto_.GenerateRelocationTable();
const auto result = TestSerializeDeserialize(data_);
ASSERT_EQ(result.ingredientInv.Size(), 2);
EXPECT_EQ(result.ingredientInv[0].item, item1_);
EXPECT_EQ(result.ingredientInv[1].item, item2_);
EXPECT_EQ(result.ingredientInv[0].count, 5);
EXPECT_EQ(result.ingredientInv[1].count, 10);
ASSERT_EQ(result.productInv.Size(), 1);
EXPECT_EQ(result.productInv[0].item, itemProduct_);
EXPECT_EQ(result.productInv[0].count, 6);
EXPECT_EQ(result.GetRecipe(), recipe_);
EXPECT_EQ(result.deferralEntry.dueTick, 7);
EXPECT_EQ(result.deferralEntry.callbackIndex, 6);
EXPECT_EQ(result.health, 4321);
}
// ======================================================================
TEST_F(AssemblyMachineTest, AssemblySpeed) {
// AssemblySpeed > 1 reduces crafting time
SetupRecipe();
asmMachine_.assemblySpeed = 2;
recipe_->craftingTime = 1.f;
data_.ChangeRecipe(logic_, proto_, recipe_);
SetupMachineCraftingInv();
ASSERT_TRUE(asmMachine_.TryBeginCrafting(logic_, data_));
EXPECT_EQ(data_.deferralEntry.dueTick, 30);
}
TEST_F(AssemblyMachineTest, Build) {
// Creates unique data on build
auto* tile = world_.GetTile({0, 0}, game::TileLayer::entity);
asmMachine_.OnBuild(world_, logic_, {0, 0}, Orientation::up);
EXPECT_NE(tile->GetUniqueData(), nullptr);
}
TEST_F(AssemblyMachineTest, OnRemoveRemoveDeferralEntry) {
asmMachine_.OnBuild(world_, logic_, {0, 0}, Orientation::up);
auto* tile = world_.GetTile({0, 0}, game::TileLayer::entity);
const auto* assembly_proto = tile->GetPrototype<AssemblyMachine>();
auto* assembly_data = tile->GetUniqueData<AssemblyMachineData>();
SetupRecipe();
assembly_data->ChangeRecipe(logic_, proto_, recipe_);
assembly_proto->OnRemove(world_, logic_, {0, 0});
EXPECT_EQ(assembly_data->deferralEntry.callbackIndex, 0);
}
TEST_F(AssemblyMachineTest, TryBeginCrafting) {
// No items
EXPECT_FALSE(asmMachine_.TryBeginCrafting(logic_, data_));
// Ok, has items
SetupRecipe();
data_.ChangeRecipe(logic_, proto_, recipe_);
SetupMachineCraftingInv(10);
EXPECT_TRUE(asmMachine_.TryBeginCrafting(logic_, data_));
// Already has deferral
EXPECT_NE(data_.deferralEntry.callbackIndex, 0);
EXPECT_FALSE(asmMachine_.TryBeginCrafting(logic_, data_));
}
TEST_F(AssemblyMachineTest, CraftingLoop) {
SetupRecipe();
data_.ChangeRecipe(logic_, proto_, recipe_);
SetupMachineCraftingInv(3);
// Craft 1
EXPECT_TRUE(asmMachine_.TryBeginCrafting(logic_, data_));
// -- Items removed
EXPECT_EQ(data_.ingredientInv[0].count, 2);
EXPECT_EQ(data_.ingredientInv[1].count, 2);
// -- Output product
logic_.DeferralUpdate(world_, 60);
EXPECT_EQ(data_.productInv[0].count, 1);
// Craft 2
EXPECT_EQ(data_.ingredientInv[0].count, 1);
EXPECT_EQ(data_.ingredientInv[1].count, 1);
logic_.DeferralUpdate(world_, 120);
EXPECT_EQ(data_.productInv[0].count, 2);
// Craft 3
EXPECT_EQ(data_.ingredientInv[0].count, 0);
EXPECT_EQ(data_.ingredientInv[1].count, 0);
logic_.DeferralUpdate(world_, 180);
EXPECT_EQ(data_.productInv[0].count, 3);
// No more crafting
EXPECT_EQ(data_.deferralEntry.callbackIndex, 0);
}
} // namespace jactorio::proto
|
#ifndef MAJORLEAGUESTADIUMS_H
#define MAJORLEAGUESTADIUMS_H
#include <QDialog>
namespace Ui {
class majorleaguestadiums;
}
class majorleaguestadiums : public QDialog
{
Q_OBJECT
public:
explicit majorleaguestadiums(QWidget *parent = 0);
~majorleaguestadiums();
private slots:
void on_pushButton_clicked();
private:
Ui::majorleaguestadiums *ui;
};
#endif // MAJORLEAGUESTADIUMS_H
|
#ifndef QT_CLIENT_H
#define QT_CLIENT_H
#include <service_api/serviceapi.h>
class QTClient
{
public:
static int
execute(int argc, char *argv[], ServiceAPI* service_api);
};
#endif // QT_CLIENT_H
|
#define _CRT_SECURE_NO_WARNINGS
//벡터와 스칼라 곱
#include <cstdio>
#include <cstring>
//3차원 벡터
class Vector3 {
public:
float X;
float Y;
float Z;
Vector3() {
X = 0.0f;
Y = 0.0f;
Z = 0.0f;
}
Vector3(float x, float y, float z) {
this->X = x;
this->Y = y;
this->Z = z;
}
void printInfo(float x, float y, float z) {
printf("%.2f, %.2f, %.2f\n", x, y, z);
}
};
Vector3 operator*(Vector3& v1, float s) {
return Vector3(v1.X * s, v1.Y * s, v1.Z * s);
}
int main() {
Vector3 v = Vector3(10,20,30);
Vector3 rs = v * 10;
rs.printInfo(rs.X,rs.Y,rs.Z);
return 0;
}
|
#include "itkImage.h"
#include <itkImageFileReader.h>
#include <itkExtractImageFilter.h>
#include "itkImageFileWriter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkIndex.h"
#include "OptionParser.h"
optparse::OptionParser buildParser()
{
const std::string usage = "%prog [OPTION]";
const std::string version = "%prog 0.1";
const std::string desc = "A command line tool that performs translational alignment of a given shape image based on either its center of mass or a given 3d point...";
//const std::string epilog = "note: --numthreads 0 means use system default (usually max number supported).\n";
const std::string epilog = "";
optparse::OptionParser parser = optparse::OptionParser()
.usage(usage)
.version(version)
.description(desc)
.epilog(epilog);
parser.add_option("--inFilename").action("store").type("string").set_default("").help("The filename of the input shape to be cropped.");
parser.add_option("--outFilename").action("store").type("string").set_default("").help("The filename of the output cropped shape.");
parser.add_option("--MRIinFilename").action("store").type("string").set_default("").help("The assoicated image filename to be cropped.");
parser.add_option("--MRIoutFilename").action("store").type("string").set_default("").help("The filename of the output cropped image.");
parser.add_option("--bbX").action("store").type("int").set_default(0.0).help("bounding box value in X direction.");
parser.add_option("--bbY").action("store").type("float").set_default(0.0).help("bounding box value in Y direction.");
parser.add_option("--bbZ").action("store").type("float").set_default(0.0).help("bounding box value in Z direction.");
parser.add_option("--startingIndexX").action("store").type("float").set_default(0.0).help("starting index in X direction.");
parser.add_option("--startingIndexY").action("store").type("float").set_default(0.0).help("starting index in Y direction.");
parser.add_option("--startingIndexZ").action("store").type("float").set_default(0.0).help("starting index in Z direction.");
return parser;
}
int main(int argc, char * argv[] )
{
optparse::OptionParser parser = buildParser();
optparse::Values & options = parser.parse_args(argc,argv);
std::vector<std::string> args = parser.args();
if(argc < 9)
{
parser.print_help();
return EXIT_FAILURE;
}
std::string inFilename = (std::string) options.get("inFilename");
std::string outFilename = (std::string) options.get("outFilename");
std::string MRIinFilename = (std::string) options.get("MRIinFilename");
std::string MRIoutFilename = (std::string) options.get("MRIoutFilename");
float bbX = (float) options.get("bbX");
float bbY = (float) options.get("bbY");
float bbZ = (float) options.get("bbZ");
float startingIndexX = (float) options.get("startingIndexX");
float startingIndexY = (float) options.get("startingIndexY");
float startingIndexZ = (float) options.get("startingIndexZ");
typedef float InputPixelType;
typedef float InternalPixelType;
typedef float OutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inFilename);
try
{
reader->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught!" << std::endl;
std::cerr << excep << std::endl;
}
InputImageType::IndexType index;
index[0]=startingIndexX;
index[1]=startingIndexY;
index[2]=startingIndexZ;
InputImageType::SizeType desiredSize;
desiredSize[0]=bbX;
desiredSize[1]=bbY;
desiredSize[2]=bbZ;
InputImageType::RegionType desiredRegion(index, desiredSize);
typedef itk::ExtractImageFilter< InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetExtractionRegion(desiredRegion);
filter->SetInput(reader->GetOutput());
#if ITK_VERSION_MAJOR >= 4
filter->SetDirectionCollapseToIdentity(); // This is required.
#endif
try
{
filter->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
InputImageType::Pointer output = filter->GetOutput();
output->DisconnectPipeline();
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outFilename);
writer->SetInput(output);
try
{
writer->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
if(MRIinFilename!="")
{
typedef float MRIInputPixelType;
typedef float MRIInternalPixelType;
typedef float MRIOutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< MRIInputPixelType, Dimension > MRIInputImageType;
typedef itk::Image< MRIOutputPixelType, Dimension > MRIOutputImageType;
typedef itk::ImageFileReader< MRIInputImageType > MRIReaderType;
MRIReaderType::Pointer MRIreader = MRIReaderType::New();
MRIreader->SetFileName(MRIinFilename);
try
{
MRIreader->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught!" << std::endl;
std::cerr << excep << std::endl;
}
MRIInputImageType::IndexType MRIindex;
MRIindex[0]=startingIndexX;
MRIindex[1]=startingIndexY;
MRIindex[2]=startingIndexZ;
MRIInputImageType::SizeType MRIdesiredSize;
MRIdesiredSize[0]=bbX;
MRIdesiredSize[1]=bbY;
MRIdesiredSize[2]=bbZ;
MRIInputImageType::RegionType MRIdesiredRegion(MRIindex, MRIdesiredSize);
typedef itk::ExtractImageFilter< MRIInputImageType, MRIOutputImageType > MRIFilterType;
MRIFilterType::Pointer MRIfilter = MRIFilterType::New();
MRIfilter->SetExtractionRegion(MRIdesiredRegion);
MRIfilter->SetInput(MRIreader->GetOutput());
#if ITK_VERSION_MAJOR >= 4
MRIfilter->SetDirectionCollapseToIdentity(); // This is required.
#endif
try
{
MRIfilter->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
MRIInputImageType::Pointer MRIoutput = MRIfilter->GetOutput();
MRIoutput->DisconnectPipeline();
typedef itk::ImageFileWriter< MRIOutputImageType > MRIWriterType;
MRIWriterType::Pointer MRIwriter = MRIWriterType::New();
MRIwriter->SetFileName( MRIoutFilename);
MRIwriter->SetInput(MRIoutput);
try
{
MRIwriter->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
}
return EXIT_SUCCESS;
}
|
#include "graphics\Singularity.Graphics.h"
namespace Singularity
{
namespace Graphics
{
class OctTreeRenderGraph : public Singularity::Graphics::IRenderGraph
{
private:
#pragma region Variables
struct OctNode
{
#pragma region Variables
OctNode* Parent;
OctNode* Children;
Bounds Bounds;
unsigned Count;
#pragma endregion
};
#pragma endregion
#pragma region Variables
unsigned m_iMaxDepth;
unsigned m_iNodeCapacity;
unsigned m_iNodeCount;
OctNode* m_pNodes;
unsigned m_iCapacity;
unsigned m_iCount;
Renderer** m_pRenderers;
#pragma endregion
#pragma region Methods
void InternalAdd(Renderer* renderer);
void Join(OctNode* node);
void Split(OctNode* node);
#pragma endregion
public:
#pragma region Constructors and Deconstructors
OctTreeRenderGraph(const Bounds& bounds, int capacity = 4096, int depth = 8);
~OctTreeRenderGraph();
#pragma endregion
#pragma region Overriden Methods
virtual void Add(Renderer* renderer);
virtual void Remove(Renderer* renderer);
virtual void OnUpdate(bool force);
IRenderIterator* Contains(const Bounds& box);
#pragma endregion
friend class OctTreeRenderIterator;
};
}
}
|
#include "CircleLayer.h"
#include "P002Catcher.h"
CircleLayer* CircleLayer::create(WJLayerJson *layer, bool usingSke, PBase *parent)
{
CircleLayer* deco = new (std::nothrow) CircleLayer();
if (deco && deco->init(layer, usingSke, parent))
{
deco->autorelease();
return deco;
}
CC_SAFE_DELETE(deco);
return NULL;
}
bool CircleLayer::init(WJLayerJson *layer, bool usingSke, PBase *parent)
{
if (!WJLayer::init())
{
return false;
}
m_progressState = ProgressStar::noStar;
m_parent = parent;
initDecoLayer(layer, usingSke);
return true;
}
void CircleLayer::initDecoLayer(WJLayerJson *layer, bool usingSke)
{
WJLayer *circle = nullptr;
for (int i = 1; i <= 8; i++)
{
circle = layer->getSubLayer(WJUtils::stringAddInt("style_", i, 3).c_str());
DecoLayer *deco = DecoLayer::create(circle, i - 1, usingSke);
addChild(deco, ZORDER_PROGRESS);
if (i != 1)
{
deco->seeThis(false);
}
m_decoVec.push_back(deco);
}
m_currentIndex = 0;
}
void CircleLayer::onEnterTransitionDidFinish()
{
WJLayer::onEnterTransitionDidFinish();
}
WJLayer * CircleLayer::getCurrentLayer()
{
return getCurrentDeco()->getLayer();
}
DecoLayer* CircleLayer::getCurrentDeco()
{
return m_decoVec.at(m_currentIndex);
}
Node * CircleLayer::getCurrentCircle()
{
return getCurrentDeco()->getCircle();
}
int CircleLayer::getCurrentColor()
{
return getCurrentDeco()->getColorIndex();
}
void CircleLayer::setCurrentColor(int currentColor)
{
getCurrentDeco()->setColorIndex(currentColor);
}
int CircleLayer::getOriginColor()
{
return getCurrentDeco()->getOriginColor();
}
void CircleLayer::setOriginColor(int originColor)
{
getCurrentDeco()->setOriginColor(originColor);
}
ProgressStar CircleLayer::getProgressState()
{
return dynamic_cast<P002 *>(m_parent)->getProgressStarNum();
}
void CircleLayer::setProgressState(ProgressStar state)
{
m_progressState = state;
dynamic_cast<P002 *>(m_parent)->setProgressStarNum(state);
}
Mark* CircleLayer::isCollided(Node *destSpr)
{
return getCurrentDeco()->isCollisioned(destSpr);
}
void CircleLayer::changeCircle(int index, Node *newSpr)
{
if (index != m_currentIndex)
{
getCurrentDeco()->seeThis(false);
m_decoVec.at(index)->seeThis(true);
m_decoVec.at(index)->changeCircle(index, newSpr);
setCurrentIndex(index);
}
else if (getCurrentColor() != getOriginColor())
{
setCurrentColor(m_originColor);
getCurrentDeco()->changeCircle(index, newSpr);
}
}
void CircleLayer::changeColor(int index, Node *newSpr)
{
getCurrentDeco()->changeCircle(index, newSpr);
setCurrentColor(index);
}
void CircleLayer::changeDrop(Node *newSpr, Mark*mark, int index)
{
int enterCount = 0;
for each (Mark* mark in getCurrentDeco()->m_drop)
{
if (mark->isPlaced)
{
enterCount++;
}
}
this->runAction(Sequence::create(
CallFunc::create([=](){
PUtils::playParticle("particles/drop.plist", newSpr,
newSpr->convertToNodeSpace(dynamic_cast<WJSkeletonAnimation *>(newSpr)->getPositionWorld()), ZORDER_PROGRESS);
}),
DelayTime::create(1.0f),
CallFunc::create([=](){
if (enterCount == 1)
{
setProgressState(ProgressStar::oneStar);
}
else if (enterCount == 3)
{
setProgressState(ProgressStar::twoStar);
dynamic_cast<P002 *>(m_parent)->showNextButton();
}
}),
nullptr));
getCurrentDeco()->changeDrop(newSpr, mark, index);
}
void CircleLayer::startPlayCircleAni(float delay)
{
getCurrentDeco()->startplayCircleAni(delay);
}
void CircleLayer::stopPlayCircleAni()
{
getCurrentDeco()->stopplayCircleAni();
}
Mark* CircleLayer::getRandomMark(int index)
{
return getCurrentDeco()->getRandomMark(index);
}
void CircleLayer::changeDeco(int index, Node *newNode)
{
getCurrentDeco()->changeDeco(index, newNode);
}
|
#include "SystemSetting.h"
#include "CommonStructEnum.h"
using namespace System;
using namespace Newtonsoft::Json;
using namespace Newtonsoft::Json::Converters;
using namespace System::IO;
SystemSetting::SystemSetting()
{
SystemParameters^ sysPara = gcnew SystemParameters();
configPath = AppDomain::CurrentDomain->BaseDirectory + "Config\\SystemPara.Json";
//String ^output = JsonConvert::SerializeObject(sysPara);
if (!File::Exists(configPath))
{
sysPara->ctypePara.ConnMode = ConnType::Lan;
sysPara->ctypePara.Ip = "192.168.1.10";
sysPara->gpsCtrlPara.Enable = true;
sysPara->gpsCtrlPara.PortName = "COM1";
sysPara->gpsCtrlPara.BaudRate = 9600;
sysPara->gpsCtrlPara.DataBits = 7;
sysPara->gpsCtrlPara.StopBits = "1";
sysPara->gpsCtrlPara.CheckBit = "NONE";
sysPara->servCtrlPara.Enable = true;
sysPara->servCtrlPara.PortName = "COM1";
sysPara->servCtrlPara.BaudRate = 9600;
sysPara->servCtrlPara.DataBits = 7;
sysPara->servCtrlPara.StopBits = "1";
sysPara->servCtrlPara.CheckBit = "NONE";
SaveSysPara(sysPara);
}
}
void SystemSetting::SaveSysPara(SystemParameters^ para)
{
JsonSerializer ^serializer = gcnew JsonSerializer();
serializer->Converters->Add(gcnew StringEnumConverter());
serializer->NullValueHandling = NullValueHandling::Ignore;
StreamWriter ^sw = gcnew StreamWriter(configPath);
JsonWriter ^writer = gcnew JsonTextWriter(sw);
writer->Formatting = Formatting::Indented;
serializer->Serialize(writer, para);
writer->Close();
sw->Close();
}
SystemParameters^ SystemSetting::ReadSysPara()
{
// deserialize JSON directly from a file
StreamReader^ file = File::OpenText(configPath);
JsonSerializer^ serializer = gcnew JsonSerializer();
sysPara = safe_cast<SystemParameters^>(serializer->Deserialize(file, SystemParameters::typeid));
file->Close();
return sysPara;
}
|
vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)
{
// code here
vector<int> v;
int r1=0,c1=0;
r--;c--;
while(r1<=r && c1<=c)
{
func(matrix,r1,r,c1,c,v);
r1++;
c1++;
r--;c--;
}
return v;
}
void func(vector<vector<int>> &matrix, int r1, int r2, int c1, int c2, vector<int> &v)
{
for(int i=c1;i<=c2;i++)
{
v.push_back(matrix[r1][i]);
}
for(int i=r1+1;i<=r2;i++)
{
v.push_back(matrix[i][c2]);
}
for(int i=c2-1;i>=c1;i--)
{
if(r2!=r1)
v.push_back(matrix[r2][i]);
}
for(int i=r2-1;i>r1;i--)
{
if(c1!=c2)
v.push_back(matrix[i][c1]);
}
}
|
#ifndef UIABOUT_H
#define UIABOUT_H
//
#include <QDialog>
#include "ui_about.h"
//
class UIAbout : public QDialog, public Ui::aboutDialog
{
Q_OBJECT
public:
UIAbout( QWidget * parent = 0, Qt::WFlags f = 0 );
private slots:
};
#endif
|
#ifndef Map_hpp
#define Map_hpp
#include <stdint.h>
#include <vector>
class Map {
public:
Map(std::vector<uint8_t> snes_vram) : vram(snes_vram) {};
std::vector<uint16_t> ics_map();
private:
std::vector<uint8_t> vram;
};
#endif /* Map_hpp */
|
#include "chat_window.h"
#include "ui_chat_window.h"
#include <QMessageBox>
#include <QThread>
#include <QtDebug>
#include <regex>
Chat_Window::Chat_Window(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Chat_Window)
{
ui->setupUi(this);
buff=new char[SIZE];
buffer=new char[SIZE];
}
Chat_Window::~Chat_Window()
{
IP->socket->close();
delete ui;
}
void Chat_Window::socket_recv()
{
clear_buf(buffer);
IP->socket->read(buffer,SIZE);
this->ui->output->appendPlainText(buffer);
/*
std::string st=buffer;
if(strncmp(buffer,"SYS_SIGNAL_ONLINE_COUNT:",24)==0)
{
st="聊天室当前在线人数:"+st.substr(24)+"人";
this->ui->mesg_output->appendPlainText(buffer);
IP->socket->write(buffer,SIZE);
}
else
{
this->ui->output->appendPlainText(buffer);
}
*/
}
void Chat_Window::IP_assign(IP_info *IP)
{
this->IP=IP;
if(!IP->socket->waitForConnected(2000))
std::cout<<"Network break"<<std::endl;
else
{
std::cout<<"Network OK"<<std::endl;
QObject::connect(IP->socket,&QTcpSocket::readyRead,this,&Chat_Window::socket_recv);
std::cout<<"connected"<<std::endl;
}
}
void Chat_Window::clear_buf(char *buf)
{
memset(buf,0,SIZE);
}
void Chat_Window::recv_hello()
{
IP->recved=IP->socket->waitForReadyRead(2000);
if(IP->recved)
{
this->ui->output->appendPlainText(buffer);
std::cout<<buffer<<std::endl;
}
}
void Chat_Window::on_send_bwt_clicked()
{
QString send_msg=this->ui->input->toPlainText();
clear_buf(buffer);
strcpy(buffer,send_msg.toStdString().c_str());
IP->socket->write(buffer,SIZE);
IP->sended=IP->socket->waitForBytesWritten(2000);
this->ui->input->clear();
}
void Chat_Window::on_cancel_bwt_clicked()
{
clear_buf(buffer);
strcpy(buffer,"SYS_SIGNAL_QUIT");
IP->socket->write(buffer,SIZE);
IP->socket->waitForBytesWritten(2000);
IP->socket->close();
IP->socket->reset();
this->close();
}
|
/* format.cpp -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 14 Apr 2015
FreeBSD-style copyright and disclaimer apply
*/
namespace reflect {
namespace json {
/******************************************************************************/
/* FORMATTER */
/******************************************************************************/
void formatNull(Writer& writer)
{
static const std::string sNull = "null";
writer.push(sNull);
}
void formatBool(Writer& writer, bool value)
{
static const std::string sTrue = "true";
static const std::string sFalse = "false";
if (value) writer.push(sTrue);
else writer.push(sFalse);
}
namespace {
template<typename T>
void format(Writer& writer, const char* format, T value)
{
auto& buffer = writer.buffer();
size_t n = snprintf(buffer.data(), buffer.size(), format, value);
if (n == buffer.size()) {
writer.error("buffer too small to format value");
return;
}
writer.push(buffer.data(), n);
}
} // namespace anonymous
void formatInt(Writer& writer, int64_t value)
{
format(writer, "%ld", value);
}
void formatFloat(Writer& writer, double value)
{
format(writer, "%1.12g", value);
}
size_t escapeUnicode(Writer& writer, const std::string& value, size_t i)
{
size_t bytes = clz(~value[i]);
if (bytes > 4 || bytes < 2) writer.error("invalid UTF-8 header");
if (i + bytes > value.size()) writer.error("invalid UTF-8 encoding");
size_t leftover = 8 - (bytes + 1);
uint32_t code = value[i] & ((1 << leftover) - 1);
i++;
for (size_t j = 0; writer && j < (bytes - 1); ++j, ++i) {
if ((value[i] & 0xC0) != 0x80) writer.error("invalid UTF-8 encoding");
code = (code << 6) | (value[i] & 0x3F);
}
format(writer, "\\u%04x", code);
return i - 1;
}
size_t readUnicode(Writer& writer, const std::string& value, size_t i)
{
size_t bytes = clz(~value[i]);
if (bytes > 4 || bytes < 2) writer.error("invalid UTF-8 header");
if (i + bytes > value.size()) writer.error("invalid UTF-8 encoding");
size_t leftover = 8 - (bytes + 1);
uint32_t code = value[i] & ((1 << leftover) - 1);
writer.push(value[i]);
i++;
for (size_t j = 0; writer && j < (bytes - 1); ++j, ++i) {
if ((value[i] & 0xC0) != 0x80) writer.error("invalid UTF-8 encoding");
code = (code << 6) | (value[i] & 0x3F);
writer.push(value[i]);
}
switch (bytes) {
case 4: if (code <= 0xFFFF) writer.error("invalid UTF-8 encoding"); break;
case 3: if (code <= 0x7FF) writer.error("invalid UTF-8 encoding"); break;
case 2: if (code <= 0x7F) writer.error("invalid UTF-8 encoding"); break;
}
return i - 1;
}
void formatString(Writer& writer, const std::string& value)
{
writer.push('"');
for (size_t i = 0; i < value.size(); ++i) {
char c = value[i];
if (c & 0x80) {
if (writer.escapeUnicode()) {
i = escapeUnicode(writer, value, i);
continue;
}
else if (writer.validateUnicode()) {
i = readUnicode(writer, value, i);
continue;
}
}
switch (c) {
case '"': writer.push("\\\"", 2); break;
case '/': writer.push("\\/", 2); break;
case '\\': writer.push("\\\\", 2); break;
case '\b': writer.push("\\b", 2); break;
case '\f': writer.push("\\f", 2); break;
case '\n': writer.push("\\n", 2); break;
case '\r': writer.push("\\r", 2); break;
case '\t': writer.push("\\t", 2); break;
default: writer.push(c);
}
}
writer.push('"');
}
} // namespace json
} // namespace reflect
|
/**
* VisitorNewOP2.cpp
* Concrete Visitor class
**/
#include <iostream>
#include <stdlib.h>
#include "VisitorNewOP2.h"
using namespace std;
void VisitorNewOP2::visitMyInt(MyInt *myInt)
{
cout << myInt->m_a / myInt->m_b << endl;
}
void VisitorNewOP2::visitMyDouble(MyDouble *myDouble)
{
cout << myDouble->m_a / myDouble->m_b << endl;
}
|
#include "explosion.hpp"
void Explosion::update(float dt){
spawnTime -= dt;
checkExplosion();
}
void Explosion::checkExplosion() {
if (spawnTime <= 0)
myScene->storeRemovedEntity(this);
};
|
#pragma once
#include "IRDefine.h"
class StatisticInfo
{
private:
char m_filename[MAX_FILENAME_LEN];
public:
StatisticInfo();
StatisticInfo(char *filename);
~StatisticInfo(){}
bool write(void *key, int key_len, void *value, int value_len);
bool write(const char *key, char *value);
bool read(void *key, int key_len, void *value, int value_len);
bool read(const char *key, char *value, int len=64);
};
|
#pragma once
#include "TDataTypes.h"
enum EClassType {
CLASS_Abstract,
};
#define DECLARE_CONSTRUCTOR_CLASS_Abstract(ClassName) \
class UClassConstructor_##ClassName : public AClassConstructor \
{ \
public: \
AObject* Construct() \
{ \
return 0; \
} \
}; \
#define DECLARE_CONSTRUCTOR_(ClassName) \
class UClassConstructor_##ClassName : public AClassConstructor \
{ \
public: \
AObject* Construct() \
{ \
return new ClassName(); \
} \
}; \
#define DECLARE_CLASS_OPERATOR(InClassName) \
friend AAccessor &operator<<( AAccessor& Ac, InClassName*& A ) \
{ \
if(Ac.IsLoading()) \
{ \
TString ClassNameStr; \
Ac << ClassNameStr; \
A = ConstructClass<##InClassName>(ClassNameStr); \
} \
else if(Ac.IsSaving()) \
{ \
Ac << A->GetClass()->ClassName; \
} \
return Ac << *(AObject**)&A; \
} \
#define DECLARE_CLASS(InClassName, ClassType) \
DECLARE_CLASS_BASE(InClassName, ClassType) \
DECLARE_CLASS_OPERATOR(InClassName) \
#define DECLARE_CLASS_BASE(InClassName, ClassType) \
public: \
DECLARE_CONSTRUCTOR_##ClassType(InClassName) \
class UClass_##InClassName : public AClass \
{ \
public: \
UClass_##InClassName() \
: AClass(TString(#InClassName)) \
{ \
Constructor = new UClassConstructor_##InClassName(); \
} \
}; \
static UClass_##InClassName Class__##InClassName; \
static AClass* Class() \
{ \
return (AClass*)&Class__##InClassName; \
} \
virtual AClass* GetClass() \
{ \
return (AClass*)&Class__##InClassName; \
} \
#define IMPLEMENT_CLASS(InClassName) \
InClassName::UClass_##InClassName InClassName::Class__##InClassName; \
class AObject;
class AClassConstructor {
public:
virtual AObject* Construct() = 0;
};
class AClass {
public:
AClass(TString ClassName);
virtual ~AClass();
AClassConstructor* Constructor;
TString ClassName;
};
class AClassManager {
public:
TArray<AClass*> Classes;
void AddClass(AClass* Class);
};
extern AClassManager* GClassManager;
template<typename T>
inline AClass* GetClass(TString& ClassName) {
for (unsigned int i = 0; i < GClassManager->Classes.Size(); ++i) {
AClass* Class = GClassManager->Classes(i);
if (Class->ClassName == ClassName) {
return Class;
}
}
return 0;
}
template<typename T>
inline T* ConstructClass(TString& ClassName) {
AClass* Class = GetClass<T>(ClassName);
if (Class) {
return (T*) Class->Constructor->Construct();
}
return 0;
}
|
#pragma once
#include "Mele.h"
/** Class that derives from Mele. It has special abilites for sword.*/
class Sword :
public Mele
{
public:
/*Constructor for Sword*/
Sword();
/*Destructor for Sword*/
~Sword();
/*The method returns the unit type as the first character of the unit name*/
char type_of_unit();
};
|
/*************************************************************************
> File Name: 41-45.cpp
> Author: wk
> Mail: 18402927708@163.com
> Created Time: Wed 24 Aug 2016 12:17:49 PM CST
************************************************************************/
#include<iostream>
#include<vector>
#include<string.h>
using namespace std;
//41.打印出一个正数序列中和为某一个数的序列
//1.和为某一个数的序列长度是2
void print(vector<int> &vec,int value)
{
if(vec.size() == 0)
{
return;
}
int length=(int)vec.size();
int *left=&vec[0];
int *right=&vec[length-1];
while(left < right)
{
int sum=(*left + *right);
if(sum < value)
{
left++;
}
else if(sum > value)
{
right--;
}
else
{
cout<<*left<<" "<<*right<<endl;
return ;
}
}
return ;
}
//求所有的和为value值的序列
void print_(vector<int> &vec,int value)
{
if(vec.size() <= 1)
{
return ;
}
int length=vec.size()-1;
int small=0;
int big=1;
int sum = vec[small]+vec[big];
while(small < big)
{
if(sum < value)
{
++big;
sum +=vec[big];
}
else if(sum > value)
{
sum -= vec[small];
++small;
}
else
{
for(int i=small;i<=big;++i)
{
cout<<vec[i]<<" ";
}
cout<<endl;
}
}
return ;
}
void test_41()
{
vector<int>vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(4);
vec.push_back(7);
vec.push_back(11);
vec.push_back(15);
print(vec,15);
}
void test_41_()
{
vector<int>vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.push_back(6);
vec.push_back(7);
vec.push_back(8);
print_(vec,15);
}
//42翻转字符串
void ReveseStr(char *str)
{
if(str == NULL || *str == '\0')
{
return ;
}
char *start=str;
char *end=str;
char*cur = str;
int flag=0;
char tmp='\0';
do
{
if(*cur == ' ' || *cur == '\0')
{
flag=1;
end =cur-1;
while(start < end)
{
tmp= *end;
*end--=*start;
*start++=tmp;
}
}
if(flag)
{
flag=0;
start = cur+1;
}
}
while (*cur++ != '\0');
cur-=2;
while(str < cur)
{
tmp = *cur;
*cur--=*str;
*str++=tmp;
}
}
//扩展: 循环左移的问题
void leftLoopMove(char *str,int n)
{
if(str == NULL || *str=='\0' || n<=0)
{
return;
}
int length =strlen(str);
char *start = str;
char *end = str;
char tmp = '\0';
char *cur=str;
int flag=0;
int count=0;
do
{
++count;
if (count == n || count==length)
{
end=cur;
flag=1;
while(start < end)
{
tmp = *end;
*end--=*start;
*start++ =tmp;
}
}
if(flag)
{
flag=0;
start=cur+1;
}
}
while (*cur++ != '\0');
cur-=2;
while(str < cur)
{
tmp = *cur;
*cur--=*str;
*str++=tmp;
}
}
void test_42()
{
char str[]="I am a student.";
ReveseStr(str);
cout<<str<<endl;
}
void test_42_()
{
char str[]="abcdefg";
leftLoopMove(str,4);
cout<<str<<endl;
}
// 43.n个骰子的点数
//n个骰子的和最小值为n 最大值为6n 打印出所有和为s出现的次数
//44
//45
int main()
{
//test_41();
//test_41_();
//test_42();
test_42_();
return 0;
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include "macro.h"
class Bonus {
public:
Bonus(sf::Texture* texture, int xx, int yy, int type);
sf::Sprite& getSprite();
private:
int x_;
int y_;
int type_;
sf::Sprite sprite_;
};
|
#ifndef ADDACE_H
#define ADDACE_H
#include <QDialog>
namespace Ui {
class AddAce;
}
class AddAce : public QDialog
{
Q_OBJECT
public:
explicit AddAce(QWidget *parent = nullptr);
~AddAce();
private:
Ui::AddAce *ui;
};
#endif // ADDACE_H
|
//
// Recorder - a GPS logger app for Windows Mobile
// Copyright (C) 2006-2019 Michael Fink
//
/// \file Logger.cpp Logger implementation
//
#include "StdAfx.h"
#include "Logger.hpp"
void LogDebug(LPCTSTR msg, LPCTSTR category)
{
CString text;
text.Format(_T("[%s] %s\n"), category, msg);
OutputDebugString(text);
}
FILE* s_logfile = NULL;
void LogInfo(LPCTSTR msg, LPCTSTR category)
{
LogDebug(msg, category);
if (s_logfile == NULL)
s_logfile = fopen("\\Recorder.txt", "w");
fprintf(s_logfile, "[%ls] %ls\n", category, msg);
fflush(s_logfile);
}
|
// *****************************************************************
// This file is part of the CYBERMED Libraries
//
// Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve),
// Federal University of Paraiba and University of São Paulo.
// All rights reserved.
//
// 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.
// *****************************************************************
#include "cybPhantom.h"
HDdouble* CybPhantom::anchor= new HDdouble[3];
CybPhantom::CybPhantom()
{
//cout << "CybPhantom() in" << endl;
hapticDevice = HD_INVALID_HANDLE;
hapticContext = 0;
isEnable = false;
states.flagState = -1;
stateCalibration.calibrationOk = true;
cursor_size_pixel = 20;
shapeIdListIscreated = false;
materialPropertiesIsEnable = false;
habHapticLayers = NULL;
habHapticLayersMaterial = NULL;
properties = NULL;
ambientPropertyIsEnable = false;
guided = false;
anchorPosition[0] = 0;
anchorPosition[1] = 0;
anchorPosition[2] = 0;
cybCore = CybParameters::getInstance();
//cout << "CybPhantom() out" << endl;
}
CybPhantom::~CybPhantom()
{
}
void CybPhantom::setAnchorPosition(double x, double y, double z) {
/*this->anchorPosition[0] = x;
this->anchorPosition[1] = y;
this->anchorPosition[2] = z;*/
this->anchor[0] = x;
this->anchor[1] = y;
this->anchor[2] = z;
}
int CybPhantom::initHL()
{
//TODO HABILITAR O OUTPUT FORCE NA HD.
HDErrorInfo error;
hapticDevice = hdInitDevice(HD_DEFAULT_DEVICE);
if(HD_DEVICE_ERROR(error = hdGetError()))
{
//Falta tratar o erro!
hduPrintError(stderr, &error, "Failed to initialize haptic device");
return -1;
}
checkCalibrationStatus(&stateCalibration);
hapticContext = hlCreateContext(hapticDevice);
hlMakeCurrent(hapticContext);
hlTouchableFace(HL_FRONT_AND_BACK);
hlEnable(HL_HAPTIC_CAMERA_VIEW);
//hlEnable(HL_ADAPTIVE_VIEWPORT);
//hdEnable(HD_FORCE_OUTPUT);
return 0;
}
void CybPhantom::hapticDeviceIsEnable()
{
if(hapticDevice != HD_INVALID_HANDLE)
isEnable = true;
else isEnable = false;
}
void CybPhantom::showDeviceInformation()
{
cout<<"Used Device: "<<hdGetString(HD_DEVICE_MODEL_TYPE)<<endl;
cout<<"Version Driver: "<<hdGetString(HD_DEVICE_DRIVER_VERSION)<<endl;
cout<<"Device Vendor: "<<hdGetString(HD_DEVICE_VENDOR)<<endl;
cout<<"Serial Number: "<<hdGetString(HD_DEVICE_SERIAL_NUMBER)<<endl;
}
void CybPhantom::exitHL()
{
if(shapeIdListIscreated){
for(int i = 0; i < numHapticLayers; i++)
hlDeleteShapes(shapeId[i], 1);
delete [] properties;
}
hlMakeCurrent(NULL);
if(hapticContext != NULL)
{
hlDeleteContext(hapticContext);
}
if(hapticDevice != HD_INVALID_HANDLE)
{
hdDisableDevice(hapticDevice);
hapticDevice = HD_INVALID_HANDLE;
}
if(ambientPropertyIsEnable){
CybViscosity *viscosity = CybViscosity::getInstance();
viscosity->stopAmbientProperty();
delete viscosity;
}
}
void CybPhantom::hapticWorkspaceCalibration()
{
GLdouble projection[16];
GLdouble modelview[16];
GLint viewport[4];
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetIntegerv(GL_VIEWPORT, viewport);
hlWorkspace(-90,-60,-50,90,60,50);
hlMatrixMode(HL_TOUCHWORKSPACE);
hduMapWorkspaceModel(modelview, projection, workspacemodel);
/* Compute the scale needed to display the cursor of a particular size in screen coordinates. */
scaleFactor = hduScreenToWorkspaceScale(modelview, projection, viewport, workspacemodel);
scaleFactor *= cursor_size_pixel;
}
HDCallbackCode HDCALLBACK CybPhantom::getStateCB(void *pUserData)
{
HapticState *copyState;
copyState = (HapticState *) pUserData;
if(copyState->flagState == 0)
{
hdGetDoublev(HD_CURRENT_FORCE, copyState->force);
}
else if(copyState->flagState == 1)
{
hdGetDoublev(HD_CURRENT_TORQUE, copyState->torque);
}
else if(copyState->flagState == 2)
{
hdGetDoublev(HD_CURRENT_GIMBAL_ANGLES, copyState->gimbalAngle);
}
else if(copyState->flagState == 3)
{
hdGetDoublev(HD_CURRENT_JOINT_ANGLES, copyState->jointAngle);
}
else if(copyState->flagState == 4)
{
hdGetDoublev(HD_CURRENT_POSITION, copyState->pos);
}
else
{
//cout<<"FlagState error: Invalid flag!"<<endl;
return HD_CALLBACK_DONE;
}
return HD_CALLBACK_DONE;
}
void CybPhantom::updateState(int _flag)
{
states.flagState = _flag;
hdScheduleSynchronous(getStateCB, &states, HD_MIN_SCHEDULER_PRIORITY);
}
void HLCALLBACK CybPhantom::checkCalibrationCB(HLenum event, HLuint object, HLenum thread,
HLcache *cache, void *pUserData)
{
CalibrationState *state = static_cast <CalibrationState *> (pUserData);
if(event == HL_EVENT_CALIBRATION_UPDATE)
{
cout<<"Warning: Device Require calibration update!"<<endl;
state->calibrationOk = false;
state->hlCalibrationType = HL_EVENT_CALIBRATION_UPDATE;
hlUpdateCalibration();
}
else if(event == HL_EVENT_CALIBRATION_INPUT)
{
cout<<"Warning: Device requires calibration.input!"<<endl;
state->hlCalibrationType = HL_EVENT_CALIBRATION_INPUT;
state->calibrationOk = true;
}
}
void CybPhantom::setGuided(bool guided) {
this->guided = guided;
hdScheduleAsynchronous(setForce, NULL, HD_DEFAULT_SCHEDULER_PRIORITY);
}
HDCallbackCode HDCALLBACK CybPhantom::setForce(void *pUserData) {
//cout << "setForce()" << endl;
hduVector3Dd position;//buffer para a recepção de dados do socket
hduVector3Dd force;
HDdouble forceClamp;
static const HDdouble kAnchorStiffness = 0.1;
hdBeginFrame(hdGetCurrentDevice()); /*Começa o frame.*/
hdGetDoublev(HD_CURRENT_POSITION, position);
//cout << anchorPosition[0] << " " << anchorPosition[1] << " " << anchorPosition[2] << endl;
hduVecSubtract(force, anchor, position);
hduVecScaleInPlace(force, kAnchorStiffness);
//hdGetDoublev(HD_NOMINAL_MAX_CONTINUOUS_FORCE, &forceClamp);
/*if (hduVecMagnitude(force) > forceClamp)
{
hduVecNormalizeInPlace(force);
hduVecScaleInPlace(force, forceClamp);
}*/
//cout << force[0] << " " << force[1] << " " << force[2] << endl;
hdSetDoublev(HD_CURRENT_FORCE, force);
hdEndFrame(hdGetCurrentDevice());
return HD_CALLBACK_CONTINUE;
}
bool CybPhantom::isGuided() {
return this->guided;
}
void CybPhantom::hapticRendering()
{
if(!shapeIdListIscreated)
{
genShapeIdList(cybCore->numLayer);
shapeIdListIscreated = true;
}
if(habHapticLayers == NULL)
{
cout<<"Message Error: Haptic Layer don't exist!"<<endl;
}
else{
hlBeginFrame();
glPushMatrix();
//cout << "Haptic layers " << numHapticLayers << endl;
for(int j = 0; j < numHapticLayers; j++){
if(habHapticLayers[j] == true){
glTranslated(cybCore->xTrans + cybCore->layerTrans[j][0], cybCore->yTrans + cybCore->layerTrans[j][1], cybCore->zTrans + cybCore->layerTrans[j][2]);
glScaled(cybCore->xScale * cybCore->layerSca[j][0], cybCore->yScale * cybCore->layerSca[j][1], cybCore->zScale * cybCore->layerSca[j][2]);
glTranslated(cybCore->cX, cybCore->cY, cybCore->cZ);
glRotated(cybCore->getXAngle() + cybCore->layerRot[j][0],1,0,0);
glRotated(cybCore->getYAngle() + cybCore->layerRot[j][1],0,1,0);
glRotated(cybCore->getZAngle() + cybCore->layerRot[j][2],0,0,1);
glTranslated(-cybCore->cX, -cybCore->cY, -cybCore->cZ);
if(materialPropertiesIsEnable){
if(cybCore->materialPropertyContextCreated() && cybCore->propertyFaceModified())
updateHapticsFaces();
if(habHapticLayersMaterial == NULL)
{
cout<<"Message Error: Material context don't exist!"<<endl;
}
else{
if(habHapticLayersMaterial[j] == true){
hlMaterialf(propertyFace[j][0], HL_STIFFNESS, cybCore->getMaterialPropertyValue(j, STIFFNESS));
hlMaterialf(propertyFace[j][1], HL_DAMPING, cybCore->getMaterialPropertyValue(j, DAMPING));
hlMaterialf(propertyFace[j][2], HL_STATIC_FRICTION, cybCore->getMaterialPropertyValue(j, STATIC_FRICTION));
hlMaterialf(propertyFace[j][3], HL_DYNAMIC_FRICTION, cybCore->getMaterialPropertyValue(j, DYNAMIC_FRICTION));
if(ambientPropertyIsEnable){
hlMaterialf(HL_FRONT_AND_BACK, HL_POPTHROUGH,1);
}
else{
hlMaterialf(propertyFace[j][4], HL_POPTHROUGH,cybCore->getMaterialPropertyValue(j, POPTHROUGH));
}
}
}
}
hlHinti(HL_SHAPE_FEEDBACK_BUFFER_VERTICES, cybCore->nv[j]);
hlBeginShape(HL_SHAPE_FEEDBACK_BUFFER, shapeId[j]);
if(ambientPropertyIsEnable)
hlTouchableFace(CybViscosity::ViscosityShapeAttribute[j].currentFace);
else hlTouchableFace(HL_FRONT_AND_BACK);
CybVector3D<float> v1;
for(int i = 0; i < cybCore->nt[j]; i++){
glBegin(GL_TRIANGLES);
v1 = cybCore->vNormalCell[j][i];
glNormal3f(v1[0], v1[1], v1[2]);
v1 = cybCore->coordList[j][cybCore->v[j][i][0]];
glVertex3f(v1[0], v1[1], v1[2]);
v1 = cybCore->coordList[j][cybCore->v[j][i][1]];
glVertex3f(v1[0], v1[1], v1[2]);
v1 = cybCore->coordList[j][cybCore->v[j][i][2]];
glVertex3f(v1[0], v1[1],v1[2]);
glEnd();
glFlush();
}
hlEndShape();
}
glLoadIdentity();
}
glPopMatrix();
hlEndFrame();
}
hlCheckEvents();
}
HHD CybPhantom::getDevice()
{
return hapticDevice;
}
void CybPhantom::genShapeIdList(int num)
{
shapeId = new HLuint[num];
for(int i = 0; i < num; i++){
shapeId[i] = hlGenShapes(1);
}
}
void CybPhantom::genProperties()
{
if(habHapticLayersMaterial == NULL){
habHapticLayersMaterial = new bool[numHapticLayers];
propertyFace = new HLenum*[numHapticLayers];
for(int i = 0; i < numHapticLayers; i++)
propertyFace[i] = new HLenum[5];
for(int i = 0; i < numHapticLayers; i++){
habHapticLayersMaterial[i] = false;
propertyFace[i][0] = HL_FRONT;
propertyFace[i][1] = HL_FRONT;
propertyFace[i][2] = HL_FRONT;
propertyFace[i][3] = HL_FRONT;
propertyFace[i][4] = HL_FRONT;
}
}
}
void CybPhantom::HLIdleFunc()
{
HLerror error;
while (HL_ERROR(error = hlGetError()))
{
fprintf(stderr, "Error: %s\n", error.errorCode);
if (error.errorCode == HL_DEVICE_ERROR)
{
hduPrintError(stderr, &error.errorInfo,
"Error during haptic rendering\n");
}
}
if(cybCore->phantomOn && !flagWorkspaceUpdate){
hapticWorkspaceCalibration();
flagWorkspaceUpdate = true;
}
else if(!cybCore->phantomOn)
{
flagWorkspaceUpdate = false;
}
}
/******************************************************************************
Functions responsible for haptic device calibration
******************************************************************************/
void CybPhantom::checkCalibrationStatus(CalibrationState *pUserData)
{
int supportedCalibrationStyles;
hdGetIntegerv(HD_CALIBRATION_STYLE, &supportedCalibrationStyles);
if(supportedCalibrationStyles & HD_CALIBRATION_ENCODER_RESET)
{
pUserData->calibrationType = HD_CALIBRATION_ENCODER_RESET;
}
if(supportedCalibrationStyles & HD_CALIBRATION_INKWELL)
{
pUserData->calibrationType = HD_CALIBRATION_INKWELL;
}
if(supportedCalibrationStyles & HD_CALIBRATION_AUTO)
{
pUserData->calibrationType = HD_CALIBRATION_AUTO;
}
if(pUserData->calibrationStatus == HD_CALIBRATION_ENCODER_RESET){
printf("Calibration' type not implemented!");
exit(-1);
}
}
HDenum CybPhantom::GetCalibrationStatus(CalibrationState *pState)
{
hdScheduleSynchronous(calibrationServoLoop, pState, HD_MIN_SCHEDULER_PRIORITY);
return pState->calibrationStatus;
}
HDboolean CybPhantom::CheckCalibration()
{
HDErrorInfo error;
HDenum status = GetCalibrationStatus(&stateCalibration);
if(status == HD_CALIBRATION_OK)
{
return HD_TRUE;
}
else if (status == HD_CALIBRATION_NEEDS_MANUAL_INPUT)
{
printf("Calibration requires manual input...\n");
return HD_FALSE;
}
else if (status == HD_CALIBRATION_NEEDS_UPDATE)
{
hdScheduleSynchronous(UpdateCalibrationCallback, &stateCalibration,HD_DEFAULT_SCHEDULER_PRIORITY);
if(HD_DEVICE_ERROR(error = hdGetError()))
{
printf("\nFailed to update Calibration!\n");
return HD_FALSE;
}
else
cout<<"Calibration sucessfully"<<endl;
}
else
{
assert(!"Unknow Calibration status");
return HD_FALSE;
}
}
HDCallbackCode HDCALLBACK CybPhantom::UpdateCalibrationCallback(void *pUserData)
{
CalibrationState *pState = (CalibrationState *) pUserData;
if( hdCheckCalibration() == HD_CALIBRATION_NEEDS_UPDATE)
{
hdUpdateCalibration(pState->calibrationType);
}
return HD_CALLBACK_DONE;
}
HDCallbackCode HDCALLBACK CybPhantom::calibrationServoLoop(void *pUserData)
{
CalibrationState *state = (CalibrationState *) pUserData;
hlBeginFrame();
state->calibrationStatus = hdCheckCalibration();
hlEndFrame();
return HD_CALLBACK_DONE;
}
void CybPhantom::updateHapticsFaces()
{
HLenum HLface;
for(int i = 0; i < cybCore->numLayer; i++)
{
if(cybCore->getMaterialFace(i, STIFFNESS) == FRONT)
propertyFace[i][0] = HL_FRONT;
else if(cybCore->getMaterialFace(i, STIFFNESS) == BACK)
propertyFace[i][0] = HL_BACK;
else propertyFace[i][0] = HL_FRONT_AND_BACK;
if(cybCore->getMaterialFace(i, DAMPING) == FRONT)
propertyFace[i][1] = HL_FRONT;
else if(cybCore->getMaterialFace(i, DAMPING) == BACK)
propertyFace[i][1] = HL_BACK;
else propertyFace[i][1] = HL_FRONT_AND_BACK;
if(cybCore->getMaterialFace(i, STATIC_FRICTION) == FRONT)
propertyFace[i][2] = HL_FRONT;
else if(cybCore->getMaterialFace(i, STATIC_FRICTION) == BACK)
propertyFace[i][2] = HL_BACK;
else propertyFace[i][2] = HL_FRONT_AND_BACK;
if(cybCore->getMaterialFace(i, DYNAMIC_FRICTION) == FRONT)
propertyFace[i][3] = HL_FRONT;
else if(cybCore->getMaterialFace(i, DYNAMIC_FRICTION) == BACK)
propertyFace[i][3] = HL_BACK;
else propertyFace[i][3] = HL_FRONT_AND_BACK;
if(cybCore->getMaterialFace(i, POPTHROUGH) == FRONT)
propertyFace[i][4] = HL_FRONT;
else if(cybCore->getMaterialFace(i, POPTHROUGH) == BACK)
propertyFace[i][4] = HL_BACK;
else propertyFace[i][4] = HL_FRONT_AND_BACK;
}
cybCore->materialFaceModified = false;
}
void CybPhantom::createAmbientContext()
{
CybViscosity *viscosity = CybViscosity::getInstance(cybCore->numLayer);
if(!shapeIdListIscreated)
{
genShapeIdList(cybCore->numLayer);
shapeIdListIscreated = true;
}
if(!materialPropertiesIsEnable)
genProperties();
hlAddEventCallback(HL_EVENT_UNTOUCH, HL_OBJECT_ANY, HL_CLIENT_THREAD,
&CybViscosity::untouchShapeCallback, NULL);
for(int i = 0; i < cybCore->numLayer; i++){
hlAddEventCallback(HL_EVENT_TOUCH, shapeId[i], HL_CLIENT_THREAD,
&CybViscosity::touchShapeCallback, &CybViscosity::ViscosityShapeAttribute[i].id);
hlAddEventCallback(HL_EVENT_MOTION, shapeId[i], HL_CLIENT_THREAD,
&CybViscosity::movingObjectCallback, &CybViscosity::ViscosityShapeAttribute[i].id);
}
habHapticLayersSave = new bool[cybCore->numLayer];
saveAttributes();
}
void CybPhantom::saveAttributes()
{
for(int i = 0; i < cybCore->numLayer; i++)
{
habHapticLayersSave[i] = habHapticLayers[i];
habHapticLayers[i] = true;
}
}
void CybPhantom::recoverAttributes()
{
for(int i = 0; i < cybCore->numLayer; i++){
habHapticLayers[i] = habHapticLayersSave[i];
}
}
|
class Solution {
public:
int firstUniqChar(string s) {
vector<int> count(26,0);
for(auto ch:s)
{
count[ch-'a']++;
}
for(int i=0; i < s.length(); i++)
{
if(count[s[i]-'a'] == 1) return i;
}
return -1;
}
};
|
#include "drake/multibody/multibody_tree/weld_mobilizer.h"
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/multibody/multibody_tree/multibody_tree.h"
#include "drake/multibody/multibody_tree/multibody_tree_system.h"
#include "drake/multibody/multibody_tree/rigid_body.h"
#include "drake/systems/framework/context.h"
namespace drake {
namespace multibody {
namespace multibody_tree {
namespace {
using Eigen::Isometry3d;
using Eigen::Matrix3d;
using Eigen::Translation3d;
using Eigen::Vector3d;
using Eigen::VectorXd;
using std::make_unique;
using std::unique_ptr;
using systems::Context;
constexpr double kTolerance = 10 * std::numeric_limits<double>::epsilon();
// Fixture to setup a simple MBT model containing a weld mobilizer.
class WeldMobilizerTest : public ::testing::Test {
public:
// Creates a simple model consisting of a single body with a weld mobilizer
// connecting it to the world, with the sole purpose of verifying the
// WeldMobilizer methods.
void SetUp() override {
// Spatial inertia for adding a body. The actual value is not important for
// these tests since they are all kinematic.
const SpatialInertia<double> M_B;
// Create an empty model.
auto model = std::make_unique<MultibodyTree<double>>();
// Add a body so we can add a mobilizer to it.
auto& body = model->AddBody<RigidBody>(M_B);
X_WB_ = Translation3d(1.0, 2.0, 3.0);
// Add a weld mobilizer between the world and the body:
weld_body_to_world_ = &model->AddMobilizer<WeldMobilizer>(
model->world_body().body_frame(), body.body_frame(), X_WB_);
// We are done adding modeling elements. Transfer tree to system and get
// a Context.
system_ = std::make_unique<MultibodyTreeSystem<double>>(std::move(model));
context_ = system_->CreateDefaultContext();
// Performance critical queries take a MultibodyTreeContext to avoid dynamic
// casting.
mbt_context_ = dynamic_cast<MultibodyTreeContext<double>*>(context_.get());
ASSERT_NE(mbt_context_, nullptr);
}
const MultibodyTree<double>& tree() const { return system_->tree(); }
protected:
std::unique_ptr<MultibodyTreeSystem<double>> system_;
std::unique_ptr<Context<double>> context_;
MultibodyTreeContext<double>* mbt_context_{nullptr};
const WeldMobilizer<double>* weld_body_to_world_{nullptr};
// Pose of body B in the world frame W.
Isometry3d X_WB_;
};
TEST_F(WeldMobilizerTest, ZeroSizedState) {
EXPECT_EQ(tree().num_positions(), 0);
EXPECT_EQ(tree().num_velocities(), 0);
}
TEST_F(WeldMobilizerTest, CalcAcrossMobilizerTransform) {
const Isometry3d X_FM =
weld_body_to_world_->CalcAcrossMobilizerTransform(*mbt_context_);
EXPECT_TRUE(CompareMatrices(X_FM.matrix(), X_WB_.matrix(),
kTolerance, MatrixCompareType::relative));
}
TEST_F(WeldMobilizerTest, CalcAcrossMobilizerSpatialVeloctiy) {
const VectorXd zero_sized_vector(0);
const SpatialVelocity<double> V_FM =
weld_body_to_world_->CalcAcrossMobilizerSpatialVelocity(
*mbt_context_, zero_sized_vector);
EXPECT_EQ(V_FM.get_coeffs(), Vector6<double>::Zero());
}
TEST_F(WeldMobilizerTest, CalcAcrossMobilizerSpatialAcceleration) {
const VectorXd zero_sized_vector(0);
const SpatialAcceleration<double> A_FM =
weld_body_to_world_->CalcAcrossMobilizerSpatialAcceleration(
*mbt_context_, zero_sized_vector);
EXPECT_EQ(A_FM.get_coeffs(), Vector6<double>::Zero());
}
TEST_F(WeldMobilizerTest, ProjectSpatialForce) {
VectorXd zero_sized_vector(0);
const SpatialForce<double> F_Mo_F; // value not important for this test.
// no-op, just tests we can call it with a zero sized vector.
weld_body_to_world_->ProjectSpatialForce(
*mbt_context_, F_Mo_F, zero_sized_vector);
}
TEST_F(WeldMobilizerTest, MapVelocityToQDotAndBack) {
VectorXd zero_sized_vector(0);
// These methods are no-ops, just test we can call them with zero sized
// vectors.
weld_body_to_world_->MapVelocityToQDot(*mbt_context_,
zero_sized_vector, &zero_sized_vector);
weld_body_to_world_->MapQDotToVelocity(*mbt_context_,
zero_sized_vector, &zero_sized_vector);
}
} // namespace
} // namespace multibody_tree
} // namespace multibody
} // namespace drake
|
#ifndef MAIN_DATA_STORAGE_H_
#define MAIN_DATA_STORAGE_H_
class DataStorage {
public:
double pitch;
double roll;
double heading;
double vsi;
double qnh;
int altitude;
int airspeed;
int ground_speed;
int desired_altitude;
int desired_heading;
};
#endif // MAIN_DATA_STORAGE_H_
|
#pragma once
#include <list>
#include <map>
#include <set>
#include "InputConstants.h"
#include "InputContext.h"
#include "InputFetcher.h"
// for organizing InputContexts in a set
struct PriorityInputContext {
InputContext* context;
int priority;
PriorityInputContext(InputContext* context = nullptr, int priority = 0) : context(context), priority(priority) {}
};
// less-than functor for KeyboardInput
struct PriorityInputContext_LT {
bool operator()(const PriorityInputContext& lhs, const PriorityInputContext& rhs) {
return lhs.priority > rhs.priority;
}
};
// for reading comprehension
typedef std::set<PriorityInputContext, PriorityInputContext_LT> PriorityContextSet;
/*
InputMapper is responsible for all InputContexts
InputMapper uses the observer pattern where it is the subject and InputContexts are the observers
*/
class InputMapper {
private:
InputFetcher _fetcher;
std::map<int, PriorityInputContext> _inputContexts;
PriorityContextSet _activeContexts;
private:
InputMapper() {}
InputMapper(const InputMapper&) = delete;
InputMapper operator=(const InputMapper&) = delete;
public:
static InputMapper& getInstance();
~InputMapper();
/*
register a new context
the context will remain inactive until activated
default priority is 0
*/
void registerContext(InputContext* context, int priority = 0);
/*
unregister an existing context
*/
void unregisterContext(InputContext* context);
/*
activate a context based on its id
return false if context doesnt exist
*/
bool activateContext(InputContext* context);
/*
deactivate a context based on its id
return false if context doesnt exist
*/
bool deactivateContext(InputContext* context);
// notify all active contexts about a key press
void notify();
};
|
/*
* masterhttpconnector.h
*
* Created on: 2015年5月3日
* Author: root
*/
#ifndef MASTERHTTPCONNECTOR_H_
#define MASTERHTTPCONNECTOR_H_
#include"AbstractMasterConnector.h"
#include<cstdint>
#include<list>
// @param maxim connection number
#define MAX_CONN_NUM 1024
#define INET_IPV4
#ifdef INET_IPV4
#define IN_ADDR_TYPE struct in_addr
#else
#define IN_ADDR_TYPE struct in_addr6
#endif
class MasterHttpConnector : public AbstractMasterConnector{
private:
//int conn_set[MAX_CONN_NUM];
std::list<int> conn_set
//network short
int http_port;
IN_ADDR_TYPE netw_addr;
int conn_num;
public:
MasterHttpConnector();
int init();
void startToListen();
void stopListening();
int registerHandle();
};
#endif /* MASTERHTTPCONNECTOR_H_ */
|
int Solution::searchInsert(vector<int> &a, int k) {
int n=a.size();
int l=0,h=n-1;
int ans=0;
while(h>=l)
{
int m=l+(h-l)/2;
if(a[m]==k)
return m;
if(a[m]>k)
h=m-1;
else
{
l=m+1;
ans=m+1;
}
}
return ans;
}
|
/*
* Copyright 2013 Maciej Poleski
*/
#ifndef BUILTINNAMETOTIMETRANSLATOR_H
#define BUILTINNAMETOTIMETRANSLATOR_H
#include "INameToTimeTranslator.hxx"
class BuiltinNameToTimeTranslator : public INameToTimeTranslator
{
public:
virtual std::tuple< uint_fast16_t, uint_fast16_t >
timeFromName(const std::string& name) const override;
};
#endif // BUILTINNAMETOTIMETRANSLATOR_H
|
#include <bits/stdc++.h>
#include "Test.h"
using namespace std;
Test::Test(){}
Test::Test(string person_name,int test_number,int questions_count, vector <int> points){
this->person_name=person_name;
this->test_number=test_number;
this->questions_count=questions_count;
this->points=points;
}
/*
void Test::read(){
cout<<"Input name:\n";
cin>>person_name;
do{
cin.clear();
cin.ignore(32767,'\n');
cout<<"Input test number:\n";
cin>>test_number;
}while(cin.fail());
do{
cin.clear();
cin.ignore(32767,'\n');
cout<<"Input number of questions:\n";
cin>>questions_count;
}while(cin.fail()||questions_count<0||questions_count>1e9);
points.resize(questions_count);
cout<<"Input score list:\n";
for(int i=0;i<questions_count;i++){
do{
cin.clear();
cin.ignore(32767,'\n');
cin>>points[i];
}while(cin.fail());
}
}
void Test::read(ifstream fin){
fin>>person_name>>test_number>>questions_count;
points.resize(questions_count);
for(int i=0;i<questions_count;i++){
fin>>points[i];
}
}
void Test::write(){
cout<<"Person name: "<<person_name<<"\nTest number: "<<test_number<<"\nQuestions count: "<<questions_count<<"\nScore:\n";
for(int i=0;i<questions_count;i++){
cout<<points[i]<<' ';
}
}
*/
int Test::compare(Test left, Test right){
if(left.person_name>right.person_name){
return 1;
}else if(left.person_name==right.person_name){
if(left.test_number>right.test_number){
return 1;
}else if(left.test_number==right.test_number){
return 0;
}
}
return -1;
}
bool Test::check(string name, int number,vector <int> bottom_edge, vector <int> top_edge){
if(person_name!=name&&name!="*"){
return false;
}
if(test_number!=number&&number!=-1){
return false;
}
for(int i=0;i<questions_count;i++){
if(points[i]<bottom_edge[i]||points[i]>top_edge[i]){
return false;
}
}
return true;
}
bool Test::check(int number){
return test_number==number;
}
int Test::getProperty(vector <int> weights){
int sum=0;
for(int i=0;i<questions_count;i++){
sum+=weights[i]*points[i];
}
return sum;
}
bool operator < (Test left,Test right){
return left.compare(left,right)<0;
}
bool operator> (Test left,Test right){
return left.compare(left,right)>0;
}
bool operator <= (Test left,Test right){
return left.compare(left,right)<=0;
}
bool operator >= (Test left,Test right){
return left.compare(left,right)>=0;
}
bool operator != (Test left,Test right){
return left.compare(left,right)!=0;
}
bool operator == (Test left,Test right){
return left.compare(left,right)==0;
}
ostream& operator << (ostream &out,Test &test){
out<<test.person_name<<'\n'<<test.test_number<<'\n'<<test.questions_count<<'\n';
for(int i=0;i<test.questions_count;i++){
out<<test.points[i]<<' ';
}
out<<'\n';
return out;
}
istream& operator >> (istream &in,Test &test){
in>>test.person_name>>test.test_number>>test.questions_count;
test.points.resize(test.questions_count);
for(int i=0;i<test.questions_count;i++){
in>>test.points[i];
}
return in;
}
|
#include <elevation_mapping/elevation_mapping.h>
namespace elevation_mapping
{
ElevationMapping::ElevationMapping(ros::NodeHandle nh) :
nh_(nh),
frame_count_(0)
{
}
ElevationMapping::~ElevationMapping()
{
}
void
ElevationMapping::init()
{
ros::NodeHandle private_nh("~");
get_octomap_client_ = nh_.serviceClient<octomap_msgs::GetOctomap>("octomap_binary");
get_elevation_map_client_ = nh_.advertiseService("get_elevation_map", &ElevationMapping::getHeightfieldMap, this);
private_nh.param<double>("max_z", max_z_, 1.5);
private_nh.param<std::string>("frame_id", frame_id_, std::string("/world"));
}
bool ElevationMapping::getHeightfieldMap(elevation_mapping::GetElevationMap::Request &request, elevation_mapping::GetElevationMap::Response &response)
{
octomap_msgs::GetOctomap srv;
if (!get_octomap_client_.call(srv))
{
ROS_ERROR("Failed to call service octomap_binary");
return false;
}
boost::shared_ptr<octomap::OcTree> oc_tree(octomap_msgs::binaryMsgToMap(srv.response.map));
double max_x, max_y, max_z;
oc_tree->getMetricMax(max_x, max_y, max_z);
double min_x, min_y, min_z;
oc_tree->getMetricMin(min_x, min_y, min_z);
double map_origin_x = min_x;
double map_origin_y = min_y;
double map_res = oc_tree->getNodeSize(oc_tree->getTreeDepth());
double delta_x = max_x - min_x;
double delta_y = max_y - min_y;
int rows = static_cast<int>((delta_x) / map_res);
int cols = static_cast<int>((delta_y) / map_res);
cv_bridge::CvImagePtr elevation_image_ptr = cv_bridge::CvImagePtr(new cv_bridge::CvImage);
elevation_image_ptr->encoding = std::string("mono16");
elevation_image_ptr->header.frame_id = frame_id_;
elevation_image_ptr->header.stamp = ros::Time::now();
elevation_image_ptr->header.seq = frame_count_++;
cv::scaleAdd(cv::Mat::ones(rows, cols, CV_32FC1), std::numeric_limits<float>::min(),
cv::Mat::zeros(rows, cols, CV_32FC1), elevation_image_ptr->image);
for (octomap::OcTree::iterator it = oc_tree->begin(), end = oc_tree->end(); it != end; ++it)
{
if (oc_tree->isNodeOccupied(*it))
{
octomap::point3d cell_coord = it.getCoordinate();
if(cell_coord.z() > max_z_)
continue;
int row, col;
worldCoordToCellCoord(cell_coord.x(), cell_coord.y(), map_origin_x, map_origin_y, map_res, row, col);
if(elevation_image_ptr->image.at<float>(rows - row - 1, col) < cell_coord.z())
{
elevation_image_ptr->image.at<float>(rows - row - 1, col) = cell_coord.z();
}
}
}
response.resolution = map_res;
response.origin_x = map_origin_x;
response.origin_y = map_origin_y;
elevation_image_ptr->toImageMsg(response.height_map);
return true;
}
void ElevationMapping::worldCoordToCellCoord(double x, double y, double map_origin_x, double map_origin_y, double map_res, int &row, int &col)
{
row = (x - map_origin_x) / map_res;
col = (y - map_origin_y) / map_res;
}
} // end namespace elevation_mapping
|
#include <Wire.h>
#include <Servo.h>
int valRead;
Servo servo;
int pos = 0; // variable to store the servo position
int incomingByte = 0; // for incoming serial data
bool shouldOpenDoor = false;
bool shouldCloseDoor = false;
void setup() {
Wire.begin(0x8);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
servo.attach(9);
servo.write(90);
}
void receiveEvent(int howMany) {
while(Wire.available()) {
char c = Wire.read();
valRead = c << 1;
if (valRead == 0) {
shouldCloseDoor = true;
} else {
shouldOpenDoor = true;
}
}
}
void openDoor() {
Serial.println("OPENING DOOR");
servo.write(0);
delay(2300);
servo.write(90);
Serial.println("DOOR IS OPEN");
}
void closeDoor() {
Serial.println("CLOSING DOOR");
servo.write(180);
delay(2300);
servo.write(90);
Serial.println("DOOR IS CLOSED");
}
// the loop function runs over and over again forever
void loop() {
delay(100);
if(shouldOpenDoor) {
shouldOpenDoor = false;
openDoor();
}
if(shouldCloseDoor) {
shouldCloseDoor = false;
closeDoor();
}
}
|
/**
* $Source: /backup/cvsroot/project/pnids/zdk/zls/zfc/CSingletonFactoryT.hpp,v $
*
* $Date: 2001/11/14 17:25:11 $
*
* $Revision: 1.3 $
*
* $Name: $
*
* $Author: zls $
*
* Copyright(C) since 1998 by Albert Zheng - 郑立松, All Rights Reserved.
*
* lisong.zheng@gmail.com
*
* $State: Exp $
*/
#ifndef _ZLS_zfc_CSingletonFactoryT_hpp_
#define _ZLS_zfc_CSingletonFactoryT_hpp_
#include <zls/zfc/Manifest.h>
#include <zls/zfc/SmartPointer.hpp>
// begin namespace "zfc::"
ZLS_BEGIN_NAMESPACE(zfc)
/**
* 这是一个"单件"工厂template,它只适用于constructor是default constructor的class.
*
* @note 如果一个class想限制在一个程序中只能有一个自己的"单件"实例,则必须:
* <pre>
* (1)这个class必须从zfc::CReferenceCounter继承.
* (2)将这个class的constructor放置在private或protected区中,这样可以防止用户误用
* new或"自动变量"来创建这个class的实例.
* (3)如果想利用CSingletonFactoryT这个template来帮助用户创建实例,则这个class的
* constructor必须是default constructor.
* (4)让template CSingletonFactoryT成为这个class的friend.
*
* 以下是个应用举例:
* CSingletonFactoryT<YOUR_CLASS> factory;
* CSmartPointerT<YOUR_CLASS> autoSingleton = factory.GetSingleton();
* autoSingleton->any_method();
* </pre>
*/
template <class CType>
class CSingletonFactoryT {
public:
typedef CSmartPointerT<CType> CSingleton_auto;
private:
/** 指向唯一的static singleton instance. */
static CType * _SpciSingleton;
/** 这个Smart Pointer将引用到那个唯一的static singleton instance. */
CSingleton_auto _autoSingleton;
public:
/**
* Constructor.
*
* @throw zfc::EOutOfMemory.
*/
CSingletonFactoryT()
{
if (! _SpciSingleton)
{
_SpciSingleton = new __OPTION(_THROW) CType();
}
// Let us reference to the singleton
_autoSingleton = _SpciSingleton;
}
CSingleton_auto & GetSingleton()
{
return _autoSingleton;
}
};
template <class CType>
CType * CSingletonFactoryT<CType>::_SpciSingleton = 0;
ZLS_END_NAMESPACE
#endif
|
#ifndef TAXONOMY_H
#define TAXONOMY_H
#include <string>
#include <vector>
#include <stack>
struct Node
{
std::string name;
std::vector<Node*> children;
Node(std::string name): name(name) { }
bool isLeaf() const
{
return children.empty();
}
Node* findChild(std::string name) const
{
for (auto it = children.begin(); it != children.end(); ++it)
{
if ((*it)->name == name) {
return *it;
}
}
return nullptr;
}
};
class Taxonomy
{
public:
class TaxonomyIterator
{
friend class Taxonomy;
Taxonomy* taxonomy;
std::stack<Node*> frames;
TaxonomyIterator(Taxonomy* taxonomy): taxonomy(taxonomy)
{
if (taxonomy->root != nullptr) {
frames.push(taxonomy->root);
unwind();
}
}
void unwind()
{
while (!frames.empty() && !frames.top()->isLeaf())
{
Node* top = frames.top();
frames.pop();
for (Node* child : top->children)
{
frames.push(child);
}
}
}
public:
bool hasNext() const
{
return !frames.empty();
}
std::string getValue() const
{
if (frames.empty()) {
return "";
}
return frames.top()->name;
}
void next()
{
if (!frames.empty())
{
frames.pop();
unwind();
}
}
};
Taxonomy();
virtual ~Taxonomy();
Taxonomy& addEntity(std::vector<std::string> path);
void print() const;
int countSpeciesWithTwoWords() const;
TaxonomyIterator iterateLeaves() {
return TaxonomyIterator(this);
}
void printPreOrder() const;
void printPostOrder() const;
private:
int countSpeciesWithTwoWords(Node* node) const;
void printPreOrder(Node*) const;
void printPostOrder(Node*) const;
protected:
private:
Node* root;
void deleteNode(Node* node);
void print(Node* node, std::vector<std::string>& path) const;
};
#endif // TAXONOMY_H
|
#pragma once
#include <string>
class MapAIHitBox
{
public:
MapAIHitBox(float x, float y, float width, float height, std::string event = "", std::string eventaction = "");
~MapAIHitBox();
bool hitdetection(MapAIHitBox tocheck);
float x;
float y;
float width;
float height;
std::string event;
std::string eventAction;
};
|
/*****
描述
石头剪子布是一种很简单的游戏:
石头胜剪子
剪子胜布
布胜石头
A和B猜拳,已知他们出拳的序列,编程求出谁胜谁负。
关于输入
第一行是一个正整数n(n<200),表明A和B一共猜了n次拳。
接下来是n行,每行有两个数字,分别表示A和B在这次猜拳中出了什么。0表示石头,1表示剪刀,2表示布。
关于输出
输出一行,"A"表示A胜,"B"表示B胜,"Tie"表示平局。
例子输入
4
1 0
2 2
1 2
2 0
例子输出
A
*****/
#include <iostream>
using namespace std;
int main()
{
int a = 0, b = 0, w = 0, n = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b;
switch((a - b + 3) % 3)
{
case 1: w--; break; // B赢
case 2: w++; break; // A赢
case 0: // 平局
default: break;
}
}
if (w > 0)
cout << "A";
else if (w < 0)
cout << "B";
else
cout << "Tie";
return 0;
}
|
/*
Name: Mohit Kishorbhai Sheladiya
Student ID: 117979203
Student Email: mksheladiya@myseneca.ca
Date: 21/02/16
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <istream>
#include <iomanip>
#include <cstring>
#include "Account.h"
using namespace std;
namespace sdds {
void Account::setEmpty() {
m_number = -1;
m_balance = 0.0;
}
// New account
Account::Account() {
m_number = 0;
m_balance = 0.0;
}
Account::Account(int number, double balance) {
setEmpty();
if (number >= 10000 && number <= 99999
&& balance > 0) {
m_number = number;
m_balance = balance;
}
}
std::ostream& Account::display() const {
if (*this) {
cout << " ";
if (m_number > 0)
cout << m_number;
else cout << " NEW ";
cout << " | ";
cout.width(12);
cout.precision(2);
cout.setf(ios::right);
cout.setf(ios::fixed);
cout << m_balance;
cout.unsetf(ios::right);
cout << " ";
}
else if (~*this) {
cout << " NEW | 0.00 ";
}
else {
cout << " BAD | ACCOUNT ";
}
return cout;
}
Account::operator bool()const {
if (m_number != -1)
return true;
else
return false;
}
Account::operator int()const {
return m_number;
}
Account::operator double()const {
return m_balance;
}
bool Account::operator ~()const {
if (m_number == 0)
return true;
else
return false;
}
Account& Account::operator=(int num) {
if(num < 10000 || num > 99999)
setEmpty();
else if (m_number == 0)
m_number = num;
return *this;
}
Account& Account::operator=(Account& newobj) {
if (m_number != -1) {
if (newobj.m_number > 9999 && newobj.m_number < 100000) {
m_balance = newobj.m_balance;
newobj.m_balance = 0.0;
m_number = newobj.m_number;
newobj.m_number = 0.0;
}
}
return *this;
}
Account& Account::operator+=(double bal) {
if (m_number > 9999 && m_number < 100000 && bal > 0 && m_balance > 0)
m_balance += bal;
return *this;
}
Account& Account::operator-=(double bal) {
if (m_number > 9999 && m_number < 100000 && bal > 0 && m_balance >= bal)
m_balance -= bal;
return *this;
}
Account& Account::operator<<(Account& A) {
if (this->m_number != A.m_number) {
this->m_balance += A.m_balance;
A.m_balance = 0.0;
}
return *this;
}
Account& Account::operator>>(Account& B) {
if (this->m_number != B.m_number) {
B.m_balance += this->m_balance;
this->m_balance = 0.0;
}
return *this;
}
double Account::getBalance()const {
return m_balance;
}
int Account::getNumber()const {
return m_number;
}
double operator+(const Account& a1, const Account& a2) {
double sum = 0.0;
if (a1.getNumber() > 9999 && a1.getNumber() < 100000 && a2.getNumber() > 9999 && a2.getNumber() < 100000) {
if(a1.getBalance() > 0 && a2.getBalance() > 0)
sum = a1.getBalance() + a2.getBalance();
}
return sum;
}
double operator+=(double& a1, const Account& a2) {
a1 += a2.getBalance();
return a1;
}
}
|
/****************************************************
* RoseBin :: Binary Analysis for ROSE
* Author : tps
* Date : Jul27 07
* Decription : Control flow Analysis
****************************************************/
#ifndef __RoseBin_ControlFlowAnalysis__
#define __RoseBin_ControlFlowAnalysis__
#include "RoseBin_FlowAnalysis.h"
#include "RoseBin_abstract.h"
//class RoseBin;
//class RoseFile;
class RoseBin_ControlFlowAnalysis : public RoseBin_FlowAnalysis {
void getCFGNodesForFunction(std::set<SgGraphNode*>& visited_f,
std::set<std::string>& visited_names,
SgGraphNode* next_n, std::string nodeName);
public:
RoseBin_ControlFlowAnalysis(SgAsmNode* global, bool forward, RoseBin_abstract* ,
bool printedges,GraphAlgorithms* algo):
RoseBin_FlowAnalysis(global,algo) {
typeNode="CFG";
typeEdge="CFG-E";
analysisName="cfa";
printEdges = printedges;
forward_analysis=forward;
}
/*
RoseBin_ControlFlowAnalysis(SgAsmNode* global, bool forward, RoseFile* ,
bool printedges, GraphAlgorithms* algo):
RoseBin_FlowAnalysis(global, algo) {
typeNode="CFG";
typeEdge="CFG-E";
analysisName="cfa";
printEdges = printedges;
forward_analysis=forward;
}
*/
~RoseBin_ControlFlowAnalysis() {
delete globalBin;
//delete roseBin;
delete vizzGraph;
std::map <std::string, SgAsmFunction* >::iterator it;
for (it = bin_funcs.begin();
it!= bin_funcs.end(); it++) {
delete it->second;
}
}
//void checkControlFlow(SgAsmInstruction* binInst, int functionSize, int countDown,
// std::string& nameOfFunction, int func_nr);
// visit the binary AST
//void visit(SgNode* node) ;
// run this analysis
void run(RoseBin_Graph* vg, std::string fileN, bool multiedge) ;
void printGraph(std::string fileName, std::set<std::string>& filter);
};
#endif
|
class System
{
public:
int getK();
int getRa();
int getRb();
void setK(int tmpK );
void setRa(int tmpRa);
void setRb(int tmpRb);
void calculate(float Sa);
private:
int K;
int Ra,Rb;
};
|
/*
Cell.h
Contains funcitonality for the cell class
Fouad Al-Rijleh, Rachel Rudolph
*/
#pragma once
#include "d_matrix.h"
#include "d_except.h"
#include "Constants.h"
#include <vector>
class Cell
{
private:
vector<int> location;
int value;
public:
void setLocation(int i, int j);
void setLocation(vector<int> newLocation);
vector<int> getLocation();
void setValue(int newValue);
int getValue();
Cell();
~Cell();
};
|
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
delay(2000);
int16_t bigNum, smallNum;
byte a,b;
Wire.requestFrom(54,2);
a = Wire.read();
b = Wire.read();
smallNum = a;
bigNum = smallNum << 8 | b;
Serial.print(bigNum);
Serial.print("\n");
}
|
#ifndef NOTEPAD_H
#define NOTEPAD_H
#include <QWidget>
#include <QTextEdit>
#include <QPushButton>
class Notepad : public QWidget {
public:
Notepad();
~Notepad();
// slots, to connect with signals
void open();
void save();
void exit();
private:
QTextEdit* text_edit = new QTextEdit;
QPushButton* open_button = new QPushButton{tr("&Open")};
QPushButton* save_button = new QPushButton{tr("&Save")};
QPushButton* exit_button = new QPushButton{tr("E&xit")};
};
#endif // NOTEPAD_H
|
/* NO WARRANTY
*
* BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO
* WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
* LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS
* AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
* THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD
* THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
* NECESSARY SERVICING, REPAIR OR CORRECTION.
*
* IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
* WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY
* AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES,
* INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
* (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
* RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
* OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
* PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#include "math.h"
#include "stdafx.h"
#include "Application\DigitalSimulatorApp.h"
#include "Application\i18n\ResourceTranslater.h"
#include "Application\Configuration\ParameterManager.h"
#include "Application\Objects\buildin\digital\ElectricNode.h"
#include "Application\Objects\buildin\digital\context\ElectricNodeContextDemultiplexer.h"
#include "DialogDemultiplexerParam.h"
BEGIN_MESSAGE_MAP(CDialogDemultiplexerParam, CSnapDialog)
//{{AFX_MSG_MAP(CDialogDemultiplexerParam)
ON_EN_CHANGE(IDC_ADDRESS_COUNT_EDIT, OnChangeAddressCountEdit)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CDialogDemultiplexerParam::CDialogDemultiplexerParam(CWnd* pParent,CElectricNode::CElectricNodeDokument& data)
: inherited(CDialogDemultiplexerParam::IDD, pParent),
m_data(data)
{
//{{AFX_DATA_INIT(CDialogDemultiplexerParam)
m_addressCount = 0;
m_outputCount = 0;
//}}AFX_DATA_INIT
}
//----------------------------------------------------------------------------
void CDialogDemultiplexerParam::DoDataExchange(CDataExchange* pDX){
//----------------------------------------------------------------------------
PROC_TRACE;
inherited::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDialogDemultiplexerParam)
DDX_Control(pDX, IDC_IMAGE_STATIC, m_image);
DDX_Control(pDX, IDOK, m_okButton);
DDX_Control(pDX, IDCANCEL, m_cancelButton);
DDX_Control(pDX, IDC_OUTPUT_COUNT_EDIT, m_outputEdit);
DDX_Control(pDX, IDC_ADDRESS_COUNT_SPIN, m_countSpin);
DDX_Control(pDX, IDC_ADDRESS_COUNT_EDIT, m_countEdit);
DDX_Text(pDX, IDC_ADDRESS_COUNT_EDIT, m_addressCount);
DDX_Text(pDX, IDC_OUTPUT_COUNT_EDIT, m_outputCount);
//}}AFX_DATA_MAP
}
//----------------------------------------------------------------------------
BOOL CDialogDemultiplexerParam::OnInitDialog() {
//----------------------------------------------------------------------------
PROC_TRACE;
inherited::OnInitDialog();
// TODO: Zusätzliche Initialisierung hier einfügen
TRANSLATE_DIALOG_ITEM(IDOK);
TRANSLATE_DIALOG_ITEM(IDCANCEL);
TRANSLATE_DIALOG_ITEM(IDC_ADDRESS_STATIC);
TRANSLATE_DIALOG_ITEM(IDC_OUTPUT_STATIC);
SetWindowText(TRANSLATE("Demultiplexer Grundeinstellungen"));
m_okButton.SetShaded();
m_cancelButton.SetShaded();
CSize inRange;
CSize outRange;
inRange = m_data.pOwner->GetInputCountRange();
outRange = m_data.pOwner->GetOutputCountRange();
m_countSpin.SetBuddy(&m_countEdit);
m_countSpin.SetRange(1,4);
m_countSpin.SetPos(max(m_data.param[CElectricNodeContextDemultiplexer::addressCount],1));
m_countSpin.SetPos(min(m_data.param[CElectricNodeContextDemultiplexer::addressCount],4));
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX-Eigenschaftenseiten sollten FALSE zurückgeben
}
//----------------------------------------------------------------------------
void CDialogDemultiplexerParam::OnChangeAddressCountEdit() {
//----------------------------------------------------------------------------
PROC_TRACE;
static lastPos =0;
char buffer[100];
sprintf(buffer,"%d", (int)pow(2,m_countSpin.GetPos()));
m_outputEdit.SetWindowText(buffer);
}
//----------------------------------------------------------------------------
void CDialogDemultiplexerParam::OnOK() {
//----------------------------------------------------------------------------
PROC_TRACE;
UpdateData();
m_data.outCount = m_outputCount;
m_data.inCount = 1 + m_addressCount;
inherited::OnOK();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.