repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
kazeevn/catboost
catboost/libs/fstr/shap_values.h
<filename>catboost/libs/fstr/shap_values.h #pragma once #include <catboost/libs/model/model.h> #include <catboost/libs/data/pool.h> #include <util/generic/vector.h> TVector<TVector<double>> CalcShapValues( const TFullModel& model, const TPool& pool, int threadCount, int logPeriod = 0, int dimension = 0 ); void CalcAndOutputShapValues( const TFullModel& model, const TPool& pool, const TString& outputPath, int threadCount, int logPeriod = 0, int dimension = 0 );
kazeevn/catboost
catboost/libs/quantized_pool/serialization.h
#pragma once #include <util/generic/fwd.h> #include <util/stream/fwd.h> namespace NCB { struct TQuantizedPool; struct TQuantizedPoolDigest; namespace NIdl { class TPoolQuantizationSchema; } } namespace NCB { void SaveQuantizedPool(const TQuantizedPool& pool, IOutputStream* output); struct TLoadQuantizedPoolParameters { bool LockMemory{true}; bool Precharge{true}; }; // Load quantized pool saved by `SaveQuantizedPool` from file. TQuantizedPool LoadQuantizedPool(TStringBuf path, const TLoadQuantizedPoolParameters& params); // TODO(yazevnul): rename it to `LoadQuantizationSchemaFromPool` NIdl::TPoolQuantizationSchema LoadQuantizationSchema(TStringBuf path); TQuantizedPoolDigest CalculateQuantizedPoolDigest(TStringBuf path); }
kazeevn/catboost
library/coroutine/engine/impl.h
<reponame>kazeevn/catboost #pragma once #include "poller.h" #include <util/system/mutex.h> #include <util/system/error.h> #include <util/system/context.h> #include <util/system/defaults.h> #include <util/system/valgrind.h> #include <util/network/iovec.h> #include <util/memory/tempbuf.h> #include <util/memory/smallobj.h> #include <util/memory/addstorage.h> #include <util/network/socket.h> #include <util/network/nonblock.h> #include <util/generic/ptr.h> #include <util/generic/buffer.h> #include <util/generic/vector.h> #include <library/containers/intrusive_rb_tree/rb_tree.h> #include <util/generic/utility.h> #include <util/generic/intrlist.h> #include <util/generic/yexception.h> #include <util/datetime/base.h> #include <util/stream/format.h> class TCont; struct TContRep; class TContEvent; class TContExecutor; class TContPollEvent; typedef void (*TContFunc)(TCont*, void*); #include "iostatus.h" #if defined(_win_) #define IOV_MAX 16 #endif #if defined(_bionic_) #define IOV_MAX 1024 #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4265) // class has virtual functions, but destructor is not virtual #endif #if defined(DEBUG_CONT) #define PCORO(p) Hex(size_t(p)) << " (" << p->Name() << ")" #define DBGOUT(x) Cdbg << x << Endl #else #define DBGOUT(x) #endif struct TContPollEventCompare { template <class T> static inline bool Compare(const T& l, const T& r) noexcept { return l.DeadLine() < r.DeadLine() || (l.DeadLine() == r.DeadLine() && &l < &r); } }; class TContPollEvent: public TRbTreeItem<TContPollEvent, TContPollEventCompare> { public: inline TContPollEvent(TCont* cont, TInstant deadLine) noexcept : Cont_(cont) , DeadLine_(deadLine) , Status_(EINPROGRESS) { } inline int Status() const noexcept { return Status_; } inline void SetStatus(int status) noexcept { Status_ = status; } inline TCont* Cont() noexcept { return Cont_; } inline TInstant DeadLine() const noexcept { return DeadLine_; } inline void Wake(int status) noexcept { SetStatus(status); Wake(); } private: inline void Wake() noexcept; private: TCont* Cont_; TInstant DeadLine_; int Status_; }; template <class T> inline int ExecuteEvent(T* event) noexcept; class IPollEvent: public TIntrusiveListItem<IPollEvent> { public: inline IPollEvent(SOCKET fd, ui16 what) : Fd_(fd) , What_(what) { } inline SOCKET Fd() const noexcept { return Fd_; } inline int What() const noexcept { return What_; } virtual void OnPollEvent(int status) noexcept = 0; private: SOCKET Fd_; ui16 What_; }; class TFdEvent final: public TContPollEvent, public IPollEvent { public: inline TFdEvent(TCont* cont, SOCKET fd, ui16 what, TInstant deadLine) noexcept : TContPollEvent(cont, deadLine) , IPollEvent(fd, what) { } inline ~TFdEvent() { RemoveFromIOWait(); } inline void RemoveFromIOWait() noexcept; void OnPollEvent(int status) noexcept override { Wake(status); } }; class TTimerEvent: public TContPollEvent { public: inline TTimerEvent(TCont* cont, TInstant deadLine) noexcept : TContPollEvent(cont, deadLine) { } }; class TContPollEventHolder { public: TContPollEventHolder(void* memory, TCont* rep, SOCKET fds[], int what[], size_t nfds, TInstant deadline); ~TContPollEventHolder(); void ScheduleIoWait(TContExecutor* executor); TFdEvent* TriggeredEvent(); private: TFdEvent* Events_; size_t Count_; }; class TInterruptibleEvent { public: TInterruptibleEvent(TCont* cont) : Cont_(cont) { } bool Interrupted() const noexcept { return Interrupted_; } void Interrupt(); template <typename F> TContIOStatus Wait(F&& f); private: TCont* Cont_ = nullptr; bool Interrupted_ = false; }; class TCont { struct TJoinWait: public TIntrusiveListItem<TJoinWait> { inline TJoinWait(TCont* c) noexcept : C(c) { } inline void Wake() noexcept { C->ReSchedule(); } TCont* C; }; friend struct TContRep; friend class TContExecutor; friend class TContPollEvent; public: inline TCont(TContExecutor* executor, TContRep* rep, TContFunc func, void* arg, const char* name) : Executor_(executor) , Rep_(rep) , Func_(func) , Arg_(arg) , Name_(name) , Cancelled_(false) , Scheduled_(false) { } inline ~TCont() { Executor_ = nullptr; Rep_ = nullptr; } inline void SetExecutor(TContExecutor* e) noexcept { Executor_ = e; } inline void SwitchTo(TCont* next) noexcept { DBGOUT(PCORO(this) << " switch to " << PCORO(next)); Context()->SwitchTo(next->Context()); } inline TExceptionSafeContext* Context() noexcept { #if defined(STACK_GROW_DOWN) return (TExceptionSafeContext*)(((char*)(this)) + Align(sizeof(TCont))); #else #error todo #endif } inline const TExceptionSafeContext* Context() const noexcept { return const_cast<TCont*>(this)->Context(); } inline TContExecutor* Executor() noexcept { return Executor_; } inline const TContExecutor* Executor() const noexcept { return Executor_; } inline TContRep* Rep() noexcept { return Rep_; } inline const TContRep* Rep() const noexcept { return Rep_; } inline const char* Name() const noexcept { return Name_; } void PrintMe(IOutputStream& out) const noexcept; inline void Yield() noexcept { if (SleepD(TInstant::Zero())) { ReScheduleAndSwitch(); } } inline void ReScheduleAndSwitch() noexcept; int SelectD(SOCKET fds[], int what[], size_t nfds, SOCKET* outfd, TInstant deadline); inline int SelectT(SOCKET fds[], int what[], size_t nfds, SOCKET* outfd, TDuration timeout) { return SelectD(fds, what, nfds, outfd, timeout.ToDeadLine()); } inline int SelectT(SOCKET fds[], int what[], size_t nfds, SOCKET* outfd) { return SelectD(fds, what, nfds, outfd, TInstant::Max()); } inline int PollD(SOCKET fd, int what, TInstant deadline) { DBGOUT(PCORO(this) << " prepare poll"); TFdEvent event(this, fd, (ui16)what, deadline); return ExecuteEvent(&event); } inline int PollT(SOCKET fd, int what, TDuration timeout) { return PollD(fd, what, timeout.ToDeadLine()); } inline int PollI(SOCKET fd, int what) { return PollD(fd, what, TInstant::Max()); } /// @return ETIMEDOUT on success inline int SleepD(TInstant deadline) { DBGOUT(PCORO(this) << " do sleep"); TTimerEvent event(this, deadline); return ExecuteEvent(&event); } inline int SleepT(TDuration timeout) { return SleepD(timeout.ToDeadLine()); } inline int SleepI() { return SleepD(TInstant::Max()); } TContIOStatus ReadD(SOCKET fd, void* buf, size_t len, TInstant deadline); inline TContIOStatus ReadT(SOCKET fd, void* buf, size_t len, TDuration timeout) { return ReadD(fd, buf, len, timeout.ToDeadLine()); } inline TContIOStatus ReadI(SOCKET fd, void* buf, size_t len) { return ReadD(fd, buf, len, TInstant::Max()); } TContIOStatus WriteVectorD(SOCKET fd, TContIOVector* vec, TInstant deadline); inline TContIOStatus WriteVectorT(SOCKET fd, TContIOVector* vec, TDuration timeOut) { return WriteVectorD(fd, vec, timeOut.ToDeadLine()); } inline TContIOStatus WriteVectorI(SOCKET fd, TContIOVector* vec) { return WriteVectorD(fd, vec, TInstant::Max()); } TContIOStatus WriteD(SOCKET fd, const void* buf, size_t len, TInstant deadline); inline TContIOStatus WriteT(SOCKET fd, const void* buf, size_t len, TDuration timeout) { return WriteD(fd, buf, len, timeout.ToDeadLine()); } inline TContIOStatus WriteI(SOCKET fd, const void* buf, size_t len) { return WriteD(fd, buf, len, TInstant::Max()); } inline void Exit(); int Connect(TSocketHolder& s, const struct addrinfo& ai, TInstant deadLine); int Connect(TSocketHolder& s, const TNetworkAddress& addr, TInstant deadLine); inline int Connect(TSocketHolder& s, const TNetworkAddress& addr, TDuration timeOut) { return Connect(s, addr, timeOut.ToDeadLine()); } inline int Connect(TSocketHolder& s, const TNetworkAddress& addr) { return Connect(s, addr, TInstant::Max()); } int ConnectD(SOCKET s, const struct sockaddr* name, socklen_t namelen, TInstant deadline); inline int ConnectT(SOCKET s, const struct sockaddr* name, socklen_t namelen, TDuration timeout) { return ConnectD(s, name, namelen, timeout.ToDeadLine()); } inline int ConnectI(SOCKET s, const struct sockaddr* name, socklen_t namelen) { return ConnectD(s, name, namelen, TInstant::Max()); } int AcceptD(SOCKET s, struct sockaddr* addr, socklen_t* addrlen, TInstant deadline); inline int AcceptT(SOCKET s, struct sockaddr* addr, socklen_t* addrlen, TDuration timeout) { return AcceptD(s, addr, addrlen, timeout.ToDeadLine()); } inline int AcceptI(SOCKET s, struct sockaddr* addr, socklen_t* addrlen) { return AcceptD(s, addr, addrlen, TInstant::Max()); } static inline SOCKET Socket(int domain, int type, int protocol) { return Socket4(domain, type, protocol); } static inline SOCKET Socket(const struct addrinfo& ai) { return Socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol); } static inline bool IsBlocked() noexcept { return IsBlocked(LastSystemError()); } static inline bool IsBlocked(int lasterr) noexcept { return lasterr == EAGAIN || lasterr == EWOULDBLOCK; } /* * useful for keep-alive connections */ static inline bool SocketNotClosedByOtherSide(SOCKET s) noexcept { const int r = MsgPeek(s); return r > 0 || (r == -1 && IsBlocked()); } static inline bool HavePendingData(SOCKET s) noexcept { return MsgPeek(s) > 0; } static inline int MsgPeek(SOCKET s) noexcept { char c; return recv(s, &c, 1, MSG_PEEK); } inline bool IAmRunning() const noexcept; inline void Cancel() noexcept; inline bool Cancelled() const noexcept { return Cancelled_; } inline bool Scheduled() const noexcept { return Scheduled_; } inline void WakeAllWaiters() noexcept { while (!Waiters_.Empty()) { Waiters_.PopFront()->Wake(); } } inline bool Join(TCont* c) noexcept { return Join(c, TInstant::Max()); } inline bool Join(TCont* c, TInstant deadLine) noexcept { DBGOUT(PCORO(this) << " join " << PCORO(c)); TJoinWait ev(this); c->Waiters_.PushBack(&ev); if (SleepD(deadLine) == ETIMEDOUT || Cancelled()) { if (!ev.Empty()) { c->Cancel(); do { SwitchToScheduler(); } while (!ev.Empty()); } return false; } return true; } /* * please dont use this :) */ inline void SwitchToScheduler() noexcept; inline void ReSchedule() noexcept; private: inline void Execute() { Y_ASSERT(Func_); Func_(this, Arg_); } public: static ssize_t DoRead(SOCKET fd, char* buf, size_t len) noexcept; static ssize_t DoWrite(SOCKET fd, const char* buf, size_t len) noexcept; static ssize_t DoWriteVector(SOCKET fd, TContIOVector* vec) noexcept; private: TContExecutor* Executor_; TContRep* Rep_; TContFunc Func_; void* Arg_; const char* Name_; TIntrusiveList<TJoinWait> Waiters_; bool Cancelled_; bool Scheduled_; }; #include "stack.h" struct TContRep: public TIntrusiveListItem<TContRep>, public ITrampoLine { TContRep(TContStackAllocator* alloc); void DoRun() override; void Construct(TContExecutor* executor, TContFunc func, void* arg, const char* name); void Destruct() noexcept; inline TCont* ContPtr() noexcept { return (TCont*)cont.Data(); } inline const TCont* ContPtr() const noexcept { return (const TCont*)cont.Data(); } inline TExceptionSafeContext* MachinePtr() noexcept { return (TExceptionSafeContext*)machine.Data(); } static inline size_t OverHead() noexcept { return Align(sizeof(TCont)) + Align(sizeof(TExceptionSafeContext)); } static inline size_t EffectiveStackLength(size_t alloced) noexcept { return alloced - OverHead(); } static inline size_t ToAllocate(size_t stackLen) noexcept { return Align(stackLen) + OverHead(); } inline bool IAmRuning() const noexcept { return ContPtr()->IAmRunning(); } TContStackAllocator::TStackPtr real; TMemRegion full; #if defined(STACK_GROW_DOWN) TMemRegion stack; TMemRegion cont; TMemRegion machine; #else #error todo #endif }; struct TPollEventList: public TIntrusiveList<IPollEvent> { inline ui16 Flags() const noexcept { ui16 ret = 0; for (TConstIterator it = Begin(); it != End(); ++it) { ret |= it->What(); } return ret; } }; class TEventWaitQueue { struct TCancel { inline void operator()(TContPollEvent* e) noexcept { e->Cont()->Cancel(); } inline void operator()(TContPollEvent& e) noexcept { operator()(&e); } }; typedef TRbTree<TContPollEvent, TContPollEventCompare> TIoWait; public: inline void Register(TContPollEvent* event) { IoWait_.Insert(event); event->Cont()->Rep()->Unlink(); } inline bool Empty() const noexcept { return IoWait_.Empty(); } inline void Abort() noexcept { TCancel visitor; IoWait_.ForEach(visitor); } inline TInstant CancelTimedOut(TInstant now) noexcept { TIoWait::TIterator it = IoWait_.Begin(); if (it != IoWait_.End()) { if (it->DeadLine() > now) { return it->DeadLine(); } do { (it++)->Wake(ETIMEDOUT); } while (it != IoWait_.End() && it->DeadLine() <= now); } return now; } private: TIoWait IoWait_; }; #include "sockmap.h" template <class T> class TBigArray { struct TValue: public T, public TObjectFromPool<TValue> { inline TValue() { } }; public: inline TBigArray() : Pool_(TMemoryPool::TExpGrow::Instance(), TDefaultAllocator::Instance()) { } inline T* Get(size_t index) { TRef& ret = Lst_.Get(index); if (!ret) { ret = new (&Pool_) TValue(); } return ret.Get(); } private: typedef TAutoPtr<TValue> TRef; typename TValue::TPool Pool_; TSocketMap<TRef> Lst_; }; class TContPoller { public: typedef IPollerFace::TEvent TEvent; typedef IPollerFace::TEvents TEvents; inline TContPoller() : P_(IPollerFace::Default()) { } inline explicit TContPoller(THolder<IPollerFace> poller) : P_(std::move(poller)) {} inline void Schedule(IPollEvent* event) { TPollEventList* lst = List(event->Fd()); const ui16 oldFlags = lst->Flags(); lst->PushFront(event); const ui16 newFlags = lst->Flags(); if (newFlags != oldFlags) { P_->Set(lst, event->Fd(), newFlags); } } inline void Remove(IPollEvent* event) noexcept { TPollEventList* lst = List(event->Fd()); const ui16 oldFlags = lst->Flags(); event->Unlink(); const ui16 newFlags = lst->Flags(); if (newFlags != oldFlags) { P_->Set(lst, event->Fd(), newFlags); } } inline size_t Wait(TEvents& events, TInstant deadLine) { events.clear(); P_->Wait(events, deadLine); return events.size(); } private: inline TPollEventList* List(size_t fd) { return Lists_.Get(fd); } private: TBigArray<TPollEventList> Lists_; THolder<IPollerFace> P_; }; class TContRepPool { typedef TIntrusiveListWithAutoDelete<TContRep, TDelete> TFreeReps; public: inline TContRepPool(TContStackAllocator* alloc) : Alloc_(alloc) { } inline TContRepPool(size_t stackLen) : MyAlloc_(new TDefaultStackAllocator(TContRep::ToAllocate(AlignUp<size_t>(stackLen, 2 * STACK_ALIGN)))) , Alloc_(MyAlloc_.Get()) { } inline TContRep* Allocate() { if (Free_.Empty()) { return new TContRep(Alloc_); } return Free_.PopFront(); } inline void Release(TContRep* cont) noexcept { Free_.PushFront(cont); } private: THolder<TContStackAllocator> MyAlloc_; TContStackAllocator* Alloc_; TFreeReps Free_; }; template <class Functor> static void ContHelperFunc(TCont* cont, void* arg) { (*((Functor*)(arg)))(cont); } template <typename T, void (T::*M)(TCont*)> static void ContHelperMemberFunc(TCont* c, void* arg) { ((ReinterpretCast<T*>(arg))->*M)(c); } /// Central coroutine class. /// Note, coroutines are single-threaded, and all methods must be called from the single thread class TContExecutor { friend class TCont; friend struct TContRep; friend class TContEvent; friend class TContPollEvent; friend class TContPollEventHolder; typedef TIntrusiveList<TContRep> TContList; struct TCancel { inline void operator()(TContRep* c) noexcept { c->ContPtr()->Cancel(); } }; struct TNoOp { template <class T> inline void operator()(T*) noexcept { } }; struct TReleaseAll { inline void operator()(TContRep* c) noexcept { c->ContPtr()->Executor()->Release(c); } }; public: TContExecutor(size_t stackSize, THolder<IPollerFace> poller = IPollerFace::Default()); TContExecutor(TContRepPool* pool, THolder<IPollerFace> poller = IPollerFace::Default()); ~TContExecutor(); /* * assume we already create all necessary coroutines */ inline void Execute() { TNoOp nop; Execute(nop); } inline void Execute(TContFunc func, void* arg = nullptr) { Create(func, arg, "sys_main"); RunScheduler(); } template <class Functor> inline void Execute(Functor& f) { Execute((TContFunc)ContHelperFunc<Functor>, (void*)&f); } template <typename T, void (T::*M)(TCont*)> inline void Execute(T* obj) { Execute(ContHelperMemberFunc<T, M>, obj); } inline TExceptionSafeContext* SchedCont() noexcept { return &SchedContext_; } template <class Functor> inline TContRep* Create(Functor& f, const char* name) { return Create((TContFunc)ContHelperFunc<Functor>, (void*)&f, name); } template <typename T, void (T::*M)(TCont*)> inline TContRep* Create(T* obj, const char* name) { return Create(ContHelperMemberFunc<T, M>, obj, name); } inline TContRep* Create(TContFunc func, void* arg, const char* name) { TContRep* cont = CreateImpl(func, arg, name); ScheduleExecution(cont); return cont; } inline TContPoller* Poller() noexcept { return &Poller_; } inline TEventWaitQueue* WaitQueue() noexcept { return &WaitQueue_; } inline TContRep* Running() noexcept { return Current_; } inline const TContRep* Running() const noexcept { return Current_; } inline void Abort() noexcept { WaitQueue_.Abort(); TCancel visitor; Ready_.ForEach(visitor); } inline void SetFailOnError(bool fail) noexcept { FailOnError_ = fail; } inline bool FailOnError() const noexcept { return FailOnError_; } inline void ScheduleIoWait(TFdEvent* event) { DBGOUT(PCORO(event->Cont()) << " schedule iowait"); WaitQueue_.Register(event); Poller_.Schedule(event); } inline void ScheduleIoWait(TTimerEvent* event) noexcept { DBGOUT(PCORO(event->Cont()) << " schedule timer"); WaitQueue_.Register(event); } private: inline TContRep* CreateImpl(TContFunc func, void* arg, const char* name) { TContRep* cont = Pool_.Allocate(); cont->Construct(this, func, arg, name); cont->Unlink(); return cont; } inline void Release(TContRep* cont) noexcept { DBGOUT(PCORO(cont->ContPtr()) << " release"); cont->Unlink(); cont->Destruct(); Pool_.Release(cont); } inline void Exit(TContRep* cont) noexcept { DBGOUT(PCORO(cont->ContPtr()) << " exit"); ScheduleToDelete(cont); cont->ContPtr()->SwitchToScheduler(); Y_FAIL("can not return from exit"); } void RunScheduler(); inline void ScheduleToDelete(TContRep* cont) noexcept { DBGOUT(PCORO(cont->ContPtr()) << " schedule to delete"); ToDelete_.PushBack(cont); } inline void ScheduleExecution(TContRep* cont) noexcept { DBGOUT(PCORO(cont->ContPtr()) << " schedule execution"); cont->ContPtr()->Scheduled_ = true; ReadyNext_.PushBack(cont); } inline void Activate(TContRep* cont) noexcept { DBGOUT("scheduler: activate " << PCORO(cont->ContPtr())); Current_ = cont; TCont* contPtr = cont->ContPtr(); contPtr->Scheduled_ = false; DBGOUT("scheduler: switch to " << PCORO(cont->ContPtr())); SchedContext_.SwitchTo(contPtr->Context()); } inline void DeleteScheduled() noexcept { TReleaseAll functor; ToDelete_.ForEach(functor); } void WaitForIO(); TInstant PeekForIO(); void PollForIO(TInstant next); void ProcessEvents(size_t evCnt); private: TContList ToDelete_; TContList Ready_; TContList ReadyNext_; TEventWaitQueue WaitQueue_; TContPoller Poller_; THolder<TContRepPool> MyPool_; TContRepPool& Pool_; TExceptionSafeContext SchedContext_; TContRep* Current_; typedef TContPoller::TEvents TEvents; TEvents Events_; bool FailOnError_; }; template <class T> inline int ExecuteEvent(T* event) noexcept { TCont* c = event->Cont(); if (c->Cancelled()) { return ECANCELED; } /* * schedule wait */ c->Executor()->ScheduleIoWait(event); /* * go to scheduler */ c->SwitchToScheduler(); /* * wait complete */ if (c->Cancelled()) { return ECANCELED; } return event->Status(); } inline void TFdEvent::RemoveFromIOWait() noexcept { Cont()->Executor()->Poller()->Remove(this); } inline void TContPollEvent::Wake() noexcept { UnLink(); Cont()->ReSchedule(); } inline void TCont::Exit() { Executor()->Exit(Rep()); } inline bool TCont::IAmRunning() const noexcept { return Rep() == Executor()->Running(); } inline void TCont::Cancel() noexcept { if (Cancelled()) { return; } DBGOUT(PCORO(this) << " do cancel"); Cancelled_ = true; if (!IAmRunning()) { DBGOUT(PCORO(this) << " do cancel from " << PCORO(Executor()->Running()->ContPtr())); ReSchedule(); } } inline void TCont::ReSchedule() noexcept { DBGOUT(PCORO(this) << " reschedule"); Executor()->ScheduleExecution(Rep()); } inline void TCont::SwitchToScheduler() noexcept { DBGOUT(PCORO(this) << " switch to scheduler"); Context()->SwitchTo(Executor()->SchedCont()); } inline void TCont::ReScheduleAndSwitch() noexcept { ReSchedule(); SwitchToScheduler(); } #define EWAKEDUP 34567 #include "events.h" #include "mutex.h" #include "condvar.h" #include "sockpool.h" #if !defined(FROM_IMPL_CPP) #undef DBGOUT #endif #ifdef _MSC_VER #pragma warning(pop) #endif template <typename F> TContIOStatus TInterruptibleEvent::Wait(F&& f) { if (Interrupted_) { return TContIOStatus(0, EWAKEDUP); } auto ret = f(Cont_); if (ret.Status() == EINPROGRESS && Interrupted_) { return TContIOStatus(0, EWAKEDUP); } return ret; }
kazeevn/catboost
util/generic/variant_traits.h
<gh_stars>0 #pragma once #include "typetraits.h" #include <util/system/yassert.h> #include <utility> #include <type_traits> template <class... Ts> class TVariant; namespace NVariant { constexpr size_t T_NPOS = -1; template <class T> struct TTypeHolder { using type = T; }; template <class X, class... Ts> constexpr size_t GetIndex() { bool bs[] = { std::is_same<X, Ts>::value... }; int ret = 0; for (auto b : bs) { if (b) { return ret; } ++ret; } return T_NPOS; } template <class X, class... Ts> struct TIndexOf : std::integral_constant<size_t, GetIndex<X, Ts...>()> {}; template <class... Ts> struct TTypeTraits { struct TNoRefs : TConjunction<TNegation<std::is_reference<Ts>>...> {}; struct TNoVoids : TConjunction<TNegation<std::is_same<Ts, void>>...> {}; struct TNoArrays : TConjunction<TNegation<std::is_array<Ts>>...> {}; struct TNotEmpty : std::integral_constant<bool, (sizeof...(Ts) > 0)> {}; }; template <size_t I, class... Ts> struct TTypeByIndex; template <size_t I, class T, class... Ts> struct TTypeByIndex<I, T, Ts...> { using type = typename TTypeByIndex<I - 1, Ts...>::type; }; template <class T, class... Ts> struct TTypeByIndex<0, T, Ts...> { using type = T; }; template <class FRef, class VRef, size_t I = 0> using TReturnType = decltype(std::declval<FRef>()(std::declval<VRef>().template Get<I>())); template <class FRef, class VRef, size_t... Is> constexpr bool CheckReturnTypes(std::index_sequence<Is...>) { using R = TReturnType<FRef, VRef>; bool tests[] = { std::is_same<R, TReturnType<FRef, VRef, Is>>::value... }; for (auto b : tests) { if (!b) { return false; } } return true; } template <class ReturnType, class T, class FRef, class VRef> ReturnType VisitImplImpl(FRef f, VRef v) { return std::forward<FRef>(f)(std::forward<VRef>(v).template Get<T>()); } template <class F, class V, class... Ts> decltype(auto) VisitImpl(F&& f, V&& v, TTypeHolder<TVariant<Ts...>>) { using FRef = decltype(std::forward<F>(f)); using VRef = decltype(std::forward<V>(v)); using ReturnType = TReturnType<FRef, VRef>; using LambdaType = ReturnType (*)(FRef, VRef); static constexpr LambdaType handlers[] = { VisitImplImpl<ReturnType, Ts, FRef, VRef>... }; return handlers[v.Index()](std::forward<F>(f), std::forward<V>(v)); } template <class F, class V> void VisitWrapForVoid(F&& f, V&& v, std::true_type) { // We need to make special wrapper when return type equals void auto l = [&](auto&& x) { std::forward<F>(f)(std::forward<decltype(x)>(x)); return 0; }; VisitImpl(l, std::forward<V>(v), TTypeHolder<std::decay_t<V>>{}); } template <class F, class V> decltype(auto) VisitWrapForVoid(F&& f, V&& v, std::false_type) { return VisitImpl( std::forward<F>(f), std::forward<V>(v), TTypeHolder<std::decay_t<V>>{}); } }
kazeevn/catboost
catboost/libs/data/doc_pool_data_provider.h
<reponame>kazeevn/catboost #pragma once #include "async_row_processor.h" #include "load_data.h" #include <catboost/libs/data_util/line_data_reader.h> #include <catboost/libs/data_util/path_with_scheme.h> #include <catboost/libs/helpers/mem_usage.h> #include <catboost/libs/options/load_options.h> #include <library/object_factory/object_factory.h> #include <library/threading/local_executor/local_executor.h> #include <util/generic/string.h> #include <util/generic/vector.h> namespace NCB { // pass this struct to to IDocPoolDataProvider ctor struct TDocPoolDataProviderArgs { TPathWithScheme PoolPath; TPathWithScheme PairsFilePath; NCatboostOptions::TDsvPoolFormatParams DsvPoolFormatParams; TVector<int> IgnoredFeatures; TVector<TString> ClassNames; ui32 BlockSize; NPar::TLocalExecutor* LocalExecutor; }; struct IDocPoolDataProvider { // Process all data virtual void Do(IPoolBuilder* poolBuilder) = 0; // Process next block of docs and build sub-pool from it // returns true if any rows were processed virtual bool DoBlock(IPoolBuilder* poolBuilder) = 0; virtual ~IDocPoolDataProvider() = default; }; using TDocDataProviderObjectFactory = NObjectFactory::TParametrizedObjectFactory<IDocPoolDataProvider, TString, TDocPoolDataProviderArgs>; /////////////////////////////////////////////////////////////////////////// // Implementations TVector<TPair> ReadPairs(const TPathWithScheme& filePath, int docCount); void WeightPairs(TConstArrayRef<float> groupWeight, TVector<TPair>* pairs); class TTargetConverter { public: static constexpr float UNDEFINED_CLASS = -1; explicit TTargetConverter(const TVector<TString>& classNames); float operator()(const TString& word) const; private: TVector<TString> ClassNames; }; /* * Some common functionality for DocPoolDataProvider classes than utilize async row processing. * Args, FeatureIds and PoolMetaInfo are provided as commonly needed * (but not related to async processing) * * Derived classes must implement GetDocDount, StartBuilder and ProcessBlock * (and might redefine FinalizeBuilder, but common implementation is provided) * and then implement IDocPoolDataProvider like this: * * > void Do(IPoolBuilder* poolBuilder) override { * > TBase::Do(GetReadFunc(), poolBuilder); * > } * > * > bool DoBlock(IPoolBuilder* poolBuilder) override { * > return TBase::DoBlock(GetReadFunc(), poolBuilder); * > } */ template <class TData> class TAsyncProcDataProviderBase { public: explicit TAsyncProcDataProviderBase(TDocPoolDataProviderArgs&& args) : Args(std::move(args)) , AsyncRowProcessor(Args.LocalExecutor, Args.BlockSize) {} protected: template <class TReadDataFunc> void Do(TReadDataFunc readFunc, IPoolBuilder* poolBuilder) { StartBuilder(false, GetDocCount(), 0, poolBuilder); while (AsyncRowProcessor.ReadBlock(readFunc)) { ProcessBlock(poolBuilder); } FinalizeBuilder(false, poolBuilder); } template <class TReadDataFunc> bool DoBlock(TReadDataFunc readFunc, IPoolBuilder* poolBuilder) { CB_ENSURE(!Args.PairsFilePath.Inited(), "TAsyncProcDataProviderBase::DoBlock does not support pairs data"); if (!AsyncRowProcessor.ReadBlock(readFunc)) return false; StartBuilder(true, AsyncRowProcessor.GetParseBufferSize(), AsyncRowProcessor.GetLinesProcessed(), poolBuilder); ProcessBlock(poolBuilder); FinalizeBuilder(true, poolBuilder); return true; } virtual int GetDocCount() = 0; virtual void StartBuilder(bool inBlock, int docCount, int offset, IPoolBuilder* poolBuilder) = 0; virtual void ProcessBlock(IPoolBuilder* poolBuilder) = 0; virtual void FinalizeBuilder(bool inBlock, IPoolBuilder* poolBuilder) { if (!inBlock) { DumpMemUsage("After data read"); if (Args.PairsFilePath.Inited()) { TVector<TPair> pairs = ReadPairs(Args.PairsFilePath, poolBuilder->GetDocCount()); if (PoolMetaInfo.HasGroupWeight) { WeightPairs(poolBuilder->GetWeight(), &pairs); } poolBuilder->SetPairs(pairs); } } poolBuilder->Finish(); } virtual ~TAsyncProcDataProviderBase() = default; protected: TDocPoolDataProviderArgs Args; NCB::TAsyncRowProcessor<TData> AsyncRowProcessor; TVector<TString> FeatureIds; TPoolMetaInfo PoolMetaInfo; }; // expose the declaration to allow to derive from it in other modules class TCBDsvDataProvider : public IDocPoolDataProvider , protected TAsyncProcDataProviderBase<TString> { public: using TBase = TAsyncProcDataProviderBase<TString>; protected: decltype(auto) GetReadFunc() { return [this](TString* line) -> bool { return LineDataReader->ReadLine(line); }; } public: explicit TCBDsvDataProvider(TDocPoolDataProviderArgs&& args); void Do(IPoolBuilder* poolBuilder) override { TBase::Do(GetReadFunc(), poolBuilder); } bool DoBlock(IPoolBuilder* poolBuilder) override { return TBase::DoBlock(GetReadFunc(), poolBuilder); } TVector<TColumn> CreateColumnsDescription(ui32 columnsCount); // call after ColumnDescription initialization void InitFeatureIds(const TMaybe<TString>& header); int GetDocCount() override { return (int)LineDataReader->GetDataLineCount(); } void StartBuilder(bool inBlock, int docCount, int offset, IPoolBuilder* poolBuilder) override; void ProcessBlock(IPoolBuilder* poolBuilder) override; protected: TVector<bool> FeatureIgnored; // init in process char FieldDelimiter; TTargetConverter ConvertTarget; THolder<NCB::ILineDataReader> LineDataReader; TVector<int> CatFeatures; }; bool IsNanValue(const TStringBuf& s); }
kazeevn/catboost
catboost/libs/algo/features_layout.h
#pragma once #include <catboost/libs/options/enums.h> #include <catboost/libs/model/features.h> #include <util/generic/vector.h> #include <util/generic/string.h> #include <util/system/yassert.h> class TFeaturesLayout { public: TFeaturesLayout(const int featureCount, std::vector<int> catFeatureIndices, const TVector<TString>& featureId); TFeaturesLayout(const TVector<TFloatFeature>& floatFeatures, const TVector<TCatFeature>& catFeatures); TString GetExternalFeatureDescription(int internalFeatureIdx, EFeatureType type) const { if (ExternalIdxToFeatureId.empty()) { return TString(); } else { int externalFeatureIdx = GetExternalFeatureIdx(internalFeatureIdx, type); return ExternalIdxToFeatureId[externalFeatureIdx]; } } const TVector<TString>& GetExternalFeatureIds() const { return ExternalIdxToFeatureId; } int GetExternalFeatureIdx(int internalFeatureIdx, EFeatureType type) const { if (type == EFeatureType::Float) { return FloatFeatureInternalIdxToExternalIdx[internalFeatureIdx]; } else { return CatFeatureInternalIdxToExternalIdx[internalFeatureIdx]; } } int GetInternalFeatureIdx(int externalFeatureIdx) const { Y_ASSERT(IsCorrectExternalFeatureIdx(externalFeatureIdx)); return FeatureExternalIdxToInternalIdx[externalFeatureIdx]; } EFeatureType GetExternalFeatureType(int externalFeatureIdx) const { Y_ASSERT(IsCorrectExternalFeatureIdx(externalFeatureIdx)); return ExternalIdxToFeatureType[externalFeatureIdx]; } bool IsCorrectExternalFeatureIdx(int externalFeatureIdx) const { return externalFeatureIdx >= 0 && externalFeatureIdx < ExternalIdxToFeatureType.ysize(); } int GetCatFeatureCount() const { return CatFeatureInternalIdxToExternalIdx.ysize(); } int GetExternalFeatureCount() const { return ExternalIdxToFeatureType.ysize(); } private: void InitIndices(const int featureCount, std::vector<int> catFeatureIndices); private: TVector<EFeatureType> ExternalIdxToFeatureType; TVector<int> FeatureExternalIdxToInternalIdx; TVector<int> CatFeatureInternalIdxToExternalIdx; TVector<int> FloatFeatureInternalIdxToExternalIdx; TVector<TString> ExternalIdxToFeatureId; };
kazeevn/catboost
catboost/python-package/catboost/helpers.h
<reponame>kazeevn/catboost #pragma once #include <catboost/libs/algo/plot.h> #include <util/generic/noncopyable.h> #include <Python.h> class TGilGuard : public TNonCopyable { public: TGilGuard() : State_(PyGILState_Ensure()) { } ~TGilGuard() { PyGILState_Release(State_); } private: PyGILState_STATE State_; }; void ProcessException(); void SetPythonInterruptHandler(); void ResetPythonInterruptHandler(); TVector<TVector<double>> EvalMetrics( const TFullModel& model, const TPool& pool, const TVector<TString>& metricsDescription, int begin, int end, int evalPeriod, int threadCount, const TString& resultDir, const TString& tmpDir ); TVector<TString> GetMetricNames(const TFullModel& model, const TVector<TString>& metricsDescription); TVector<double> EvalMetricsForUtils( const TVector<float>& label, const TVector<TVector<double>>& approx, const TString& metricName, const TVector<float>& weight, const TVector<int>& groupIdParam, int threadCount ); class TMetricsPlotCalcerPythonWrapper { public: TMetricsPlotCalcerPythonWrapper(const TVector<TString>& metricDescriptions, const TFullModel& model, int begin, int end, int evalPeriod, int threadCount, const TString& tmpDir, bool deleteTempDirOnExit = false) : Metrics(CreateMetricsFromDescription(metricDescriptions, model.ObliviousTrees.ApproxDimension)) , MetricPlotCalcer(CreateMetricCalcer( model, begin, end, evalPeriod, /*processedIterationsStep=*/-1, Executor, tmpDir, Metrics)) { Executor.RunAdditionalThreads(threadCount - 1); MetricPlotCalcer.SetDeleteTmpDirOnExit(deleteTempDirOnExit); } ~TMetricsPlotCalcerPythonWrapper() { MetricPlotCalcer.ClearTempFiles(); } void AddPool(const TPool& pool) { if (MetricPlotCalcer.HasAdditiveMetric()) { MetricPlotCalcer.ProceedDataSetForAdditiveMetrics(pool, /*isProcessBoundaryGroups=*/false); } if (MetricPlotCalcer.HasNonAdditiveMetric()) { MetricPlotCalcer.ProceedDataSetForNonAdditiveMetrics(pool); } } TVector<const IMetric*> GetMetricRawPtrs() const { TVector<const IMetric*> ptrs; for (const auto& metric : Metrics) { ptrs.push_back(metric.Get()); } return ptrs; } TVector<TVector<double>> ComputeScores() { if (MetricPlotCalcer.HasAdditiveMetric()) { MetricPlotCalcer.FinishProceedDataSetForAdditiveMetrics(); } if (MetricPlotCalcer.HasNonAdditiveMetric()) { MetricPlotCalcer.FinishProceedDataSetForNonAdditiveMetrics(); } return MetricPlotCalcer.GetMetricsScore(); } private: NPar::TLocalExecutor Executor; TVector<THolder<IMetric>> Metrics; TMetricsPlotCalcer MetricPlotCalcer; };
kazeevn/catboost
catboost/libs/quantization_schema/schema.h
#pragma once #include <catboost/libs/options/enums.h> #include <util/generic/vector.h> #include <util/generic/string.h> namespace NCB { // TODO(yazevnul): replace `NCatboostCuda::TBinarizedFloatFeaturesMetaInfo` with this struct struct TPoolQuantizationSchema { TVector<size_t> TrueFeatureIndices; // Each element is sorted (asc.) and each value is unique. TVector<TVector<float>> Borders; // TODO(yazevnul): maybe rename `ENanMode` to `ENanPolicy`? TVector<ENanMode> NanModes; // List of class names; Makes sence only for multiclassification. // // NOTE: order is important TVector<TString> ClassNames; }; }
kazeevn/catboost
catboost/cuda/cuda_lib/cuda_events_provider.h
<filename>catboost/cuda/cuda_lib/cuda_events_provider.h<gh_stars>0 #pragma once #include "cuda_base.h" #include <util/system/spinlock.h> #include <util/generic/vector.h> namespace NCudaLib { class TCudaEventsProvider { private: TVector<cudaEvent_t> FreeHandles; TVector<cudaEvent_t> FreeHandlesWithoutTiming; static const ui64 RequestHandlesBatchSize = 16; TSpinLock Lock; void RequestHandle(bool disableTimming = true); public: class TCudaEvent: private TNonCopyable { private: mutable cudaEvent_t Event; bool IsWithoutTiming; TCudaEventsProvider* Owner; public: TCudaEvent(cudaEvent_t event, bool isWithoutTiming, TCudaEventsProvider* owner) : Event(event) , IsWithoutTiming(isWithoutTiming) , Owner(owner) { } ~TCudaEvent() { TGuard<TSpinLock> lock(Owner->Lock); if (IsWithoutTiming) { Owner->FreeHandlesWithoutTiming.push_back(Event); } else { Owner->FreeHandles.push_back(Event); } } void Record(const TCudaStream& stream) const { CUDA_SAFE_CALL(cudaEventRecord(Event, stream.GetStream())); } void StreamWait(const TCudaStream& stream) const { CUDA_SAFE_CALL(cudaStreamWaitEvent(stream.GetStream(), Event, 0)); } void WaitComplete() const { CUDA_SAFE_CALL(cudaEventSynchronize(Event)); } bool IsComplete() const { cudaError_t errorCode = cudaEventQuery(Event); if (errorCode == cudaSuccess) { return true; } if (errorCode != cudaErrorNotReady) { ythrow TCatboostException() << "CUDA error: " << cudaGetErrorString(errorCode) << " " << (int)errorCode; } return false; } }; public: using TCudaEventPtr = THolder<TCudaEvent>; ~TCudaEventsProvider() throw (TCatboostException) { for (auto event : FreeHandles) { CUDA_SAFE_CALL(cudaEventDestroy(event)); } for (auto event : FreeHandlesWithoutTiming) { CUDA_SAFE_CALL(cudaEventDestroy(event)); } } TCudaEventPtr Create(bool disableTimming = true); }; using TCudaEvent = TCudaEventsProvider::TCudaEvent; using TCudaEventPtr = TCudaEventsProvider::TCudaEventPtr; inline static TCudaEventsProvider& CudaEventProvider() { return *FastTlsSingleton<TCudaEventsProvider>(); } inline TCudaEventPtr CreateCudaEvent(bool disableTimming = true) { return CudaEventProvider().Create(disableTimming); } }
PaerrePampula/SmartCan_sensor
ScreenControl.h
#include "Adafruit_GFX.h" #include "Adafruit_SSD1331.h" // Define colors #define Black 0x0000 #define Blue 0x001F #define Red 0xF800 #define Green 0x07E0 #define Cyan 0x07FF #define Magenta 0xF81F #define Yellow 0xFFE0 #define White 0xFFFF class ScreenControl { public: ScreenControl(Adafruit_SSD1331 &screen); void notifyInitialCalibration(int initialDepth); void notifyNewCalculation(int newCalculation); private: Adafruit_SSD1331 *OLED; void init(); void updateScreen(); };
PaerrePampula/SmartCan_sensor
MQTTNetworkingControl.h
#include <MQTTClientMbedOs.h> #include "ESP8266Interface.h" #include "ntp-client/NTPClient.h" #define ntpAddress "time.mikes.fi" // The VTT Mikes in Helsinki #define ntpPort 123 // Typically 123 for every NTP server class MQTTNetworkingControl { public: MQTTNetworkingControl(ESP8266Interface& espInterface); void createAndSendMQTTMessage(int depthDifference); private: void init(); void initNetwork(); void initNTP(); //Fields ESP8266Interface &esp; // Store device IP SocketAddress deviceIP; // Store broker IP SocketAddress MQTTBroker; TCPSocket socket; MQTTClient client; NTPClient ntp; };
PaerrePampula/SmartCan_sensor
DistanceSensor.h
<reponame>PaerrePampula/SmartCan_sensor /*A distance sensor, that is using sonar to measure distances. The recommended and the originally used component is HC-SR04. Maximum possible distance measured : 400cm The connections are: Connect VCC to a 5v power supply, do not use 3.3V! Its not enough for the sensor, and it only gives almost nonexistent results or nothing at all! Connect Ground to Ground. Connect ECHO and TRIGGER to any available digital pin on the MCU eg. D9 and D10. */ class DistanceSensor { public: /** Constructed with required pins.. * @param echoP the pin, where the echo is connected (Output to MCU) * @param triggerP the pin, where the trigger is connected (Input from MCU) */ DistanceSensor(PinName echoP, PinName triggerP); void startMeasuring(); float getDistanceInCm(); private: InterruptIn echo; DigitalOut trigger; Timer timer; float calculatedDistance; Timeout triggerTimeout, echoTimeout; float minClamp = 2; //The minimum distance possible float maxClamp = 400; //The max distance possible, the highest correctly measured distance. void initializeSensor(); void stopTrigger(); void stopTimerAndMeasure(); void startTimer(); };
FelixYin66/CocoapodsDemo
TestCocoapodsProject/Example/TestCocoapodsProject/FYViewController.h
// // FYViewController.h // TestCocoapodsProject // // Created by <NAME> on 04/01/2017. // Copyright (c) 2017 <NAME>. All rights reserved. // @import UIKit; @interface FYViewController : UIViewController @end
FelixYin66/CocoapodsDemo
TestCocoapodsProject/Example/Pods/Target Support Files/TestCocoapodsProject/TestCocoapodsProject-umbrella.h
<filename>TestCocoapodsProject/Example/Pods/Target Support Files/TestCocoapodsProject/TestCocoapodsProject-umbrella.h #ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double TestCocoapodsProjectVersionNumber; FOUNDATION_EXPORT const unsigned char TestCocoapodsProjectVersionString[];
FelixYin66/CocoapodsDemo
TestCocoapodsProject/Example/Pods/Target Support Files/Pods-TestCocoapodsProject_Example/Pods-TestCocoapodsProject_Example-umbrella.h
<reponame>FelixYin66/CocoapodsDemo #ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_TestCocoapodsProject_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_TestCocoapodsProject_ExampleVersionString[];
FelixYin66/CocoapodsDemo
TestCocoapodsProject/Example/TestCocoapodsProject/CocoapodsTest/FYCocoapodsViewController.h
<gh_stars>0 // // FYCocoapodsViewController.h // TestCocoapodsProject // // Created by <NAME> on 2017/4/1. // Copyright © 2017年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface FYCocoapodsViewController : UIViewController @end
FelixYin66/CocoapodsDemo
TestCocoapodsProject/Example/Pods/Target Support Files/Pods-TestCocoapodsProject_Tests/Pods-TestCocoapodsProject_Tests-umbrella.h
<gh_stars>0 #ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_TestCocoapodsProject_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_TestCocoapodsProject_TestsVersionString[];
FelixYin66/CocoapodsDemo
TestCocoapodsProject/Example/TestCocoapodsProject/FYAppDelegate.h
// // FYAppDelegate.h // TestCocoapodsProject // // Created by <NAME> on 04/01/2017. // Copyright (c) 2017 <NAME>. All rights reserved. // @import UIKit; @interface FYAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
MoSights/Cleaner
thirdparty/OptParse/optparse.h
<gh_stars>1-10 // // Copyright (c) 2006 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #ifndef __OPTION_PARSER_H #define __OPTION_PARSER_H #include <vector> #include <map> #include <string> enum HANDLE_STATE { STATE_NORMAL, STATE_ESCAPE, STATE_QUOTED, STATE_DELIMITER }; #ifdef _UNICODE typedef std::wstring String; typedef wchar_t TCHAR; #define IS_ALPHA(x) iswalpha(x) #else typedef std::string String; typedef char TCHAR; #define IS_ALPHA(x) isalpha(x) #endif #ifndef _T #ifdef _UNICODE #define _T(x) L##x #else #define _T(x) x #endif #endif // // OptParser's error codes // #define E_OK 0 ///< Success #define E_ERROR 1 ///< Generic error #define E_OPT_UNKNOWN 2 ///< Unknown switch/option #define E_OPT_MISSING 4 ///< Mandatory option was missing #define E_OPT_DUPLICATE 8 ///< Duplicate option (when adding an option) #define E_ARG_EXPECTED 16 ///< Expected argument missing #define E_ARG_INVALID 32 ///< Argument was not validated #define E_INVALID 64 ///< Invalid parameter given to function #define E_OPT_TMO 128 ///< Too many occurences of this switch #define CB_OPT_UNKNOWN 1 ///< An unknown switch has been found on the commandline #define CB_OPT_MALFORMED 2 ///< Malformed option: either it has an argument that wasn't expected #define CB_OPT_MISSING 3 ///< A required option was missing #define CB_ARG_MISSING 4 ///< Argument missing #define CB_ARG_INVALID 5 ///< Argument is invalid (has validator, not validated) #define CB_OPT_TMO 6 ///< Too many occurences of this switch // // Flags for addOption. Can be OR'ed together. // #define OPT_NONE 0 ///< This option has no flags #define OPT_REQUIRED 1 ///< Option required for the command line to be valid #define OPT_NEEDARG 2 ///< Option needs an argument #define OPT_MULTI 4 ///< Switch can appear multiple times (not compatible with NEEDARG) #define OPT_HELP 8 ///< This is the help switch, will invoke help callback for every defined option // // Flags for the parser // #define OPT_PARSE_INCLUDE_ARGV0 1 ///< Include argv[0] in the list of free args #define OPT_PARSE_QUOTED_ARGS 2 ///< Allow quoted args like --s="asd asd" and "asd asd" #define OPT_PARSE_UNQUOTE_ARGS 4 ///< Unquote quoted args "asd asd" --> asd asd -- must be set with the previous flag // NOT IMPLEMENTED YET #define OPT_PARSE_AUTO_VERSION 16 ///< Automatically generate -v and --version #define OPT_PARSE_AUTO_HELP 32 ///< Automatically generate -h and --help /** * @brief Options class, stores all options and helps parsing. */ class Options { friend class Parser; public: //! Callback used to impose constraints on options typedef bool (*option_validator)(const String&); typedef int (*generic_callback)(int, const String&); ///< Generic callback type typedef int (*help_callback)(const String&, const String&, const String&, int); Options(); ~Options(); /** * @param p_short String describing the short form of this option, e.g "-s" * @param p_long String describing the long form of this option, e.g. "--start" * @param p_help Documentation for this parameter, e.g. "Start the server" * @param p_flags Flags for this option * @param p_validator Callback used to validate the value of the argument (NULL if no validation required or no argument for this opt) * @return E_ERROR when there was a failure allocating memory * @return E_INVALID if both option strings are empty or the option was given a validator even if not needed * @return E_OPT_DUPLICATE if there was another option by this name * @return E_OK if everything went ok */ int addOption(const String& p_short, const String& p_long, const String& p_help, int p_flags, option_validator p_validator); /** * @param p_opt String containing the option whose argument is to be retrieved * @return Argument given on the commandline to the requested option * @return Empty string in case the option is invalid or missing or no argument was found */ String asString(const String& p_opt); /** * Example: bool b = isOptionSet("-s"); * @param p_opt String containing the option to look for. * @return true If the option was specified on the command line * @return false Otherwise */ bool isSet(const String& p_opt); /** * Sets callback for invalid command line options encountered * @param p_callback Pointer to function to call on invalid opts */ void setErrorCallback( generic_callback p_callback ); /** * Sets callback for help generation (invoked when encountered) -h or --help. * If not set, default will be used * @param p_callback Pointer to function to call on help generation. */ void setHelpCallback( help_callback p_callback ); /** * Reset the options object */ void reset(); #ifdef _DEBUG void dump_options(); #endif private: //////////////////////////////////////////////////////////////////// // Variables and Data Structures //////////////////////////////////////////////////////////////////// //! Internal structure for keeping option settings struct _option { _option(const String& p_short, const String& p_long, const String& p_help, int p_flags, option_validator p_option) : m_count(0) , m_flags(p_flags) , m_validArg(true) , m_help(p_help) , m_shortName(p_short) , m_longName(p_long) , m_optionValidator(p_option) { // // We don't want to throw an exception, but set m_optionValidator // to NULL if the option doesn't require an argument. // if (!(m_flags & OPT_REQUIRED)) { m_optionValidator = NULL; } } int m_count; ///< How many times this has been found // // Internal flags // int m_validArg; ///< Option's argument is valid int m_flags; ///< Flags for this option String m_arg; ///< Matched arg String m_help; ///< Help description for this option String m_shortName; ///< Short option name String m_longName; ///< Long option name option_validator m_optionValidator; ///< Callback for validating options }; typedef std::map<String, _option*> OptionMap; // // Map for short options (one dash) -- for fast searching, instead of linear in a vector // OptionMap m_shortOpts; // // Map for long options (two dashes) -- for fast searching, instead of linear in a vector // OptionMap m_longOpts; // // Vector to keep all the options in order. Needed for help generation and resource de-allocation. // std::vector<_option*> m_orderedOpts; // // Pointer to the _option structure who's argument should be next on // the commandline. // _option* m_waitingArg; // // Vector for free arguments // std::vector<String> m_freeArgs; // // Callbacks // generic_callback m_errorCallback; // Invalid argument help_callback m_helpCallback; // Called when encountering -h or --help //////////////////////////////////////////////////////////////////// // Functions //////////////////////////////////////////////////////////////////// static int _defaultHelpCallback(const String&, const String&, const String&, int flags); /** * This is called when a OPT_HELP type option is encountered */ int _generateHelp(); //! Returns an error code reflecting the state of the option parser int _validateState(); /** * Internal helper function. Give it the a short option (e.g. "-s") * from the commandline and it will properly set flags inside the * structures. * * @param p_opt Option from the commandline * @return E_OK if the handling was ok * @return E_ERROR if the string was empty * @return E_OPT_UNKNOWN if the given option was not known */ int _handleShortOption(const String& p_opt); /** * Internal helper function. Give it the a long option (e.g. "--start") * from the commandline and it will properly set flags inside the * structures. * * @param p_opt Option from the commandline * @return E_OK if the handling was ok * @return E_OPT_UNKNOWN if the given option was not known * @return E_ERROR if the option was empty or invalid somehow (e.g. "--=asd" or argument given if not expected) * @return E_ARG_EXPECTED if the option needs an argument and none given (e.g --start instead of --start=now) */ int _handleLongOption(const String& p_opt); /** * Internal helper function. Called by the Parser class for each argument on the * command line. * * @param p_arg Argument from the commandline * @warning Can return bitmask! * @return E_OK if the handling was ok * @return E_OPT_UNKNOWN if the given option was not known * @return E_ERROR if the option was empty or invalid somehow (e.g. "--=asd" or argument given if not expected) * @return E_ARG_EXPECTED if the option needs an argument and none given (e.g --start instead of --start=now) */ int _processArg(const String& p_arg); /** * Returns true if the string is a valid short option, in the current options context */ bool _validShortOpt(const String& p_arg); /** * Returns true if the string is a valid long option, in the current options context */ bool _validLongOpt(const String& p_arg); /** * Inserts an option into one of the maps while checking for duplicates. * @param p_map The map to insert option into * @param p_name The name of the option * @param p_optPtr Pointer to the option structure to be inserted * @return E_OPT_DUPLICATE if there is another entry with this name in the map * @return E_OK if everything went ok */ int _insertOption(OptionMap& p_map, const String& p_name, _option* p_optPtr); _option* _getOptionByName(const String& p_opt, const OptionMap& p_map) const { OptionMap::const_iterator it = p_map.find(p_opt); return ( it != p_map.end() ) ? it->second : NULL; } _option* _getShortOptionByname(const String& p_opt) const { return _getOptionByName(p_opt, m_shortOpts); } _option* _getLongOptionByname(const String& p_opt) const { return _getOptionByName(p_opt, m_longOpts); } _option* _getOptionByName(const String& p_opt) const { if ( p_opt.size() == 2 && p_opt[0] == _T('-') ) { return _getShortOptionByname(p_opt); } else if ( p_opt.size() >= 3 && p_opt.find( _T("--"),0,2) == 0 ) { return _getLongOptionByname(p_opt); } //TODO: Error callback because of invalid option ? return NULL; } }; /** * @brief Parser class */ class Parser { public: Parser(); ~Parser(); /** * Parse command line arguments given in the classical form of (argc, argv). * @param p_argc Number of arguments including program name (argv[0]) * @param p_argv Array of TCHAR* containing the arguments * @param p_opts Options class containing the expected options * @warning Can return bitmasked answer! * @return E_OK if the parsing was successfull and all required options and args were ok * @return E_OPT_UNKNOWN if the given option was not known * @return E_ERROR if the option was empty or invalid somehow (e.g. "--=asd" or argument given if not expected) * @return E_ARG_EXPECTED if the option needs an argument and none given (e.g --start instead of --start=now) * @return E_ARG_INVALID if one of the options with argument validators wasn't validated :) * */ int parse(int p_argc, TCHAR** p_argv, Options& p_opts); /** * Parse command line arguments given in the windows GetCommandLine() form. * @param p_cmdLine Commandline string * @param p_opts Options class containing the expected options * @warning Can return bitmasked answer! * @return E_OK if the parsing was successfull and all required options and args were ok * @return E_OPT_UNKNOWN if the given option was not known * @return E_ERROR if the option was empty or invalid somehow (e.g. "--=asd" or argument given if not expected) * @return E_ARG_EXPECTED if the option needs an argument and none given (e.g --start instead of --start=now) * @return E_ARG_INVALID if one of the options with argument validators wasn't validated :) */ int parse(const TCHAR* p_cmdLine, Options& p_opts); /** * Sets flags for the parser */ void setFlags(int p_flags); private: // Internal methods used to parse windows style command line int _state_handle_space(String& p_opt, TCHAR c, int& current_state, Options& p_opts); int _state_handle_quote(String& p_opt, TCHAR c, int& current_state); int _state_handle_escape(String& p_opt, TCHAR c, int& current_state); int _state_handle_other(String& p_opt, TCHAR c, int& current_state); int pre_parse(Options&); private: // Variables int m_flags; }; #endif
MoSights/Cleaner
common/str.h
#pragma once unsigned int a2w(const char * astr, wchar_t *wstr); unsigned int w2a(const wchar_t *wstr, char *astr); unsigned int a2u8(const char *astr, char *utf8); unsigned int u82a(const char *utf8, char *astr); unsigned int u2u8(const wchar_t *wstr, char *utf8); unsigned int u82u(const char *utf8, wchar_t *wstr);
MoSights/Cleaner
thirdparty/SlimXml/SlimXml.h
#ifndef __SLIM_XML_H__ #define __SLIM_XML_H__ #include <string> #include <list> #include <istream> #pragma warning(push) #pragma warning(disable:4251) //disable this to make parsing a little bit faster //#define SLIM_TRANSFER_CHARACTER #if defined(SLIMLIB_EXPORTS) #if defined(_MSC_VER) //#define SLIMLIB_API __declspec(dllexport) #define SLIMLIB_API #else #define SLIMLIB_API #endif #else #if defined(_MSC_VER) //#define SLIMLIB_API __declspec(dllimport) #define SLIMLIB_API #else #define SLIMLIB_API #endif #endif namespace slim { #undef SLIM_USE_WCHAR #if defined (_MSC_VER) && defined (UNICODE) #define SLIM_USE_WCHAR #endif enum Encode { ANSI = 0, UTF_8, UTF_8_NO_MARK, UTF_16, UTF_16_BIG_ENDIAN, #if defined (SLIM_USE_WCHAR) || defined (__GNUC__) DefaultEncode = UTF_8 #else DefaultEncode = ANSI #endif }; #ifdef SLIM_USE_WCHAR typedef wchar_t Char; #define T(str) L##str #define StrToI _wtoi #define StrToF _wtof #define Sprintf swprintf #define Sscanf swscanf #define Strlen wcslen #define Strcmp wcscmp #define Stricmp _wcsicmp #define Strncmp wcsncmp #define Memchr wmemchr #define Strcpy wcscpy #else typedef char Char; #define T(str) str #define StrToI atoi #define StrToF atof #if defined (__GNUC__) #define Sprintf snprintf #elif defined (_MSC_VER) #define Sprintf sprintf_s #endif #define Sscanf sscanf #define Strlen strlen #define Strcmp strcmp #define Stricmp _stricmp #define Strncmp strncmp #define Memchr memchr #define Strcpy strcpy #endif class XmlAttribute; class XmlNode; typedef std::basic_string<Char> String; typedef std::list<XmlAttribute*> AttributeList; typedef std::list<XmlNode*> NodeList; typedef SLIMLIB_API AttributeList::const_iterator AttributeIterator; typedef SLIMLIB_API NodeList::const_iterator NodeIterator; enum NodeType { DOCUMENT = 0, ELEMENT, COMMENT, DECLARATION }; /////////////////////////////////////////////////////////////////////////////////////////////////// class SLIMLIB_API XmlBase { friend class XmlDocument; public: XmlBase(); ~XmlBase(); const Char* getName() const; void setName(const Char* name); const Char* getString() const; bool getBool() const; int getInt() const; unsigned long getHex() const; float getFloat() const; double getDouble() const; void setString(const Char* value); void setString(const String& value); void setBool(bool value); void setInt(int value); void setHex(unsigned long value); void setFloat(float value); void setDouble(double value); private: void assignString(Char* &str, Char* value, size_t length, bool transferCharacter); protected: Char* m_name; Char* m_value; bool m_nameAllocated; bool m_valueAllocated; }; /////////////////////////////////////////////////////////////////////////////////////////////////// class SLIMLIB_API XmlAttribute : public XmlBase { public: XmlAttribute(); ~XmlAttribute(); }; /////////////////////////////////////////////////////////////////////////////////////////////////// class SLIMLIB_API XmlNode : public XmlBase { public: XmlNode(NodeType type, XmlNode* parent); ~XmlNode(); public: NodeType getType() const; bool isEmpty() const; XmlNode* getParent() const; bool hasChild() const; XmlNode* getFirstChild(NodeIterator& iter) const; XmlNode* getNextChild(NodeIterator& iter) const; XmlNode* getChild(NodeIterator iter) const; size_t getChildCount() const; XmlNode* findChild(int index) const; XmlNode* findChild(const Char* name) const; XmlNode* findFirstChild(const Char* name, NodeIterator& iter) const; XmlNode* findNextChild(const Char* name, NodeIterator& iter) const; size_t getChildCount(const Char* name) const; void removeChild(XmlNode* node); void clearChild(); XmlNode* addChild(const Char* name = NULL, NodeType = ELEMENT); XmlNode* addChild(XmlNode* before_node, const Char* child_name, NodeType type = ELEMENT); bool hasAttribute() const; XmlAttribute* findAttribute(const Char* name) const; const Char* readAttributeAsString(const Char* name, const Char* defaultValue = T("")) const; bool readAttributeAsBool(const Char* name, bool defaultValue = false) const; int readAttributeAsInt(const Char* name, int defaultValue = 0) const; void readAttributeAsIntArray(const Char* name, int* out, unsigned long length, int defaultValue = 0) const; unsigned long readAttributeAsHex(const Char* name, unsigned long defaultValue = 0) const; float readAttributeAsFloat(const Char* name, float defaultValue = 0.0f) const; double readAttributeAsDouble(const Char* name, double defaultValue = 0.0) const; unsigned long readAttributeAsEnum(const Char* name, const Char* const* enumNames, unsigned long enumCount, unsigned long defaultValue = 0) const; XmlAttribute* getFirstAttribute(AttributeIterator& iter) const; XmlAttribute* getNextAttribute(AttributeIterator& iter) const; void removeAttribute(XmlAttribute* attribute); void clearAttribute(); XmlAttribute* addAttribute(const Char* name = NULL, const Char* value = NULL); XmlAttribute* addAttribute(const Char* name, bool value); XmlAttribute* addAttribute(const Char* name, int value); XmlAttribute* addAttribute(const Char* name, float value); XmlAttribute* addAttribute(const Char* name, double value); protected: void writeNode(String& output, int depth) const; void writeChildNodes(String& output, int depth) const; void writeTransferredString(String& output, const Char* input) const; private: NodeType m_type; AttributeList m_attributes; XmlNode* m_parent; NodeList m_children; }; /////////////////////////////////////////////////////////////////////////////////////////////////// class SLIMLIB_API XmlDocument : public XmlNode { public: XmlDocument(); ~XmlDocument(); bool loadFromFile(const Char* filename); bool loadFromStream(std::istream& input); bool loadFromMemory(const char* buffer, size_t size); bool save(const Char* filename, Encode encode = DefaultEncode) const; private: bool reallyLoadFromMemory(char* buffer, size_t size, bool copiedMemory); bool parse(Char* input, size_t size); bool findLabel(Char* &begin, size_t size, Char* &label, size_t &labelSize); bool parseLabel(XmlNode* node, Char* label, size_t labelSize); private: char* m_buffer; }; /////////////////////////////////////////////////////////////////////////////////////////////////// size_t utf8toutf16(const char* u8, size_t size, wchar_t* u16, size_t outBufferSize); size_t utf16toutf8(const wchar_t* u16, size_t size, char* u8, size_t outBufferSize); Encode detectEncode(const char* str, size_t size, bool& multiBytes); } #pragma warning(pop) #endif
MoSights/Cleaner
thirdparty/SlimXml/XmlSchema.h
#ifndef __SLIM_XML_SCHEMA_H__ #define __SLIM_XML_SCHEMA_H__ #include "SlimXml.h" namespace slim { class SLIMLIB_API XmlSchema : public XmlDocument { public: //parse schema from xml file bool constructFromXml( XmlDocument* file ); //generate reading/writing c++ code automatically bool generateCode( const Char* filename, const Char* pchFilename = NULL ) const; private: bool parseNodeStruct( XmlNode* dst, XmlNode* src ); const Char* guessType( const Char* content ) const; bool generateCodeForNode( const XmlNode* node, String& headerCode, String& sourceCode ) const; size_t getNodeMemberTypeWidth( const XmlNode* node ) const; void addSimpleMember( const XmlNode* child, String& structure, size_t typeWidth, String& readFunction, String& writeFunction ) const; void addSimpleVector( const XmlNode* child, String& structure, size_t typeWidth, String& readFunction, String& writeFunction ) const; void addStructMember( const XmlNode* child, String& structure, size_t typeWidth, String& readFunction, String& writeFunction ) const; void addStructVector( const XmlNode* child, String& structure, size_t typeWidth, String& readFunction, String& writeFunction ) const; void addConstructorItem( const XmlNode* child, String& structure, int& index ) const; String getSimpleTypeString( const XmlAttribute* type ) const; const Char* getTypeDefaultValue( const Char* type ) const; String getPluralName( const String& name ) const; }; } #endif
aral/XAuthTwitterEngine
XAuthTwitterEngineDemo/Classes/XAuthTwitterEngineDemoViewController.h
<reponame>aral/XAuthTwitterEngine // // XAuthTwitterEngineDemoViewController.h // XAuthTwitterEngineDemo // // Created by <NAME> on 28/02/2010. // Copyright Naklab 2010. All rights reserved. // #import <UIKit/UIKit.h> #import "XAuthTwitterEngineDelegate.h" #import "OAToken.h" #define kOAuthConsumerKey @"" // Replace these with your consumer key #define kOAuthConsumerSecret @"" // and consumer secret from // http://twitter.com/oauth_clients/details/<your app id> #define kCachedXAuthAccessTokenStringKey @"cachedXAuthAccessTokenKey" @class XAuthTwitterEngine; @interface XAuthTwitterEngineDemoViewController : UIViewController <XAuthTwitterEngineDelegate> { IBOutlet UITextField *usernameTextField; IBOutlet UITextField *passwordTextField; IBOutlet UIButton *sendTweetButton; XAuthTwitterEngine *twitterEngine; } @property (nonatomic, retain) UITextField *usernameTextField, *passwordTextField; @property (nonatomic, retain) UIButton *sendTweetButton; @property (nonatomic, retain) XAuthTwitterEngine *twitterEngine; - (IBAction)xAuthAccessTokenRequestButtonTouchUpInside; - (IBAction)sendTestTweetButtonTouchUpInside; @end
aral/XAuthTwitterEngine
XAuthTwitterEngineDemo/UIAlertView+Helper.h
<filename>XAuthTwitterEngineDemo/UIAlertView+Helper.h // // UIAlertViewHelper.h // CocoaHelpers // // Created by <NAME> on 10/16/08. // Copyright 2008 enormego. All rights reserved. // #import <UIKit/UIKit.h> /* * Convenience method to throw a quick alert to the user */ void UIAlertViewQuick(NSString* title, NSString* message, NSString* dismissButtonTitle); @interface UIAlertView (Helper) @end
aral/XAuthTwitterEngine
XAuthTwitterEngineDemo/Classes/XAuthTwitterEngineDemoAppDelegate.h
// // XAuthTwitterEngineDemoAppDelegate.h // XAuthTwitterEngineDemo // // Created by <NAME> on 28/02/2010. // Copyright Naklab 2010. All rights reserved. // #import <UIKit/UIKit.h> @class XAuthTwitterEngineDemoViewController; @interface XAuthTwitterEngineDemoAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; XAuthTwitterEngineDemoViewController *viewController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet XAuthTwitterEngineDemoViewController *viewController; @end
EricJeffrey/my_http_server
response_header.h
#if !defined(RESPONSE_HEADER_H) #define RESPONSE_HEADER_H #include "utils.h" #include <map> #include <string> #include <sys/stat.h> using std::map; using std::string; using std::to_string; class response_header { public: static map<int, string> code2phrase; static string STR_VERSION_HTTP_1_1; static const int CODE_INTERNAL_SERVER_ERROR; static const int CODE_NOT_FOUND; static const int CODE_OK; static map<string, string> mp_file_suffix_2_content_type; string version; int status_code; string phrase; map<string, string> mp_gene_headers; response_header() {} ~response_header() {} // header with content-type:html, content-length:size of file of [path] static int htmlHeader(string path_file, response_header &header, int status_code = 200) { int ret = 0; struct stat file_info; ret = stat(path_file.c_str(), &file_info); if (ret == -1) { logger::fail({"in ", __func__, ": call to stat file: ", path_file, " failed"}, true); return -1; } header.version = STR_VERSION_HTTP_1_1; header.status_code = status_code; header.phrase = code2phrase[status_code]; header.mp_gene_headers["Content-Type"] = "text/html;charset=UTF-8"; header.mp_gene_headers["Content-Length"] = to_string(file_info.st_size); return 0; } static int strHeader(const string &data, response_header &header, int status_code = 200) { header.version = STR_VERSION_HTTP_1_1; header.status_code = status_code; header.phrase = code2phrase[status_code]; header.mp_gene_headers["Content-Type"] = "text/plain;charset=UTF-8"; header.mp_gene_headers["Content-Length"] = to_string(data.size()); return 0; } static int fileHeader(const string path_file, response_header &header, int status_code = 200) { int ret = 0; struct stat file_info; ret = stat(path_file.c_str(), &file_info); if (ret == -1) { logger::fail({"in ", __func__, ": call to stat file: ", path_file, " failed"}, true); return -1; } header.version = STR_VERSION_HTTP_1_1; header.status_code = status_code; header.phrase = code2phrase[status_code]; header.mp_gene_headers["Content-Type"] = "text/plain;charset=UTF-8"; header.mp_gene_headers["Content-Length"] = to_string(file_info.st_size); // set content-type according to suffix size_t last_pos_of_dot = path_file.find_last_of('.'); if (last_pos_of_dot != string::npos) { const string file_type = path_file.substr(last_pos_of_dot); if (mp_file_suffix_2_content_type.find(file_type) != mp_file_suffix_2_content_type.end()) header.mp_gene_headers["Content-Type"] = mp_file_suffix_2_content_type[file_type]; } return 0; } string toString() { stringstream ss; const char sp = ' '; const string crlf = "\r\n"; const char colon = ':'; ss << version << sp << status_code << sp << phrase << crlf; for (auto &&p : mp_gene_headers) ss << p.first << colon << p.second << crlf; ss << crlf; return ss.str(); } }; const int response_header::CODE_OK = 200; const int response_header::CODE_NOT_FOUND = 404; const int response_header::CODE_INTERNAL_SERVER_ERROR = 500; string response_header::STR_VERSION_HTTP_1_1 = "HTTP/1.1"; map<int, string> response_header::code2phrase; map<string, string> response_header::mp_file_suffix_2_content_type = { {".tif", "image/tiff"}, {".asf", "video/x-ms-asf"}, {".asp", "text/asp"}, {".asx", "video/x-ms-asf"}, {".au", "audio/basic"}, {".avi", "video/avi"}, {".awf", "application/vnd.adobe.workflow"}, {".biz", "text/xml"}, {".bmp", "application/x-bmp"}, {".bot", "application/x-bot"}, {".cdr", "application/x-cdr"}, {".cel", "application/x-cel"}, {".cer", "application/x-x509-ca-cert"}, {".cg4", "application/x-g4"}, {".cgm", "application/x-cgm"}, {".cit", "application/x-cit"}, {".class", "java/*"}, {".cml", "text/xml"}, {".cmp", "application/x-cmp"}, {".cmx", "application/x-cmx"}, {".cot", "application/x-cot"}, {".crl", "application/pkix-crl"}, {".crt", "application/x-x509-ca-cert"}, {".csi", "application/x-csi"}, {".css", "text/css"}, {".cut", "application/x-cut"}, {".dbf", "application/x-dbf"}, {".dbm", "application/x-dbm"}, {".dbx", "application/x-dbx"}, {".dcd", "text/xml"}, {".dcx", "application/x-dcx"}, {".der", "application/x-x509-ca-cert"}, {".dgn", "application/x-dgn"}, {".dib", "application/x-dib"}, {".dll", "application/x-msdownload"}, {".doc", "application/msword"}, {".dot", "application/msword"}, {".drw", "application/x-drw"}, {".dtd", "text/xml"}, {".dwf", "Model/vnd.dwf"}, {".dwf", "application/x-dwf"}, {".dwg", "application/x-dwg"}, {".dxb", "application/x-dxb"}, {".dxf", "application/x-dxf"}, {".edn", "application/vnd.adobe.edn"}, {".emf", "application/x-emf"}, {".eml", "message/rfc822"}, {".ent", "text/xml"}, {".epi", "application/x-epi"}, {".eps", "application/x-ps"}, {".eps", "application/postscript"}, {".etd", "application/x-ebx"}, {".exe", "application/x-msdownload"}, {".fax", "image/fax"}, {".fdf", "application/vnd.fdf"}, {".fif", "application/fractals"}, {".fo", "text/xml"}, {".frm", "application/x-frm"}, {".g4", "application/x-g4"}, {".gbr", "application/x-gbr"}, {".", "application/x-"}, {".gif", "image/gif"}, {".gl2", "application/x-gl2"}, {".gp4", "application/x-gp4"}, {".hgl", "application/x-hgl"}, {".hmr", "application/x-hmr"}, {".hpg", "application/x-hpgl"}, {".hpl", "application/x-hpl"}, {".hqx", "application/mac-binhex40"}, {".hrf", "application/x-hrf"}, {".hta", "application/hta"}, {".htc", "text/x-component"}, {".htm", "text/html"}, {".html", "text/html"}, {".htt", "text/webviewhtml"}, {".htx", "text/html"}, {".icb", "application/x-icb"}, {".ico", "image/x-icon"}, {".ico", "application/x-ico"}, {".iff", "application/x-iff"}, {".ig4", "application/x-g4"}, {".igs", "application/x-igs"}, {".iii", "application/x-iphone"}, {".img", "application/x-img"}, {".ins", "application/x-internet-signup"}, {".isp", "application/x-internet-signup"}, {".IVF", "video/x-ivf"}, {".java", "java/*"}, {".jfif", "image/jpeg"}, {".jpe", "image/jpeg"}, {".jpe", "application/x-jpe"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".jpg", "application/x-jpg"}, {".js", "application/x-javascript"}, {".jsp", "text/html"}, {".la1", "audio/x-liquid-file"}, {".lar", "application/x-laplayer-reg"}, {".latex", "application/x-latex"}, {".lavs", "audio/x-liquid-secure"}, {".lbm", "application/x-lbm"}, {".lmsff", "audio/x-la-lms"}, {".ls", "application/x-javascript"}, {".ltr", "application/x-ltr"}, {".m1v", "video/x-mpeg"}, {".m2v", "video/x-mpeg"}, {".m3u", "audio/mpegurl"}, {".m4e", "video/mpeg4"}, {".mac", "application/x-mac"}, {".man", "application/x-troff-man"}, {".math", "text/xml"}, {".mdb", "application/msaccess"}, {".mdb", "application/x-mdb"}, {".mfp", "application/x-shockwave-flash"}, {".mht", "message/rfc822"}, {".mhtml", "message/rfc822"}, {".mp1", "audio/mp1"}, {".mp2", "audio/mp2"}, {".mp2v", "video/mpeg"}, {".mp3", "audio/mp3"}, {".mp4", "video/mpeg4"}, {".mpa", "video/x-mpg"}, {".mpd", "application/vnd.ms-project"}, {".mpe", "video/x-mpeg"}, {".mpeg", "video/mpg"}, {".mpg", "video/mpg"}, {".mpga", "audio/rn-mpeg"}, {".mpp", "application/vnd.ms-project"}, {".mps", "video/x-mpeg"}, {".mpt", "application/vnd.ms-project"}, {".mpv", "video/mpg"}, {".mpv2", "video/mpeg"}, {".mpw", "application/vnd.ms-project"}, {".mpx", "application/vnd.ms-project"}, {".mtx", "text/xml"}, {".mxp", "application/x-mmxp"}, {".net", "image/pnetvue"}, {".nrf", "application/x-nrf"}, {".nws", "message/rfc822"}, {".odc", "text/x-ms-odc"}, {".out", "application/x-out"}, {".pdf", "application/pdf"}, {".pdf", "application/pdf"}, {".plt", "application/x-plt"}, {".png", "image/png"}, {".png", "application/x-png"}, {".pot", "application/vnd.ms-powerpoint"}, {".ppa", "application/vnd.ms-powerpoint"}, {".ppm", "application/x-ppm"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppt", "application/vnd.ms-powerpoint"}, {".ppt", "application/x-ppt"}, {".pr", "application/x-pr"}, {".prf", "application/pics-rules"}, {".prn", "application/x-prn"}, {".prt", "application/x-prt"}, {".ps", "application/x-ps"}, {".ps", "application/postscript"}, {".ptn", "application/x-ptn"}, {".rec", "application/vnd.rn-recording"}, {".red", "application/x-red"}, {".rgb", "application/x-rgb"}, {".rm", "application/vnd.rn-realmedia"}, {".rmf", "application/vnd.adobe.rmf"}, {".rmi", "audio/mid"}, {".rmj", "application/vnd.rn-realsystem-rmj"}, {".rmm", "audio/x-pn-realaudio"}, {".rmp", "application/vnd.rn-rn_music_package"}, {".rms", "application/vnd.rn-realmedia-secure"}, {".rmvb", "application/vnd.rn-realmedia-vbr"}, {".rmx", "application/vnd.rn-realsystem-rmx"}, {".rnx", "application/vnd.rn-realplayer"}, {".rp", "image/vnd.rn-realpix"}, {".rpm", "audio/x-pn-realaudio-plugin"}, {".rsml", "application/vnd.rn-rsml"}, {".rt", "text/vnd.rn-realtext"}, {".rtf", "application/msword"}, {".rtf", "application/x-rtf"}, {".rv", "video/vnd.rn-realvideo"}, {".sam", "application/x-sam"}, {".sat", "application/x-sat"}, {".sdp", "application/sdp"}, {".spc", "application/x-pkcs7-certificates"}, {".spl", "application/futuresplash"}, {".spp", "text/xml"}, {".ssm", "application/streamingmedia"}, {".sst", "application/vnd.ms-pki.certstore"}, {".stl", "application/vnd.ms-pki.stl"}, {".stm", "text/html"}, {".sty", "application/x-sty"}, {".svg", "text/xml"}, {".swf", "application/x-shockwave-flash"}, {".tdf", "application/x-tdf"}, {".tg4", "application/x-tg4"}, {".tga", "application/x-tga"}, {".tif", "image/tiff"}, {".tif", "application/x-tif"}, {".tiff", "image/tiff"}, {".tld", "text/xml"}, {".top", "drawing/x-top"}, {".torrent", "application/x-bittorrent"}, {".tsd", "text/xml"}, {".txt", "text/plain"}, {".uin", "application/x-icq"}, {".uls", "text/iuls"}, {".vcf", "text/x-vcard"}, {".vda", "application/x-vda"}, {".vdx", "application/vnd.visio"}, {".vml", "text/xml"}, {".vpg", "application/x-vpeg005"}, {".vsd", "application/vnd.visio"}, {".vsd", "application/x-vsd"}, {".vss", "application/vnd.visio"}, {".vst", "application/vnd.visio"}, {".vst", "application/x-vst"}, {".vsw", "application/vnd.visio"}, {".vsx", "application/vnd.visio"}, {".vtx", "application/vnd.visio"}, {".vxml", "text/xml"}, {".wav", "audio/wav"}, {".wax", "audio/x-ms-wax"}, {".wb1", "application/x-wb1"}, {".wb2", "application/x-wb2"}, {".wb3", "application/x-wb3"}, {".wbmp", "image/vnd.wap.wbmp"}, {".wiz", "application/msword"}, {".wk3", "application/x-wk3"}, {".wk4", "application/x-wk4"}, {".wkq", "application/x-wkq"}, {".wks", "application/x-wks"}, {".wm", "video/x-ms-wm"}, {".wma", "audio/x-ms-wma"}, {".wmd", "application/x-ms-wmd"}, {".wmf", "application/x-wmf"}, {".wml", "text/vnd.wap.wml"}, {".wmv", "video/x-ms-wmv"}, {".wmx", "video/x-ms-wmx"}, {".wmz", "application/x-ms-wmz"}, {".wp6", "application/x-wp6"}, {".wpd", "application/x-wpd"}, {".wpg", "application/x-wpg"}, {".wpl", "application/vnd.ms-wpl"}, {".wq1", "application/x-wq1"}, {".wr1", "application/x-wr1"}, {".wri", "application/x-wri"}, {".wrk", "application/x-wrk"}, {".ws", "application/x-ws"}, {".ws2", "application/x-ws"}, {".wsc", "text/scriptlet"}, {".wsdl", "text/xml"}, {".wvx", "video/x-ms-wvx"}, {".xdp", "application/vnd.adobe.xdp"}, {".xdr", "text/xml"}, {".xfd", "application/vnd.adobe.xfd"}, {".xfdf", "application/vnd.adobe.xfdf"}, {".xhtml", "text/html"}, {".xls", "application/vnd.ms-excel"}, {".xls", "application/x-xls"}, {".xlw", "application/x-xlw"}, {".xml", "text/xml"}, {".xpl", "audio/scpls"}, {".xq", "text/xml"}, {".xql", "text/xml"}, {".xquery", "text/xml"}, {".ipa", "application/vnd.iphone"}, {".apk", "application/vnd.android.package-archive"}, }; #endif // RESPONSE_HEADER_H
EricJeffrey/my_http_server
config.h
<reponame>EricJeffrey/my_http_server #if !defined(CONFIG_H) #define CONFIG_H #include <string> #include <unordered_map> #include <vector> using std::pair; using std::string; using std::unordered_map; using std::vector; typedef pair<string, string> PAIR_SS; typedef pair<int, string> PAIR_IS; class config { public: static string address; static int port; static int backlog; // timeout of connection static double timeout_sec_conn; static string path_logger; static vector<PAIR_SS> list_url2file_cgi; static vector<PAIR_SS> list_url2path_static; static unordered_map<int, string> map_code2file_error; // specfied in argumemtns static bool debug; // specfied in argumemtns static int log_level; // predefined values static const string key_port; static const string key_address; static const string key_timeout_sec_conn; static const string key_path_logger; static const string key_list_url2path_static; static const string key_list_url2file_cgi; static const string key_map_code2file_error; static const string path_default_logger_cerr; static const string path_config; static const string key_env_query_string; config() {} ~config() {} }; string config::address; int config::port; int config::backlog; bool config::debug; int config::log_level; vector<PAIR_SS> config::list_url2path_static; vector<PAIR_SS> config::list_url2file_cgi; unordered_map<int, string> config::map_code2file_error; double config::timeout_sec_conn; string config::path_logger; const string config::key_port = "port"; const string config::key_address = "address"; const string config::key_timeout_sec_conn = "connection_timeout"; const string config::key_path_logger = "log_file"; const string config::key_list_url2path_static = "static_directory_map"; const string config::key_list_url2file_cgi = "cgi_file_map"; const string config::key_map_code2file_error = "error_file_map"; const string config::key_env_query_string = "query"; const string config::path_default_logger_cerr = "cerr"; const string config::path_config = "halox.conf"; #endif // CONFIG_H
EricJeffrey/my_http_server
request_header.h
#if !defined(REQUEST_HEADER_H) #define REQUEST_HEADER_H #include "utils.h" #include <map> #include <vector> using std::map; using std::pair; using std::vector; typedef pair<string, string> PAIR_SS; class request_header { public: string version; string method; string url; map<string, string> mp_gene_req_headers; vector<PAIR_SS> list_pair_headers; request_header() {} ~request_header() {} bool has(string key) { return mp_gene_req_headers.find(key) != mp_gene_req_headers.end(); } // ensure key exists! string get(string key) { return mp_gene_req_headers[key]; } // -1 for error static int fromHeaderLines(vector<string> line_headers, request_header &header) { if (line_headers.size() <= 0) { logger::fail({__func__, "failed, line_headers.size = 0"}); return -1; }; const string req_line = line_headers[0]; size_t pos_start = 0; size_t pos_end = 0; const char space = ' '; // method pos_end = req_line.find(space, pos_start); if (pos_end == string::npos) return -1; header.method = req_line.substr(pos_start, pos_end - pos_start); // url pos_start = pos_end + 1; pos_end = req_line.find(space, pos_start); if (pos_end == string::npos) return -1; header.url = req_line.substr(pos_start, pos_end - pos_start); // version pos_start = pos_end + 1; header.version = req_line.substr(pos_start); const char colon = ':'; for (size_t i = 1; i < line_headers.size(); i++) { string line_tmp = line_headers[i]; pos_end = line_tmp.find(colon); if (pos_end == string::npos) return -1; string key = line_tmp.substr(0, pos_end); pos_end += 1; string val = line_tmp.substr(pos_end, line_tmp.size() - pos_end); header.mp_gene_req_headers[key] = val; header.list_pair_headers.push_back(PAIR_SS(key, val)); } return 0; } }; #endif // REQUEST_HEADER_H
EricJeffrey/my_http_server
oldver_19_11/header_file/include_heads.h
<gh_stars>1-10 #include <arpa/inet.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <pthread.h> #include <string> #include <sys/socket.h> #include <sys/stat.h> #include <unistd.h> #include <vector> using std::pair; using std::string; using std::vector; typedef const char *con_c_str; #define SVR_PORT 2500 #define BACKLOG 20 #define PAGE_DIR_PATH "./pages" #if !defined(ERR_EXIT) #define ERR_EXIT int err_exit(int err, const char *s, bool thread_exit, int sd); #endif // ERR_EXIT
EricJeffrey/my_http_server
oldver_19_10/src/logger.h
#include <stdio.h> #include <stdlib.h> #if !defined(LOGGER_H) #define LOGGER_H const int LOG_LV_DEBUG = 1; const int LOG_LV_VERBOSE = 2; const char LOG_LV_STR[][20] = {"", "DEBUG", "VERBOSE"}; int LOG_LEVEL = LOG_LV_VERBOSE; FILE *FP_LOG_OUTPUT = stderr; // 设置日志等级 #define LOGGER_SET_LV(x) \ do { \ if (x >= LOG_LV_DEBUG && x <= LOG_LV_VERBOSE) \ LOG_LEVEL = x; \ } while (0) #define LOGGER_SIMP(level, str) \ do { \ if (level <= LOG_LEVEL && level > 0) \ fprintf(FP_LOG_OUTPUT, "LOG %s:--- %s --- LOG %s OVER\n", LOG_LV_STR[level], str, LOG_LV_STR[level]); \ } while (0) #define LOGGER_FORMAT(level, format, ...) \ do { \ if (level <= LOG_LEVEL && level > 0) { \ fprintf(FP_LOG_OUTPUT, "LOG %s:--- ", LOG_LV_STR[level]); \ fprintf(FP_LOG_OUTPUT, format, __VA_ARGS__); \ fprintf(FP_LOG_OUTPUT, ". ---LOG %s OVER\n", LOG_LV_STR[level]); \ } \ } while (0) #endif // LOGGER_H
EricJeffrey/my_http_server
conn_hanlder.h
<gh_stars>1-10 #if !defined(CONN_HANDLER_H) #define CONN_HANDLER_H #include "buffered_reader.h" #include "cgi_server.h" #include "config.h" #include "request_header.h" #include "response_header.h" #include "static_server.h" #include "utils.h" #include <arpa/inet.h> #include <fcntl.h> #include <netdb.h> #include <sys/socket.h> #include <thread> #include <unistd.h> using std::thread; class conn_handler { private: int sd; sockaddr_in addr; socklen_t len_addr; // 解析url路径与参数,返回路径类型 // 1-static,0-cgi,-1-error static int parseUrl(string url, string &path, vector<string> &paras_list) { path.clear(); paras_list.clear(); const size_t npos = string::npos; const size_t sz_url = url.size(); if (sz_url == 0) return -1; size_t pos_of_question_sign = url.find_first_of('?'); int res = -1; size_t st_path = 0; size_t ed_path = (pos_of_question_sign == npos ? sz_url : pos_of_question_sign); // static or cgi int type_static = -1; string dir_static_mapped; string file_cgi_mapped; // static dir url // todo fix bug: '/' is mapped to everyone for (auto &&url2path : config::list_url2path_static) { const string &url_key_tmp = url2path.first; const size_t sz_url_tmp = url_key_tmp.size(); if (sz_url > sz_url_tmp && url.substr(0, sz_url_tmp) == url_key_tmp) { st_path = sz_url_tmp; dir_static_mapped = url2path.second; type_static = 1; break; } } if (type_static == -1) { // cgi file url for (auto &&url2file : config::list_url2file_cgi) { const string &url_key_tmp = url2file.first; const size_t sz_url_tmp = url_key_tmp.size(); // e.g. url='/abcd', url2file='/abc'->'xxx' if (sz_url >= sz_url_tmp && url.substr(0, sz_url_tmp) == url_key_tmp && (sz_url == sz_url_tmp || url[sz_url_tmp] == '?')) { file_cgi_mapped = url2file.second; type_static = 0; break; } } } res = type_static; if (res == -1) return -1; // /static/? or /static/ if (type_static == 1 && st_path == ed_path) return -1; path = (type_static == 1 ? dir_static_mapped + url.substr(st_path, ed_path - st_path) : file_cgi_mapped); // no ? found in url if (pos_of_question_sign == npos || pos_of_question_sign == sz_url - 1) return res; size_t st_para = pos_of_question_sign + 1; while (true) { size_t pos_and_sign = url.find_first_of('&', st_para); // no more '&' if (pos_and_sign == string::npos || pos_and_sign == sz_url) { paras_list.push_back(url.substr(st_para, sz_url - st_para)); break; } else { if (pos_and_sign > st_para) paras_list.push_back(url.substr(st_para, pos_and_sign - st_para)); st_para = pos_and_sign + 1; } } return res; } // todo custom error file page int serveError(int status_code) { logger::info({"start serve error file, status_code: ", to_string(status_code)}); int ret = 0; auto &mp = config::map_code2file_error; if (mp.find(status_code) == mp.end()) { // unsupported, just send code response_header header; const string data = "error" + to_string(status_code); response_header::strHeader(data, header, status_code); string resp = header.toString() + data; ret = utils::writeStr2Fd(resp, sd); if (ret == -1) { logger::fail({"in ", __func__, ": call to utils.writeStr2Fd failed"}); return -1; } return 0; } int fd_file; int sz_file; string str_header; sz_file = fd_file = 0; const string &path_abs = mp[status_code]; ret = createFileBundle(path_abs, str_header, sz_file, fd_file, status_code); if (ret == -1) { logger::fail({"in ", __func__, ": call to create file bundle failed!"}); return -1; } ret = writeFBundle2client(str_header, sz_file, fd_file, sd); if (ret == -1) { logger::fail({"in ", __func__, ": call to write file bundle to client failed!"}); return -1; } close(fd_file); return 0; } // clear lines. do not read body // return num of lines readed, -1 for error, -2 for wouldblock, -3 for closed int readRequestHeader(request_header &header) { buffered_reader reader(sd); int ret = 0; // check header end const string line_crlf = string("\r\n"); vector<string> lines; while (true) { string line; ret = reader.readLine(line); if (ret == -1) { logger::fail({"in ", __func__, ": call to reader.readline on sd: ", to_string(sd), " failed"}); return -1; } else if (ret == -2) { return -2; } else if (ret == 0) { logger::info({"in ", __func__, ": call to reader.readline on sd: ", to_string(sd), " return 0, closed"}); return -3; } if (line == line_crlf) break; if (ret > 0) lines.push_back(line); } ret = request_header::fromHeaderLines(lines, header); if (ret == -1) { logger::fail({"in ", __func__, ": call to fromHeaderLines failed with return -1"}); return -1; }; return 0; } // run in new thread! int handleNewConn() { logger::info({"handling new conn from sock: ", to_string(sd), " , addr: ", inet_ntoa(addr.sin_addr)}); int ret = 0; // set to nonblock // ret = fcntl(sd, F_SETFL, O_NONBLOCK); if (ret == -1) { logger::fail({"in ", __func__, ": call to fcntl, set socket nonblock failed"}, true); close(sd); return -1; } // timer clock_t clock_start = clock(); while ((clock() - clock_start) / (double)CLOCKS_PER_SEC < config::timeout_sec_conn) { request_header header; ret = readRequestHeader(header); if (ret == -1) { logger::fail({"in ", __func__, ": call to readRequestHeader failed"}); serveError(response_header::CODE_INTERNAL_SERVER_ERROR); return -1; } else if (ret == -2) { // would block, continue continue; } else if (ret == -3) { logger::info({"connection to socket: ", to_string(sd), " closed"}); close(sd); return 0; } logger::debug({"request url: ", header.url}); string path; vector<string> list_paras; ret = parseUrl(header.url, path, list_paras); if (ret == 1) { // static ret = serveStatic(path, sd); if (ret == -1) { logger::fail({"in ", __func__, ": call to serveStatic failed"}); serveError(response_header::CODE_INTERNAL_SERVER_ERROR); } else if (ret == -2) { serveError(response_header::CODE_NOT_FOUND); } } else if (ret == 0) { // cgi ret = serveCgi(path, list_paras, sd); if (ret == -1) { logger::fail({"in ", __func__, ": call to serveCgi failed"}); serveError(response_header::CODE_INTERNAL_SERVER_ERROR); } else if (ret == -2) { serveError(response_header::CODE_NOT_FOUND); } } else { serveError(response_header::CODE_NOT_FOUND); } } logger::verbose({"connection from socket: ", to_string(sd), " timeout, closing"}); ret = close(sd); return 0; } public: conn_handler(int sd, sockaddr_in addr, socklen_t len_addr) { this->sd = sd; this->addr = addr; this->len_addr = len_addr; } ~conn_handler() {} void start() { handleNewConn(); } }; #endif // CONN_HANDLER_H
EricJeffrey/my_http_server
main_app.h
#if !defined(MAIN_APP_H) #define MAIN_APP_H #include <set> #include <string> #include <unistd.h> using std::set; using std::string; enum state { initialize, start, stop }; class main_app { private: // arguments to parse static int argc; static char **argv; static const string usage; static set<pid_t> set_child_pids; static int createConfigFile(); static int parseArgs(); static int loadConfig(); static void init(); static void start(); static void stop(); public: static state app_state; main_app() {} ~main_app() {} static void run(int argc, char *argv[]) { main_app::argc = argc; main_app::argv = argv; init(); start(); } static void addChildProcess(pid_t pid) { set_child_pids.insert(pid); } static void removeChild(pid_t pid) { set_child_pids.erase(pid); } }; #endif // MAIN_APP_H
EricJeffrey/my_http_server
utils.h
#if !defined(UTILS_H) #define UTILS_H #include "config.h" #include "logger.h" #include <fcntl.h> #include <regex> #include <string> #include <sys/stat.h> using std::regex; using std::regex_match; using std::to_string; class utils { private: public: static const set<string> set_errorcode; utils() {} ~utils() {} static bool check_timeout(string timeout) { return regex_match(timeout, regex("^[1-9]\\d*[.\\d*]{0,}")); } static bool check_port(string port) { return regex_match(port, regex("[1-9]{1}[0-9]{3,4}")); }; static bool check_addr(string addr) { return regex_match(addr, regex("(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d).(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d).(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d).(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)")); }; static bool check_log_level(string log_level) { for (auto &&p : logger::LIST_LOG_LV2STRING) if (p.second == log_level) return true; return false; }; // split string with [ch], -1 for error static int split(const string &s, const char ch, PAIR_SS &res) { size_t pos = 0; pos = s.find('='); if (pos == 0 || pos == s.size() || pos == string::npos) return -1; res.first = s.substr(0, pos); pos += 1; res.second = s.substr(pos, s.size() - pos); return 0; }; // trim [s] in place, remove whitespace and tab static void trim(string &s) { size_t st = 0; size_t ed = s.size(); while (st < s.size() && (s[st] == ' ' || s[st] == '\t')) st++; while (ed >= 0 && (s[ed] == ' ' || s[st] == '\t')) ed--; if (st <= ed) s = s.substr(st, ed - st + 1); }; // check existence of [path], create it and open it static bool check_output_path(string path) { if (path == config::path_default_logger_cerr || access(path.c_str(), F_OK | W_OK) != -1) return true; int fd = 0; if (creat(path.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) { if ((fd = open(path.c_str(), O_RDWR | O_TRUNC)) == -1) return false; close(fd); } return true; }; // 判断文件是否为普通文件,-1 error, 0 not, 1 ok static int isRegFile(const char *path) { struct stat path_info; int ret = stat(path, &path_info); if (ret == -1) { logger::info({"stat file failed"}); return -1; } if (path_info.st_mode & S_IFREG) return 1; return 0; }; // 从 fd 读取数据直到 [read] 返回 0 // return number of bytes read, -1 for error, -2 for EAGAIN|EWOULDBLOCK static int readAll(int fd, string &res) { res.clear(); int ret = 0; const size_t sz_buf = 2048; size_t n; char buffer[sz_buf]; while (true) { // will block on pipe ret = read(fd, buffer, sz_buf); int errno_tmp = errno; if (ret == -1) { if (errno_tmp == EINTR) continue; if (errno_tmp == EAGAIN || errno_tmp == EWOULDBLOCK) { logger::info({"read on sd: ", to_string(fd), " would block"}); return -2; } logger::fail({"in ", __func__, ": call to read failed"}, true); cerr << "read failed" << endl; return -1; } if (ret == 0) break; n += ret; res += string(buffer, ret); } return n; }; // 将 [s] 中的内容写到 fd 中,-1 for error static int writeStr2Fd(const string &s, int fd) { const char *buf = s.c_str(); int sz = s.size(); while (true) { int ret = write(fd, buf, sz); // all bytes written if (ret == sz) return 0; if (ret == -1) { logger::fail({"in ", __func__, ": failed with string(first 20 bytes): ", s.substr(0, std::max((int)s.size(), 20))}, true); return -1; } if (ret < sz) { // interrupted by signal int errno_tmp = errno; if (errno_tmp == EINTR) { buf += ret; sz -= ret; continue; } logger::fail({"in ", __func__, ": failed, bytes written less than size(ret < s.size())"}, true); return -1; } } } }; const set<string> utils::set_errorcode = {"400", "401", "402", "403", "404", "405", "406", "407", "408", "409", "410", "411", "412", "413", "414", "415", "416", "417", "500", "501", "502", "503", "504", "505"}; #endif // UTILS_H
EricJeffrey/my_http_server
oldver_19_10/src/thread_pool.h
<gh_stars>1-10 #if !defined(THREAD_POOL_H) #define THREAD_POOL_H #include "logger.h" #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <vector> using std::condition_variable; using std::mutex; using std::queue; using std::thread; using std::unique_lock; using std::vector; // 线程池任务参数 struct task_arg { int fd; task_arg() : fd(0) {} task_arg(int f) : fd(f) {} }; typedef void (*runnable)(task_arg arg); // 线程池中待执行任务 struct task { runnable runner; task_arg arg; task(runnable r, task_arg a) { runner = r; arg = a; } void run() { LOGGER_FORMAT(LOG_LV_VERBOSE, "task: run now, arg fd: %d", arg.fd); runner(arg); } }; // 线程池 class thread_pool { private: const int thread_num; vector<thread> threads; condition_variable condq; queue<task> qtasks; mutex mutexq; thread_pool(int thr_num) : thread_num(thr_num) { for (int i = 0; i < thread_num; i++) { threads.push_back(thread([this]() { while (1) { unique_lock<mutex> lck(mutexq); while (qtasks.empty()) condq.wait(lck); task tmptask = qtasks.front(); lck.unlock(); lck.release(); LOGGER_SIMP(LOG_LV_DEBUG, "thread: task got, lck unlocked, running..."); tmptask.run(); } })); } } public: // 提交任务,通知可用线程执行 void pushTask(task t) { LOGGER_SIMP(LOG_LV_VERBOSE, "thread pool: push task"); mutexq.lock(); qtasks.push(t); mutexq.unlock(); condq.notify_one(); } thread_pool(thread_pool &) = delete; void operator=(thread_pool const &) = delete; // 获取线程池实例 static thread_pool &getInstance(int tot_thread_num) { static thread_pool pool(tot_thread_num); return pool; } }; #endif // THREAD_POOL_H
EricJeffrey/my_http_server
test_utils.h
<reponame>EricJeffrey/my_http_server #include "utils.h" #include <iomanip> #include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; void test_parse_url() { vector<string> url_list = { "", "cgi", "/stait", "/static", "/hello", "/static/", "/cg", "/fil", "/cgi/", "/static/a", "/static/?", "/static/?wd=sdf", "/static/bcde", "/static/cd?", "/static/cd?a", "/static/cd?bcdefgh&sd", "/static/cd?wd=2&sd", "/static/cd?wd&sd=sdg", "/tak", "ta", "/tak?a=2", "/take?a=2&b=3", "/take?a&b", "/find?&b", "/find?a&cx=34"}; int i = 0; for (auto &&url_tmp : url_list) { cout << i++ << '\t'; cout << std::setw(23) << url_tmp << '\t' << std::setw(0); vector<string> paras; string path; int ret = utils::parseUrl(url_tmp, path, paras); if (ret == -1) { cout << "failed" << endl; } else { const string comma = ",\t"; cout << std::setw(6) << path << comma << std::setw(0); for (auto &&para_tmp : paras) cout << para_tmp << comma; cout << endl; } } }
EricJeffrey/my_http_server
oldver_19_10/header_file/req_resp_header.h
<reponame>EricJeffrey/my_http_server<gh_stars>1-10 #include "include_heads.h" #if !defined(REQ_RESP_HEADER) #define REQ_RESP_HEADER // request headers struct my_req_header { string path, method, version; vector<string> keys, values; void print_me() { printf("path: %s\nmethod: %s\nproto: %s\n", path.c_str(), method.c_str(), version.c_str()); for (int i = 0; i < keys.size(); i++) printf("%s:%s\n", keys[i].c_str(), values[i].c_str()); } }; // response msg_body, include header and content struct my_resp_msg { string version; int status_code; string phrase; vector<string> keys, values; int header_len; const char * msg_body; int msg_body_len; // init heaer my_resp_msg(const char *v, int code, const char *p) { version = v, status_code = code, phrase = p; header_len = version.size() + sizeof(int) + phrase.size() + 2 + 2 + 2; // two space, two \r\n } // set header content, 0 success, -1 on error int set_key_vals(const vector<string> &ks, const vector<string> &vals) { if (ks.size() != vals.size()) { printf("error: ks and vals size not equal."); return -1; } for (int i = 0; i < (int)ks.size() && i < (int)vals.size(); i++) { keys.push_back(ks[i]), values.push_back(vals[i]); header_len += ks[i].size() + values[i].size() + 3; // key:value\r\n } return 0; } // set response msg body and its lenth int set_msg_body(const char *mb, int mb_len) { msg_body = mb, msg_body_len = mb_len; } // convert response msg to c str (for send), return msg body len, -1 on error int get_msg_cstr(char *buf, int buf_len) { if (buf_len < msg_body_len + header_len) { printf("error get_msg_cstr: buf_len < msg_body_len."); return -1; } int t = 0; t += sprintf(buf, "%s %d %s\r\n", version.c_str(), status_code, phrase.c_str()); for (int i = 0; i < (int)keys.size(); i++) { t += sprintf(buf + t, "%s:%s\r\n", keys[i].c_str(), values[i].c_str()); } t += sprintf(buf + t, "\r\n%s", msg_body); return t; } }; #endif // REQ_RESP_HEADER
EricJeffrey/my_http_server
oldver_19_11/header_file/svr_mgr.h
<gh_stars>1-10 #if !defined(SVR_MGR) #define SVR_MGR #include "req_resp_header.h" const char msg_body_404[] = "404: Requested Resource Not Found"; typedef pair<string, string> pss; // exit on error. err: error number, s: info, thread_exit: exit only this thread, sd: sd to close (only when thread_exit is false) int err_exit(int err, const char *s, bool thread_exit, int sd); // parse http headers, saved in header void parse_headers(const char *buf, int len, my_req_header *header); // handle client connectioin void *handle_conn(void *x); // server listen void start_listen(); /*send a http msg sd: socket, ver_co_phr: http/1.0 200 OK, vcp_len: len of ver_co_phr h_body: general header content, msg_body: data, m_body_len: size of data*/ int send_msg(int sd, con_c_str ver_co_phr, int vcp_len, vector<pss> *h_body, con_c_str msg_body, int mb_len); // send file content into sd int send_file(string path, int sd); #endif // SVR_MGR
EricJeffrey/my_http_server
buffered_reader.h
<gh_stars>1-10 #if !defined(BUFFERED_READER_H) #define BUFFERED_READER_H #include "logger.h" #include "utils.h" #include <unistd.h> #include <vector> using std::fill; using std::to_string; class buffered_reader { private: static const int SIZE_BUFFER = 2048; char buffer[SIZE_BUFFER]; int fd; int pos; int len; void resetBuffer() { fill(buffer, buffer + SIZE_BUFFER, 0); pos = len = 0; } // clear buffer, return [length], -1 for error, -2 for [fd] EAGAIN|EWOULDBLOCK int fillBuffer() { resetBuffer(); int ret = 0; int pos_tmp = 0; int sz_to_read = SIZE_BUFFER; while (true) { ret = read(fd, buffer + pos_tmp, sz_to_read); int errno_tmp = errno; if (ret == -1) { // socket would block if (errno_tmp == EAGAIN || errno_tmp == EWOULDBLOCK) { return -2; } logger::fail({"in ", __func__, ": call to read failed"}, true); return -1; } else if (ret < sz_to_read) { if (errno_tmp == EINTR) { // interrupted sz_to_read -= ret; pos_tmp += ret; continue; } else { // no more len = pos_tmp + ret; return len; } } len = SIZE_BUFFER; return len; } return 0; } public: buffered_reader(int fd) { fill(buffer, buffer + SIZE_BUFFER, 0); this->fd = fd; pos = len = 0; } ~buffered_reader() {} // save '\r\n' !! [line] will be cleared! // return [length], 0 for eof(closed socket), -1 for error, -2 for timeout int readLine(string &line) { line.clear(); stringstream ss; int ret = 0; if (len == 0) { ret = fillBuffer(); if (ret == -1) { logger::fail({"in ", __func__, ": call to fillbuffer failed"}); return -1; } else if (ret == 0) { logger::fail({"in ", __func__, ": call to fillbuffer return 0"}); return 0; } else if (ret == -2) { return -2; } } for (int ed = pos;; ed++) { if (ed + 1 < len && buffer[ed] == '\r' && buffer[ed + 1] == '\n') { ed = ed + 2; ss << string(buffer + pos, buffer + ed); pos = ed; string str_tmp = ss.str(); line = str_tmp; return line.size(); } if (ed == len - 1) { ss << string(buffer + pos, buffer + len); ret = fillBuffer(); if (ret == -1) { logger::fail({"in ", __func__, ": call to fillbuffer failed in loop"}); return -1; } else if (ret == 0) { logger::verbose({"fillbuffer return 0"}); return 0; } else if (ret == -2) { return -2; } } } return 0; } }; #endif // BUFFERED_READER_H
EricJeffrey/my_http_server
oldver_19_10/src/err_handler.h
<filename>oldver_19_10/src/err_handler.h #include <errno.h> #include <stdio.h> #include <string.h> #include <signal.h> #if !defined(ERR_HANDLER_H) #define ERR_HANDLER_H FILE *fp_err_out = stderr; #define errExitSimp(A) \ do { \ fprintf(fp_err_out, "ERROR! %s.\nerrno: %d, strerror: %s\n", A, errno, strerror(errno)); \ kill(0, SIGKILL); \ exit(EXIT_FAILURE); \ } while (0); #define errExitFormat(A, ...) \ do { \ fprintf(fp_err_out, "ERROR! ---\n"); \ fprintf(fp_err_out, A, __VA_ARGS__); \ fprintf(fp_err_out, ".\nerrno: %d, strerror: %s ---\n", errno, strerror(errno)); \ kill(0, SIGKILL); \ exit(EXIT_FAILURE); \ } while (0) #endif // ERR_HANDLER_H
EricJeffrey/my_http_server
logger.h
#if !defined(LOGGER_H) #define LOGGER_H #include "config.h" #include <cerrno> #include <cstring> #include <fstream> #include <initializer_list> #include <iostream> #include <mutex> #include <ostream> #include <queue> #include <sstream> #include <string> #include <sys/syscall.h> #include <sys/types.h> #include <thread> #include <unistd.h> using std::cerr; using std::endl; using std::initializer_list; using std::mutex; using std::ofstream; using std::ostream; using std::queue; using std::string; using std::stringstream; using std::thread; using std::unique_ptr; class logger { private: static thread thread_logger; static mutex mtx_logger; static queue<string> queue_logger; static bool running_logger; static ostream *ofs_logger; static bool ofs_using_cerr; // get current thread id static void preInfo(stringstream &ss) { ss << syscall(__NR_gettid) << " "; } static void msgInfo(stringstream &ss, initializer_list<string> &msg_list) { for (auto &&msg : msg_list) ss << msg; } // lock and flush queue static void flushQueue() { mtx_logger.lock(); while (!queue_logger.empty()) { (*ofs_logger) << queue_logger.front() << endl; queue_logger.pop(); } mtx_logger.unlock(); ofs_logger->flush(); } // todo maybe too many lock/unlock, consider another way // commit log static void commitLog(const string &s) { mtx_logger.lock(); queue_logger.push(s); mtx_logger.unlock(); } public: static const int LOG_LV_VERBOSE; static const int LOG_LV_INFO; static const vector<PAIR_IS> LIST_LOG_LV2STRING; logger() {} ~logger() {} // to [stderr] static void info(initializer_list<string> msg_list) { if (config::log_level >= LOG_LV_INFO) { stringstream ss; preInfo(ss); ss << "info\t"; msgInfo(ss, msg_list); commitLog(ss.str()); } } // to [stderr] static void verbose(initializer_list<string> msg_list) { if (config::log_level > LOG_LV_VERBOSE) { stringstream ss; preInfo(ss); ss << "verbose\t"; msgInfo(ss, msg_list); commitLog(ss.str()); } } // to [stderr], print [errno] if [show_errno]=true, no [exit]! static void fail(initializer_list<string> msg_list, bool show_erron = false) { int errno_tmp = errno; string err_msg = string(strerror(errno_tmp)); stringstream ss; preInfo(ss); ss << "ERROR\t"; msgInfo(ss, msg_list); if (show_erron && errno_tmp != 0) ss << ". errno: " << errno_tmp << ", " << err_msg << "."; commitLog(ss.str()); } // to [stderr] static void debug(initializer_list<string> msg_list) { if (config::debug) { stringstream ss; preInfo(ss); ss << "debug\t"; msgInfo(ss, msg_list); commitLog(ss.str()); } } // stop thread, flush queue static void stop() { running_logger = false; flushQueue(); } // start logger thread static void start() { if (config::path_logger == config::path_default_logger_cerr) { ofs_logger = &cerr, ofs_using_cerr = true; } else { ofs_logger = new ofstream(config::path_logger, std::ios_base::trunc); } running_logger = true; thread_logger = thread([]() -> void { // sleep for 0.2 seconds struct timespec ts = {200000000, 0}, remain_ts; while (running_logger) { ts.tv_nsec = 200000000, ts.tv_sec = 0; nanosleep(&ts, &remain_ts); flushQueue(); } if (!ofs_using_cerr) dynamic_cast<ofstream *>(ofs_logger)->close(); }); thread_logger.detach(); } }; const int logger::LOG_LV_VERBOSE = 5; const int logger::LOG_LV_INFO = 4; const vector<PAIR_IS> logger::LIST_LOG_LV2STRING = { PAIR_IS(LOG_LV_INFO, "info"), PAIR_IS(LOG_LV_VERBOSE, "verbose"), }; thread logger::thread_logger; mutex logger::mtx_logger; queue<string> logger::queue_logger; bool logger::running_logger = false; ostream *logger::ofs_logger; bool logger::ofs_using_cerr = false; #endif // LOGGER_H
EricJeffrey/my_http_server
main_listener.h
<gh_stars>1-10 #if !defined(MAIN_LISTENER_H) #define MAIN_LISTENER_H #include "config.h" #include "conn_hanlder.h" #include "main_app.h" #include "utils.h" class main_listener { private: /* -1 for error int openListenFd(int port, int backlog) { addrinfo hints, *listp, *p; int listenfd, optval = 1; int ret = 0; memset(&hints, 0, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG | AI_NUMERICSERV; const char *port_str = to_string(port).c_str(); getaddrinfo(NULL, port_str, &hints, &listp); for (p = listp; p; p = p->ai_next) { listenfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (listenfd < 0) continue; // reuse setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)); ret = bind(listenfd, p->ai_addr, p->ai_addrlen); if (ret == 0) break; close(listenfd); } freeaddrinfo(listp); if (p == nullptr) { logger::fail({__func__, "create listen socket failed"}, true); return -1; } if (listen(listenfd, backlog) < 0) { close(listenfd); logger::fail({"in ", __func__, ": call to listen on socket failed"}, true); return -1; } return listenfd; } */ // donot use getaddrinfo // -1 for error int openListenFd(string address, int port, int backlog) { int listenfd; int optval = 1; int ret; listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { logger::fail({"in ", __func__, ": call to socket failed"}, true); return -1; } ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)); if (ret < 0) { logger::fail({"in ", __func__, ": call to setsockopt failed"}, true); return -1; } sockaddr_in addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(config::address.c_str()); ret = bind(listenfd, (sockaddr *)&addr, sizeof addr); if (ret < 0) { logger::fail({"in ", __func__, ": call to bind failed"}, true); return -1; } ret = listen(listenfd, backlog); if (ret < 0) { logger::fail({"in ", __func__, ": call to listen falied"}, true); return -1; } return listenfd; } public: main_listener() {} ~main_listener() {} void start() { int sd_listen = openListenFd(config::address, config::port, config::backlog); if (sd_listen == -1) { logger::fail({"in ", __func__, ": call to openListenFd failed"}); exit(EXIT_FAILURE); } logger::info({"server started, listening on ", config::address, ":", to_string(config::port), ", log path: ", config::path_logger, ", debug: ", (config::debug ? "true" : "false")}); vector<thread> list_threads; while (main_app::app_state == state::start) { sockaddr_in addr_tmp; socklen_t len_addr_tmp = sizeof(addr_tmp); int sd_conn = accept(sd_listen, (sockaddr *)&addr_tmp, &len_addr_tmp); if (sd_conn == -1) { logger::fail({"in ", __func__, ": call to accept failed"}, true); return; } logger::info({"connection from: ", inet_ntoa(addr_tmp.sin_addr), " established on socket: ", to_string(sd_conn)}); list_threads.push_back(thread(&conn_handler::start, conn_handler(sd_conn, addr_tmp, len_addr_tmp))); } } }; #endif // MAIN_LISTENER_H
EricJeffrey/my_http_server
oldver_19_10/src/wrappers.h
<reponame>EricJeffrey/my_http_server #include "err_handler.h" #include "logger.h" #include <fcntl.h> #include <sys/epoll.h> #include <sys/socket.h> #include <unistd.h> #if !defined(WAPPERS_H) #define WAPPERS_H static int ret_wrapper = 0; // IO api int Close(int fd) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: close"); if ((ret_wrapper = close(fd)) == -1) errExitSimp("close failed"); return ret_wrapper; } // socket api int Socket(int domain, int type, int protocol) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: socket"); if ((ret_wrapper = socket(domain, type, protocol)) == -1) errExitSimp("create socket failed"); return ret_wrapper; } int Bind(int fd, const sockaddr *addr, socklen_t len) { if ((ret_wrapper = bind(fd, addr, len)) == -1) errExitSimp("bind failed"); return ret_wrapper; } int Listen(int fd, int backlog) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: listen"); if ((ret_wrapper = listen(fd, backlog)) == -1) errExitSimp("listen failed"); return ret_wrapper; } int Accept(int sd, sockaddr *addr, socklen_t *len) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: accept"); if ((ret_wrapper = accept(sd, addr, len)) == -1) errExitSimp("accept failed"); return ret_wrapper; } int Fcntl_NBlock(int fd) { if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) errExitSimp("fcntl nonblock failed"); } // epoll api int Epoll_create(int sz) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: epoll_create"); ret_wrapper = epoll_create(sz); if (ret_wrapper == -1) errExitSimp("epoll create failed"); return ret_wrapper; } int Epoll_ctl(int epfd, int op, int fd, epoll_event *events) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: epoll_ctl"); ret_wrapper = epoll_ctl(epfd, op, fd, events); if (ret_wrapper == -1) errExitSimp("epoll ctl failed"); return ret_wrapper; } int Epoll_wait(int epfd, epoll_event *evlist, int maxevents, int timeout) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: epoll_wait"); ret_wrapper = epoll_wait(epfd, evlist, maxevents, timeout); if (ret_wrapper == -1) { if (errno == EINTR) epoll_wait(epfd, evlist, maxevents, timeout); else errExitSimp("epoll wait failed"); } return ret_wrapper; } void Epoll_add(int epfd, int fd, uint32_t events) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: Epoll_add"); epoll_event tmpev; tmpev.events = events; tmpev.data.fd = fd; Epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &tmpev); } void Epoll_del(int epfd, int fd, uint32_t events) { LOGGER_SIMP(LOG_LV_VERBOSE, "Wrapper: Epoll_del"); epoll_event tmpev; tmpev.events = events; tmpev.data.fd = fd; Epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &tmpev); } #endif // WAPPERS_H
EricJeffrey/my_http_server
cgi_server.h
#if !defined(CGI_SERVER_H) #define CGI_SERVER_H #include "config.h" #include "logger.h" #include "response_header.h" #include "utils.h" #include <cstring> #include <fcntl.h> #include <iostream> #include <signal.h> #include <sstream> #include <string> #include <sys/stat.h> #include <unistd.h> #include <vector> #include <wait.h> using std::pair; using std::string; using std::vector; // 执行 [python3 path_prog] int startCgiProg(int fds_pipe[], const string &path_prog, const vector<string> &list_paras) { int ret = 0; close(fds_pipe[0]); string query_string; for (size_t i = 0; i < list_paras.size(); i++) { if (i != 0) query_string += '&'; query_string += list_paras[i]; } setenv(config::key_env_query_string.c_str(), query_string.c_str(), 1); ret = dup2(fds_pipe[1], STDOUT_FILENO); if (ret == -1) { logger::fail({"in ", __func__, ": call to dup2 failed"}, true); return -1; } char *path_cstr = strdup(path_prog.c_str()); char *path_exe = strdup("python3"); char *argv[] = {path_exe, path_cstr, NULL}; execvp(path_exe, argv); logger::fail({"in ", __func__, ": call to execvp failed"}, true); return -1; } // 执行 [python3 path_prog],并将标准输出的内容发送到 [sd], // -1 for error, 0 success, -2 404 int serveCgi(const string &path_prog, const vector<string> &list_paras, int sd) { int ret = 0; ret = utils::isRegFile(path_prog.c_str()); // check file accessibility if (ret == -1 || ret == 0) { logger::info({__func__, " call to utils.isRegFile failed"}); return -2; } if (access(path_prog.c_str(), F_OK | R_OK) == -1) { logger::info({__func__, " call to access failed, file not found or cannot read"}); return -2; } int fds_pipe[2]; // create pipe ret = pipe(fds_pipe); if (ret == -1) { logger::fail({"in ", __func__, ": call to pipe failed"}, true); return -1; } sigset_t mask, prev; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigprocmask(SIG_BLOCK, &mask, &prev); // start child pid_t pid_child = fork(); if (pid_child == -1) { logger::fail({"in ", __func__, ": call to fork failed"}, true); return -1; } else if (pid_child == 0) { sigprocmask(SIG_SETMASK, &prev, NULL); // child ret = startCgiProg(fds_pipe, path_prog, list_paras); if (ret == -1) { logger::fail({"in ", __func__, ": call to startCgiProg failed"}); return -1; } } else if (pid_child > 0) { // father, add child to list main_app::addChildProcess(pid_child); // close read close(fds_pipe[1]); string data; ret = utils::readAll(fds_pipe[0], data); if (ret == -1) { logger::fail({"in ", __func__, ": call to utils.readAll failed"}); return -1; } else if (ret == -2) { logger::fail({"in ", __func__, ": call to utils.readAll failed, would block!"}); return -1; } logger::debug({"cgi server, read child ", to_string(ret), " bytes"}); int status_child; sigprocmask(SIG_SETMASK, &prev, nullptr); // start waitpid ret = waitpid(pid_child, &status_child, 0); if (ret == -1) { logger::fail({"in ", __func__, ": call to waitpid failed"}, true); return -1; } // remove child main_app::removeChild(pid_child); const int exit_code_child = WEXITSTATUS(status_child); // terminated with 0 if (exit_code_child == 0 || WIFSIGNALED(status_child)) { // send response response_header header; response_header::strHeader(data, header); string resp = header.toString() + data; ret = utils::writeStr2Fd(resp, sd); if (ret == -1) { logger::fail({"in ", __func__, ": call of writeStr2Fd failed"}); return -1; } return 0; } else { logger::fail({"in ", __func__, ": cgi prog: ", path_prog, " exit with non-zero value: ", to_string(exit_code_child)}); return -1; } } return 0; } #endif // CGI_SERVER_H
EricJeffrey/my_http_server
static_server.h
<reponame>EricJeffrey/my_http_server #if !defined(STATIC_SERVER_H) #define STATIC_SERVER_H #include "config.h" #include "logger.h" #include "response_header.h" #include "utils.h" #include <sys/sendfile.h> #include <sys/socket.h> #include <sys/types.h> // write [n] bytes of [buffer] to [sd], return n or -1 int writeBufferToSocket(int sd, void *buffer, size_t n, int flags = 0) { int ret = 0; ssize_t size_sent = 0; while (size_sent < (ssize_t)n) { ret = send(sd, (char *)buffer + (ssize_t)size_sent, n - size_sent, flags); if (ret == -1) { logger::fail({"in ", __func__, ": call to send failed"}, true); return -1; } size_sent += ret; } return n; } // read from [in_fd] and [send] them on out_sd, return 0 or -1 int writeFileToSocket(int in_fd, int out_sd, const int sz_file) { int ret = 0; const int buf_size = 8192; char buffer[buf_size]; ssize_t size_sent = 0; while (size_sent < sz_file) { ret = read(in_fd, buffer, buf_size); if (ret < 0) { logger::fail({"in ", __func__, ": call to read failed"}, true); return -1; } int flags = (size_sent + ret >= sz_file ? 0 : MSG_MORE); ret = writeBufferToSocket(out_sd, buffer, ret, flags); if (ret < 0) { logger::fail({"in ", __func__, ": call to writeBufferToSocket failed"}, true); return -1; } size_sent += ret; } return 0; } // write [str_header] [fd_file] to client // won't close [sd] [fd_file] int writeFBundle2client(const string &str_header, const int sz_file, const int fd_file, const int sd) { int ret = utils::writeStr2Fd(str_header, sd); if (ret >= 0) ret = writeFileToSocket(fd_file, sd, sz_file); if (ret == -1) { logger::fail({"in ", __func__, ": call to write file fd: ", to_string(fd_file), " to client failed"}, true); return -1; } return 0; } // todo different file type // give filepath, create [header], [file_size] and **OPENED** [fd_file] // -1 for error, and fd_file is not specified int createFileBundle(const string &path_abs, string &str_header, int &sz_file, int &fd_file, int status_code = 200) { if (access(path_abs.c_str(), F_OK | R_OK) == -1) { logger::fail({"in ", __func__, ": call to access file: ", path_abs, " failed"}, true); return -1; } response_header header; response_header::fileHeader(path_abs, header, status_code); fd_file = open(path_abs.c_str(), O_RDONLY); if (fd_file == -1) { logger::fail({"in ", __func__, ": call to open ", path_abs, " failed"}, true); return -1; } struct stat file_info; int ret = fstat(fd_file, &file_info); if (ret == -1) { logger::fail({"in ", __func__, ": call to fstat failed"}, true); return -1; } str_header = header.toString(); sz_file = file_info.st_size; return 0; } // path_url has 'static/', -1 for internal error, 0 for success, -2 for 404 int serveStatic(string path_abs, const int sd) { logger::info({"start serve static file: ", path_abs}); int ret = 0; // generate header ret = utils::isRegFile(path_abs.c_str()); if (ret == -1) { // no such file logger::info({path_abs, " does not exist"}); return -2; } else if (ret == 0) { // not a regular file logger::info({path_abs, " not a regular file"}); return -2; } // create bundle string str_header; int sz_file = 0; int fd_file = 0; ret = createFileBundle(path_abs, str_header, sz_file, fd_file); if (ret == -1) { logger::fail({"in ", __func__, ": call to create file bundle failed"}); return -1; } // do all write here ret = writeFBundle2client(str_header, sz_file, fd_file, sd); if (ret == -1) { logger::fail({"in ", __func__, ": call to write file bundle failed"}); return -1; } if (close(fd_file) != -1) { logger::verbose({"response to socket: ", to_string(sd), " successfully written "}); return 0; } logger::fail({"in ", __func__, ": call to close sd or fd_file failed"}, true); return -1; } #endif // STATIC_SERVER_H
kedzie/autotools-maven-plugin
archetype/shared/src/main/resources/archetype-resources/src/main/native/hello.c
<reponame>kedzie/autotools-maven-plugin #ifdef HAVE_CONFIG_H \#include "config.h" #endif \#include "hello.h" \#include "jni-${artifactId}.h" const char * greeting(void) { return "Hello World!"; } #set( $jnipackage = $package.replace('.','_') ) JNIEXPORT jstring JNICALL Java_${jnipackage}_App_getGreeting0(JNIEnv *env, jobject thiz) { return (*env)->NewStringUTF(env, greeting()); }
kedzie/autotools-maven-plugin
it/src/it/automake-subdir/src/main/native/subdir/hello.h
#ifndef __SAY_HELLO #define __SAY_HELLO extern int say_hello(void); #endif
kedzie/autotools-maven-plugin
archetype/shared/src/main/resources/archetype-resources/src/main/native/hello.h
#ifndef __HELLO_H #define __HELLO_H extern const char *greeting(void); #endif
kedzie/autotools-maven-plugin
it/src/it/libraries/libshared-foo/src/main/native/shared-foo.c
/* * Copyright (C) 2006-2013 <NAME> <<EMAIL>> * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include "shared-foo.h" #if defined(WINDOWS) || defined(WIN32) #define DllExport __declspec(dllexport) #else #define DllExport #endif #define MIN(a,b) ((a)>(b)?(b):(a)) static const char *foo_data = "World"; int DllExport shared_foo(char *s, int n) { int p; int w = MIN(n < 0 ? strlen(s) : n, strlen(foo_data)); for (p = 0; p < w && s[p]; ++p) { s[p] = foo_data[p]; } return p; }
kedzie/autotools-maven-plugin
it/src/it/automake-subdir/src/main/native/subdir/hello.c
#include <stdio.h> #include "hello.h" int say_hello(void) { printf("Hello World\n"); return 0; }
kedzie/autotools-maven-plugin
it/src/it/libraries/bar/src/main/native/bar.c
<reponame>kedzie/autotools-maven-plugin /* * Copyright (C) 2006-2013 <NAME> <<EMAIL>> * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_DLFCN_H #include <dlfcn.h> #endif #ifdef HAVE_WINDOWS_H #include <windows.h> #endif #include <static-foo.h> #include <shared-foo.h> #define MAX(a,b) ((a)>(b)?(a):(b)) #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) void rchop_path(char *path, char *chopped) { int n = strlen(path); while ((--n) > 0 && path[n] != '/' && path[n] != '\\'); if (chopped != NULL) { strncpy(chopped, &path[n], FILENAME_MAX); } path[n] = '\0'; } void rappend_path(char *path, char *append) { int n = strlen(path); strncat(path, append, MAX(FILENAME_MAX, PATH_MAX - n)); } void make_libshared_path(char *path, char *argv0) { char chopped_os[FILENAME_MAX + 1]; char chopped_arch[FILENAME_MAX + 1]; char *rchop[] = { NULL, NULL, chopped_arch, chopped_os, NULL }; char *rappend[] = { "/dependencies", chopped_os, chopped_arch, "/lib" }; int p; strncpy(path, argv0, PATH_MAX); for (p = 0; p < ARRAY_SIZE(rchop); ++p) { rchop_path(path, rchop[p]); } for (p = 0; p < ARRAY_SIZE(rappend); ++p) { rappend_path(path, rappend[p]); } rappend_path(path, #if defined(__APPLE__) || defined(MACOSX) "/libshared-foo-1.0.bundle" #elif defined(WINDOWS) || defined(WIN32) "/libshared-foo-1-0.dll" #else "/libshared-foo-1.0.so" #endif ); } /* Just a poor man's wrapper of dlopen on top of the Windows API. */ #if (defined(WINDOWS) || defined(WIN32)) && !defined(HAVE_DLFCN_H) #define RTLD_LAZY 1 void * dlopen(char *path, int mode) { HMODULE handle = LoadLibrary(path); return (void *) handle; } void * dlsym(void* handle, char* symbol) { FARPROC address = GetProcAddress(handle, symbol); return (void *) address; } char * dlerror(void) { return ""; } #endif int main(int argc, char **argv) { char libshared[PATH_MAX + 1]; char result[] = "This failed"; void *dlp; shared_foo_t shared_foo; int n = static_foo(result, -1); result[n] = ' '; make_libshared_path(libshared, argv[0]); dlp = dlopen(libshared, RTLD_LAZY); if (dlp == NULL) { fprintf(stderr, "dlopen: %s\n", dlerror()); return -1; } shared_foo = (shared_foo_t) dlsym(dlp, "shared_foo"); if (shared_foo == NULL) { fprintf(stderr, "dlsym: %s\n", dlerror()); return -1; } shared_foo(&result[n + 1], -1); printf("%s\n", result); return 0; }
kedzie/autotools-maven-plugin
it/src/it/automake-subdir/src/main/native/main.c
#include "hello.h" int main(int argc, char **argv) { return say_hello(); }
Naimin/Zephyr
Zephyr_Common/src/Primitive/Triangle.h
#ifndef TRIANGLE_H #define TRIANGLE_H #include "Point.h" #include "Vertex.h" namespace Zephyr { namespace Common { struct ZEPHYR_COMMON_API Triangle { public: Triangle(Vertex p0 = Vertex(), Vertex p1 = Vertex(), Vertex p2 = Vertex()); Vertex getVertex(const int i) const; Vector3f computeNormal() const; Vector3f computeNormalNorm() const; float computeArea() const; Vertex mVertex[3]; }; } } #endif
Naimin/Zephyr
Zephyr_GPU/src/stdfx.h
#pragma once #ifdef ZEPHYR_GPU_EXPORTS #define ZEPHYR_GPU_API __declspec(dllexport) #else #define ZEPHYR_GPU_API __declspec(dllimport) #endif #ifndef NOMINMAX #define NOMINMAX #endif
Naimin/Zephyr
Zephyr_Algorithm/src/stdfx.h
#pragma once #ifdef ZEPHYR_ALGORITHM_EXPORTS #define ZEPHYR_ALGORITHM_API __declspec(dllexport) #else #define ZEPHYR_ALGORITHM_API __declspec(dllimport) #endif
Naimin/Zephyr
Zephyr_App/src/UI.h
#ifndef ZEPHYR_UI_H #define ZEPHYR_UI_H #include <string> #include <Eigen/Eigen> #include <unordered_map> #include <nana/gui/wvl.hpp> #include <nana/gui/widgets/label.hpp> #include <nana/gui/widgets/button.hpp> #include <nana/gui/widgets/slider.hpp> namespace Zephyr { class App; class UI { public: UI(const std::string& windowTitle, App* pApp); virtual ~UI(); bool initialize(); void show(); std::shared_ptr<nana::form> getForm(); std::shared_ptr<nana::nested_form> getNestedForm(); std::shared_ptr<nana::label> getLabel(const std::string& labelName); std::shared_ptr<nana::label> createLabel(std::shared_ptr<nana::nested_form> parent, const std::string& labelName, nana::rectangle& rect); void updateCaption(const std::string& widgetName, const std::string caption); std::shared_ptr<nana::button> getButton(const std::string& buttonName); std::shared_ptr<nana::button> createButton(std::shared_ptr<nana::nested_form> parent, const std::string& buttonName, nana::rectangle& rect); std::shared_ptr<nana::slider> getSlider(const std::string& sliderName); std::shared_ptr<nana::slider> createSlider(std::shared_ptr<nana::nested_form> parent, const std::string& sliderName, nana::rectangle& rect); protected: // mouse events void setupMouseMouseEvent(); void setupMouseClickEvent(); void setupMouseWheelEvent(); private: App* mpApp; std::shared_ptr<nana::form> mpForm; std::shared_ptr<nana::nested_form> mpNfm; // buttons std::unordered_map <std::string, std::shared_ptr<nana::widget>> mWidgetList; // mouse event data float mZoom; Eigen::Vector2i mMousePosition; }; } #endif
Naimin/Zephyr
Zephyr_Common/src/Random.h
<filename>Zephyr_Common/src/Random.h #ifndef COMMON_RANDOM_H #define COMMON_RANDOM_H #include "stdfx.h" #include "boost/random.hpp" #include "boost/generator_iterator.hpp" namespace Zephyr { namespace Common { typedef boost::mt19937 RNGType; class ZEPHYR_COMMON_API RandomGenerator { public: RandomGenerator(int min, int max, int seed); virtual ~RandomGenerator(); int next(); private: RNGType mRng; boost::uniform_int<> mRange; boost::variate_generator< RNGType, boost::uniform_int<> > mDice; }; } } #endif
Naimin/Zephyr
Zephyr_GPU/src/QueryDevice.h
<filename>Zephyr_GPU/src/QueryDevice.h #ifndef ZEPHYR_GPU_QUERY_DEVICE_H #define ZEPHYR_GPU_QUERY_DEVICE_H #include "stdfx.h" #include <vector> namespace Zephyr { namespace GPU { class ZEPHYR_GPU_API QueryDevice { public: static int getDeviceCount(); static std::string getDeviceName(const int gpuId); // MP stats static int getMultiProcessorCount(const int gpuId); static int getMaxThreadPerMultiProcessor(const int gpuId); static int getSharedMemPerMP(const int gpuId); // Grid stats static std::vector<int> getMaxGridSize(const int gpuId); // Block stats static std::vector<int> getMaxBlockSize(const int gpuId); static int getMaxThreadPerBlock(const int gpuId); static int getSharedMemPerBlock(const int gpuId); // GPU memory static int getTotalDeviceMem(const int gpuId); static int getTotalConstMem(const int gpuId); static size_t getAvailableMem(); static void printQuery(); // Util static int computeOptimalBlockCount(const int workSize, const int threadPerBlock, const int gpuId); }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/IRenderPass.h
#ifndef RENDER_PASS_H #define RENDER_PASS_H #include "stdfx.h" #include "ShaderManager.h" #include "CommandList.h" namespace Zephyr { namespace Graphics { class Renderer; } } namespace Zephyr { namespace Graphics { class GraphicsEngine; class CommandList; class ZEPHYR_GRAPHICS_API IRenderPass : public CommandList { public: IRenderPass(const int frameBufferCount, GraphicsEngine* pEngine); virtual ~IRenderPass(); virtual bool initialize() = 0; virtual void update(const int frameIndex, const double deltaTime) = 0; protected: virtual bool setupViewport(); protected: D3D12_VIEWPORT mViewport; // area that output from rasterizer will be stretched to. D3D12_RECT mScissorRect; // the area to draw in. pixels outside that area will not be drawn onto }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Camera.h
<reponame>Naimin/Zephyr<filename>Zephyr_Common/src/Camera.h #ifndef CAMERA_H #define CAMERA_H #include "stdfx.h" namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API Camera { public: Camera(); ~Camera(); void intialize(const Common::Vector3f& cameraPos, const Common::Vector3f& cameraTarget, const Common::Vector3f& cameraUp, const float fov, // in radian const float nearClip, const float farClip, const int screenWidth, const int screenHeight); void updatePerspectiveMatrix(const float fov, // in radian const float aspectRatio, const float nearClip, const float farClip); void updateViewMatrix(const Common::Vector3f& cameraPos, const Common::Vector3f& cameraTarget, const Common::Vector3f& cameraUp); void zoom(const float distance); void pan(const float deltaX, const float deltaY); void rotation(const float degreeX, const float degreeY); Common::Vector3f getViewDirection() const; Common::Vector3f getPickingRay(const int mouseX, const int mouseY) const; public: Common::Vector3f mCameraPos; Common::Vector3f mCameraTarget; Common::Vector3f mCameraUp; Common::Vector3f mPolarCoord; // Radius, Latitude, Azimuth float mFOV; // radian float mNearClip; float mFarClip; float mAspectRatio; Eigen::Matrix4f mPerspectiveMatrix; Eigen::Matrix4f mViewMatrix; int mScreenWidth; int mScreenHeight; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Mesh/Texture.h
<gh_stars>1-10 #ifndef TEXTURE_H #define TEXTURE_H #include "../stdfx.h" #include <FreeImagePlus.h> #include <boost/filesystem/path.hpp> namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API Texture { public: Texture(); Texture(const boost::filesystem::path& path); virtual ~Texture(); bool isValid() const; boost::filesystem::path getPath() const; fipImage getRawData(); protected: bool loadFromFile(const boost::filesystem::path& path); private: bool bValid; boost::filesystem::path mPath; fipImage mFreeImageData; }; } } #endif
Naimin/Zephyr
Zephyr_Algorithm/src/Decimate/QuadricError.h
<filename>Zephyr_Algorithm/src/Decimate/QuadricError.h #ifndef ZEPHYR_ALGORITHM_QUADRIC_ERROR_H #define ZEPHYR_ALGORITHM_QUADRIC_ERROR_H #include "../stdfx.h" #include <Mesh/OM_Mesh.h> #include <OpenMesh/Core/Geometry/QuadricT.hh> #include <OpenMesh/Tools/Decimater/CollapseInfoT.hh> #include <vector> /// Quadric using double typedef OpenMesh::Geometry::QuadricT<double> QuadricD; typedef OpenMesh::Decimater::CollapseInfoT<Zephyr::Common::OMMesh> CollapseInfo; namespace Zephyr { namespace Algorithm { const float INVALID_COLLAPSE = 10000.0f; // super big error, so the std::map always place it last class ZEPHYR_ALGORITHM_API QuadricError { public: static float computeQuadricError(HalfedgeHandle halfEdgeHandle, Common::OpenMeshMesh& mesh, float maxError, float maxAngle); static QuadricD computeQuadricForFace(FaceHandle faceHandle, Common::OpenMeshMesh& mesh); static QuadricD computeQuadricForVertex(VertexHandle vertexHandle, Common::OpenMeshMesh& mesh); static float computeTriangleFlipAngle(CollapseInfo& collapseInfo, Common::OpenMeshMesh& mesh, float maxAngle); static float computeTriangleFlipAngle(CollapseInfo & collapseInfo, Common::OMMesh & omesh, float maxAngle); private: float mMaxError; }; } } #endif
Naimin/Zephyr
Zephyr_Algorithm/src/Decimate/Decimate.h
#ifndef ZEPHYR_ALGORITHM_DECIMATE_H #define ZEPHYR_ALGORITHM_DECIMATE_H #include "../stdfx.h" #include <Mesh/OM_Mesh.h> namespace Zephyr { namespace Algorithm { enum DecimationType { GREEDY_DECIMATE = 0, RANDOM_DECIMATE, RANDOM_DECIMATE_VERTEX, ADAPTIVE_RANDOM_DECIMATE, GPU_RANDOM_DECIMATE, GPU_SUPER_VERTEX }; class ZEPHYR_ALGORITHM_API Decimater { public: static int decimate(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount,int binSize, DecimationType type = GREEDY_DECIMATE); static int decimateGreedy(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount); static int decimateRandom(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount, unsigned int binSize = 8); static int decimateRandomVertex(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount, unsigned int binSize = 8); static int decimateAdaptiveRandom(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount, unsigned int binSize = 8); }; } } #endif
Naimin/Zephyr
Zephyr_Algorithm/src/Segmentation/iDualGraph.h
#ifndef I_DUAL_GRAPH_H #define I_DUAL_GRAPH_H #include "../stdfx.h" #include <vector> #include <algorithm> namespace Zephyr { namespace Algorithm { template <class NodeType, class EdgeType> class ZEPHYR_ALGORITHM_API DualGraph { public: struct Node { Node(const NodeType data_) : data(data_) {} NodeType data; std::vector<int> edgeIds; }; struct Edge { Edge() {} Edge(const EdgeType data_) : data(data_) {} EdgeType data; std::vector<int> nodeIds; }; DualGraph() {} ~DualGraph() {} // access both node and edge by id Node& getNode(const int id) { return mNodes[id]; } Node getNode(const int id) const { return mNodes[id]; } Edge& getEdge(const int id) { return mEdges[id]; } Edge getEdge(const int id) const { return mEdges[id]; } // construction function int addNode(const NodeType& data) { mNodes.push_back(Node(data)); return (int)mNodes.size() - 1; // return new node id } int addEdge() { mEdges.push_back(Edge()); return (int)mEdges.size() - 1; } int addEdge(const EdgeType& data) { mEdges.push_back(Edge(data)); return (int)mEdges.size() - 1; // return new edge id } int linkNodes(const int currentNodeId, const int linkNodeId) { if (currentNodeId == linkNodeId) { std::cout << "Attempting to link the same node to itself"; return -1; } Node& currentNode = mNodes[currentNodeId]; Node& linkNode = mNodes[linkNodeId]; // create a new edge int edgeId = addEdge(); Edge& edge = getEdge(edgeId); // if edge don't already exist in this node if (std::find(currentNode.edgeIds.begin(), currentNode.edgeIds.end(), edgeId) == currentNode.edgeIds.end()) currentNode.edgeIds.push_back(edgeId); if (std::find(linkNode.edgeIds.begin(), linkNode.edgeIds.end(), edgeId) == linkNode.edgeIds.end()) linkNode.edgeIds.push_back(edgeId); // since it is a new edge no need to check if edges exist. edge.nodeIds.push_back(currentNodeId); edge.nodeIds.push_back(linkNodeId); return edgeId; } // transverse utility std::vector<int> getNeighbourNodeId(const int id) const { const Node& currentNode = mNodes[id]; std::vector<int> neighbour; for (auto edgeId : currentNode.edgeIds) { for (auto nodeId : mEdges[edgeId].nodeIds) { // if not current/self id if (nodeId != id) neighbour.push_back(nodeId); } } return neighbour; } std::vector<Edge> getNeighbourEdges(const int id) const { const Node& currentNode = mNodes[id]; std::vector<Edge> neighbour; for (auto edgeId : currentNode.edgeIds) { neighbour.push_back(getEdge(edgeId)); } return neighbour; } protected: std::vector<Node> mNodes; std::vector<Edge> mEdges; }; typedef std::pair<int, int> EdgeIdPair; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/ResourceManager.h
<gh_stars>1-10 #ifndef RESOURCE_MANAGER_H #define RESOURCE_MANAGER_H #include "stdfx.h" #include "CommandQueue.h" namespace Zephyr { namespace Graphics { class GraphicsEngine; class ZEPHYR_GRAPHICS_API ResourceManager { public: enum RESOURCE_TYPE { DEFAULT = 1, // GPU read/write, no CPU UPLOAD, // GPU read, CPU write READ_BACK, // GPU write, CPU read }; public: ResourceManager(GraphicsEngine* pGraphicsEngine); virtual ~ResourceManager(); bool initialize(); SharedPtr<ID3D12Resource> createResource(const std::wstring & resourceName, int bufferSize, RESOURCE_TYPE type, D3D12_RESOURCE_DESC* description = nullptr); SharedPtr<ID3D12Resource> createDepthStencilResource(const std::wstring & resourceName, D3D12_CLEAR_VALUE& clearValue); bool copyDataToResource(const std::wstring& toResourceName, const std::wstring& fromResourceName, int bufferSize, void* pData, int rowPitch = -1, int height = -1); bool createAndCopyToGPU(const std::wstring& resourceName, int bufferSize, void* pData, int rowPitch = -1, int height = -1); bool createTextureAndCopyToGPU(const std::wstring& resourceName, D3D12_RESOURCE_DESC* description, int bufferSize, void* pData, int rowPitch = -1, int height = -1); bool copyTextureToResource(const std::wstring& toResourceName, const std::wstring& fromResourceName, int bufferSize, void* pData, int rowPitch = -1, int height = -1); SharedPtr<ID3D12Resource> getResource(const std::wstring& resourceName); void releaseResource(const std::wstring& resourceName); void waitForPreviousTask(); D3D12_VERTEX_BUFFER_VIEW getVertexResourceView(const std::wstring & resourceName, const int stride); D3D12_INDEX_BUFFER_VIEW getIndexResourceView(const std::wstring & resourceName); GraphicsEngine* getEngine(); protected: bool createCommandQueue(); private: GraphicsEngine* mpGraphicsEngine; std::unordered_map<std::wstring, SharedPtr<ID3D12Resource>> mResources; std::unordered_map<std::wstring, int> mResourceSize; std::shared_ptr<CommandQueue> mpCommandQueue; // container for command lists std::map<std::string, CommandList> mCommands; // command to copy resources Fence mFence; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/ShaderManager.h
<filename>Zephyr_Graphics/src/ShaderManager.h<gh_stars>1-10 #ifndef SHADER_MANAGER_H #define SHADER_MANAGER_H #include "stdfx.h" namespace Zephyr { namespace Graphics { class ZEPHYR_GRAPHICS_API ShaderManager { public: enum SHADER_TYPE { VERTEX = 0, PIXEL }; ShaderManager(); virtual ~ShaderManager(); D3D12_SHADER_BYTECODE getOrCreateShader(const std::wstring& shaderPath, const std::wstring& shaderName, SHADER_TYPE type); bool createShader(const std::wstring& shaderPath, const std::wstring& shaderName, SHADER_TYPE type); D3D12_SHADER_BYTECODE getShader(const std::wstring& shaderName); private: std::unordered_map<std::wstring, D3D12_SHADER_BYTECODE> mShaderByteCode; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Timer.h
<filename>Zephyr_Common/src/Timer.h #ifndef COMMON_TIMER_H #define COMMON_TIMER_H #include "stdfx.h" #include <chrono> namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API Timer { public: Timer(const std::string& name=""); virtual ~Timer(); double getElapsedTime(); // Time since creation of the Timer double getDeltaTime(); // Time since last call to this function double getTimeDifference(const std::chrono::high_resolution_clock::time_point& startTime, const std::chrono::high_resolution_clock::time_point& endTime); void reportTime(); private: std::string mName; std::chrono::high_resolution_clock::time_point mStartTime; std::chrono::high_resolution_clock::time_point mPrevDeltaTime; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/Zephyr_Graphics.h
<filename>Zephyr_Graphics/src/Zephyr_Graphics.h #ifndef ZEPHYR_GRAPHICS_H #define ZEPHYR_GRAPHICS_H #include "stdfx.h" #include "Renderer.h" #include "ShaderManager.h" #include "ResourceManager.h" namespace Zephyr { namespace Graphics { class BasicRenderPass; class ZEPHYR_GRAPHICS_API GraphicsEngine { public: GraphicsEngine(); virtual ~GraphicsEngine(); bool initialize(unsigned int backBufferWidth, unsigned int backBufferHeight, HWND& hwnd, bool bFullScreen); bool setupRenderPass(IRenderPass* pRenderPass, const std::string& passName); void cleanup(); void update(); void render(); void waitForPreviousFrame(); public: // Accessor bool isRunning() const; std::shared_ptr<Renderer> getRenderer() const; std::shared_ptr<ShaderManager> getShaderManager() const; std::shared_ptr<ResourceManager> getResourceManager() const; unsigned int getWidth() const; unsigned int getHeight() const; private: unsigned int mBackBufferWidth, mBackBufferHeight; bool mbFullScreen; bool mbIsRunning; std::shared_ptr<Renderer> mpRenderer; std::shared_ptr<ShaderManager> mpShaderManager; std::shared_ptr<ResourceManager> mpResourceManager; std::vector<IRenderPass*> mRenderPasses; BasicRenderPass* mpRenderPass; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/CommandQueue.h
<filename>Zephyr_Graphics/src/CommandQueue.h #ifndef COMMAND_QUEUE_H #define COMMAND_QUEUE_H #include "stdfx.h" #include "CommandList.h" #include "IRenderPass.h" namespace Zephyr { namespace Graphics { enum COMMAND_QUEUE_TYPE { DIRECT = 0, BUNDLE = 1, COMPUTE = 2, COPY = 3 }; class ZEPHYR_GRAPHICS_API CommandQueue { public: CommandQueue(const int id, COMMAND_QUEUE_TYPE type, SharedPtr<ID3D12Device> pDevice); virtual ~CommandQueue(); bool enqueueCommandList(std::shared_ptr<CommandList> pCommandList); void update(const int frameIndex, const double deltaTime); bool execute(const int frameIndex); void clear(); void wait(); public: SharedPtr<ID3D12CommandQueue> getCommandQueue() const; std::shared_ptr<CommandList> getCommandList(const int index) const; SharedPtr<ID3D12Device> getDevice() const; protected: int mId; SharedPtr<ID3D12Device> mpDevice; SharedPtr<ID3D12CommandQueue> mpCommandQueue; std::vector<std::shared_ptr<CommandList>> mCommandLists; // list of command lists Fence mFence; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Mesh/Material.h
#ifndef MATERIAL_H #define MATERIAL_H #include "../stdfx.h" #include "Texture.h" namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API Material { public: Material(boost::filesystem::path path = boost::filesystem::path(""), std::string name = std::string()); virtual ~Material(); boost::filesystem::path& getPath(); std::string mName; boost::filesystem::path mPath; Vector3f mAmbientColor; Vector3f mEmissiveColor; Vector3f mDiffuseColor; Vector3f mSpecularColor; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Mesh/OM_Mesh.h
#ifndef OM_MESH_H #define OM_MESH_H #include "../stdfx.h" #include <OpenMesh/Core/IO/MeshIO.hh> // Wrapper class foor OpenMesh half-edge mesh representation #include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh> #include <OpenMesh/Core/Mesh/TriMeshT.hh> #include "Mesh.h" using namespace OpenMesh; struct ZephyrTraits : public OpenMesh::DefaultTraits { VertexAttributes(OpenMesh::Attributes::Status); FaceAttributes(OpenMesh::Attributes::Status|OpenMesh::Attributes::Normal); EdgeAttributes(OpenMesh::Attributes::Status); HalfedgeAttributes(OpenMesh::Attributes::Status); }; namespace Zephyr { namespace Common { // define traits typedef OpenMesh::TriMesh_ArrayKernelT<ZephyrTraits> OMMesh; class ZEPHYR_COMMON_API OpenMeshMesh { public: OpenMeshMesh(); // take in a Zephyr::Graphics::Mesh and build half edge OpenMeshMesh(Common::Mesh &mesh); OpenMeshMesh(const std::string& path); virtual ~OpenMeshMesh(); void loadMesh(Common::Mesh& mesh); OMMesh& getMesh(); bool exports(const std::string& path); protected: OMMesh mMesh; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/CommandList.h
<gh_stars>1-10 #ifndef COMMAND_LIST_H #define COMMAND_LIST_H #include "stdfx.h" #include "Fence.h" namespace Zephyr { namespace Graphics { class GraphicsEngine; class CommandQueue; class Pipeline; // wrapper over directx commandList class ZEPHYR_GRAPHICS_API CommandList { public: CommandList(const int frameBufferCount, GraphicsEngine* pEngine); virtual ~CommandList(); virtual void update(const int frameIndex, const double deltaTime); virtual bool startRecording(const int frameIndex); virtual bool endRecording(const int frameIndex); void signal(const int frameIndex, SharedPtr<ID3D12CommandQueue> pCommandQueue); // allow GPU to signal bool ready(); // check if the command list is ready to execute public: ID3D12GraphicsCommandList* getCommandList(); ID3D12PipelineState* getPipelineState() const; protected: bool createCommandAllocator(const int frameBufferCount); bool createCommandList(); bool createFence(const int frameBufferCount); protected: int mFrameBufferCount; bool bClosed; GraphicsEngine* mpEngine; SharedPtr<ID3D12Device> mpDevice; std::vector<ID3D12CommandAllocator*> mCommandAllocators; // we want enough allocators for each buffer * number of threads (we only have one thread) SharedPtr<ID3D12GraphicsCommandList> mpCommandList; // list of all available command list we can record commands into, then execute them to render the frame std::shared_ptr<Pipeline> mpPipelineState; // pso containing a pipeline state // for synchronization std::vector<std::shared_ptr<Fence>> mFences; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/TestRenderPass.h
<reponame>Naimin/Zephyr<gh_stars>1-10 #ifndef TEST_RENDER_PASS_H #define TEST_RENDER_PASS_H #include "IRenderPass.h" namespace Zephyr { namespace Graphics { class ZEPHYR_GRAPHICS_API TestRenderPass : public IRenderPass { public: TestRenderPass(const int frameBufferCount, GraphicsEngine* pEngine); virtual ~TestRenderPass(); void setClearColor(float r, float g, float b, float a); virtual bool initialize(); virtual void update(const int frameIndex, const double deltaTime); protected: float clearColor[4]; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/RenderableModel.h
<filename>Zephyr_Graphics/src/RenderableModel.h #ifndef RENDERABLE_MODEL_H #define RENDERABLE_MODEL_H #include "stdfx.h" #include <Mesh/Model.h> #include <Mesh/Material.h> namespace Zephyr { namespace Graphics { class CommandList; class ResourceManager; class OpenMeshMesh; // class of renderable model class ZEPHYR_GRAPHICS_API RenderableModel : public Common::Model { public: // HACK RenderableModel(const std::wstring& name) : mpResourceManager(nullptr) {} // HACK end RenderableModel(const std::wstring& name, ResourceManager* pResourceManager); virtual ~RenderableModel(); D3D12_VERTEX_BUFFER_VIEW getVertexResourceView(const int meshId); D3D12_INDEX_BUFFER_VIEW getIndexResourceView(const int meshId); bool loadFromFile(const std::string& path); bool loadOpenMesh(const OpenMeshMesh & mesh); bool uploadToGPU(); void unloadFromGPU(); bool drawMesh(const int meshId, SharedPtr<ID3D12GraphicsCommandList> pCommandList); protected: std::wstring getVertexResourceName(const int meshId) const; std::wstring getIndexResourceName(const int meshId) const; bool uploadVerticesToGPU(const int meshId); bool uploadIndicesToGPU(const int meshId); bool uploadTextureToGPU(const int materialId); private: ResourceManager* mpResourceManager; std::wstring mPath; std::wstring mName; // each material will have a mesh std::vector<ID3D12DescriptorHeap*> mTextureHeap; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Mesh/Model.h
<filename>Zephyr_Common/src/Mesh/Model.h #ifndef MODEL_H #define MODEL_H #include "Material.h" #include "Mesh.h" #include <vector> namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API Model { public: Model(); virtual ~Model(); // Mesh Accessor void addMesh(Mesh& mesh); Mesh& getMesh(const int i); const Mesh& getMesh(const int i) const; std::vector<Mesh>& getMeshes(); const std::vector<Mesh>& getMeshes() const; void resizeMeshes(const int size); int getMeshesCount() const; // Material Accessor void addMaterial(Material& material); Material& getMaterial(const int i); const Material& getMaterial(const int i) const; std::vector<Material>& getMaterials(); const std::vector<Material>& getMaterials() const; void resizeMaterial(const int size); int getMaterialsCount() const; // Texture Accessor void addTexture(const boost::filesystem::path& texturePath); Texture& getTexture(const int i); const Texture& getTexture(const int i) const; std::vector<Texture>& getTextures(); const std::vector<Texture>& getTextures() const; void resizeTexture(const int size); int getTexturesCount() const; protected: std::vector<Mesh> mMeshes; std::vector<Material> mMaterials; std::vector<Texture> mTextures; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/Renderer.h
#ifndef RENDERER_H #define RENDERER_H #include "stdfx.h" #include "IRenderPass.h" #include "CommandQueue.h" #include <Timer.h> namespace Zephyr { namespace Graphics { const int FRAME_BUFFER_COUNT = 3; // triple buffering class GraphicsEngine; class ZEPHYR_GRAPHICS_API Renderer { public: Renderer(GraphicsEngine* pEngine); virtual ~Renderer(); // function declarations bool initialize(unsigned int backBufferWidth, unsigned int backBufferHeight, HWND& hwnd, bool bFullscreen); // initializes direct3d 12 // Render Pass management void addRenderPass(const std::string& renderPassName, IRenderPass* pRenderPass); // update the direct3d pipeline (update command lists) // automatically create new command list when queue index is higher current command list count bool enqueuRenderPass(const std::string& renderPassName, const int queueIndex); void clearRenderPassQueue(const int queueIndex); std::shared_ptr<Graphics::IRenderPass> getRenderPass(const std::string& renderPassName); bool enqueueUIRenderPass(const std::string& renderPassName, const int queueIndex); void clearUIRenderPassQueue(const int queueIndex); void render(); // execute the command list void waitForPreviousFrame(); // wait until gpu is finished with command list public: // accessor bool isRunning() const; SharedPtr<ID3D12Device> getDevice() const; SharedPtr<ID3D12DescriptorHeap> getDescriptionHeap() const; int getFrameIndex() const; int getRtvDescriptorSize() const; //SharedPtr<ID3D12CommandQueue> getCommandQueue() const; //std::shared_ptr<CommandList> getCommandList(const int Id) const; //int getCommandListCount() const; std::vector<ID3D12Resource*> getRenderTargets() const; DXGI_SAMPLE_DESC getSampleDesc() const; protected: bool createDevice(); bool createCommandQueue(); bool createUICommandQueue(); bool createSwapChain(HWND& hwnd, bool bFullScreen); bool createRenderTargetView(); bool createFence(); void cleanup(); // release com ojects and clean up memory private: GraphicsEngine* mpEngine; bool bIsRunning; unsigned int mBackBufferWidth, mBackBufferHeight; SharedPtr<IDXGIFactory4> mpDxgiFactory; SharedPtr<ID3D12Device> mpDevice; // direct3d device SharedPtr<IDXGISwapChain3> mpSwapChain; // swapchain used to switch between render targets SharedPtr<ID3D12DescriptorHeap> mpRtvDescriptorHeap; // a descriptor heap to hold resources like the render targets std::vector<ID3D12Resource*> mRenderTargets; // number of render targets equal to buffer count std::vector<std::shared_ptr<CommandQueue>> mCommandQueues; // std::vector<std::shared_ptr<CommandQueue>> mUICommandQueues; // Command queue for UI render, ie this is rendered last int mFrameIndex; // current rtv we are on int mRtvDescriptorSize; // size of the rtv descriptor on the device (all front and back buffers will be the same size) std::vector<std::shared_ptr<Fence>> mFences; // std::unordered_map <std::string, std::shared_ptr<IRenderPass>> mRenderPassMap; // storage for Render Pass DXGI_SAMPLE_DESC mSampleDesc; Common::Timer mTimer; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/SharedPtr.h
<filename>Zephyr_Graphics/src/SharedPtr.h #ifndef SHARED_POINTER_H #define SHARED_POINTER_H // Specialized std::shared_ptr that call directx12 Release() instead of delete #include "stdfx.h" // this will only call release if an object exists (prevents exceptions calling release on non existant objects) #define SAFE_RELEASE(p) { if ( (p) ) { (p)->Release(); (p) = 0; } } namespace Zephyr { template <typename T> struct Releaser { void operator()(T* p) { if (nullptr != p) { SAFE_RELEASE(p) } }; }; template <typename T> struct SharedPtr { SharedPtr(T* p = nullptr) { mPtr = std::shared_ptr<T>(p, Releaser<T>()); } ~SharedPtr() { mPtr.reset(); } void reset(T* p) { auto ptr = std::shared_ptr<T>(p, Releaser<T>()); mPtr = ptr; } void reset() { mPtr.reset(); } T* get() const { return mPtr.get(); } T* operator->() { return mPtr.operator->(); } bool operator==(T* p) { return mPtr == p; } // HACK: couldn't figure out operator== bool isNull() { return nullptr == mPtr; } std::shared_ptr<T> mPtr; }; } #endif
Naimin/Zephyr
Zephyr_GPU/src/Algorithm/QEM_Data.h
<gh_stars>1-10 #ifndef ZEPHYR_GPU_OpenMesh_H #define ZEPHYR_GPU_OpenMesh_H #include "../stdfx.h" #include <Mesh/OM_Mesh.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/system/cuda/experimental/pinned_allocator.h> namespace Zephyr { namespace GPU { typedef unsigned char INDEX_TYPE; struct SortVector3f : public Common::Vector3f { SortVector3f(float x=0, float y=0, float z=0) : Common::Vector3f(x, y, z) {} bool operator<(const SortVector3f& b) const { return std::tie(x(), y(), z()) < std::tie(b.x(), b.y(), b.z()); } }; const INDEX_TYPE MAX_VALENCE = 32; const INDEX_TYPE MAX_FACE = 48; struct QEM_Data { QEM_Data() : bValid(true), vertexCount(0), indexCount(0), vertexToKeepId(-1) {} Common::Vector3f vertices[MAX_VALENCE]; // vertex buffer INDEX_TYPE indices[MAX_FACE*3]; // all the faces formed INDEX_TYPE vertexCount; INDEX_TYPE indexCount; INDEX_TYPE vertexToKeepId; bool bValid; void reset() { bValid = true; vertexCount = 0; indexCount = 0; vertexToKeepId = -1; } }; typedef thrust::host_vector<QEM_Data, thrust::system::cuda::experimental::pinned_allocator<QEM_Data>> QEM_Data_List; typedef thrust::host_vector<int, thrust::system::cuda::experimental::pinned_allocator<int>> Thrust_host_vector_int; struct QEM_Data_Package { QEM_Data_Package(size_t numQEM_Data); QEM_Data_Package(QEM_Data_List& QEM_Datas); void setup(QEM_Data_List& QEM_Datas); QEM_Data* getDevicePtr(); ~QEM_Data_Package(); // device ptr thrust::device_vector<QEM_Data> mQEM_Data_GPU; }; struct CopyPartialMesh { CopyPartialMesh(size_t totalSelectionCount); QEM_Data* copyPartialMesh(Common::OMMesh& mesh, const Thrust_host_vector_int& randomList); protected: void collectOneRingNeighbour(VertexHandle vh, Common::OMMesh & mesh, Common::Vector3f* vertexBuffer, INDEX_TYPE& vertexCount, INDEX_TYPE* indexBuffer, INDEX_TYPE& indexCount, std::map<SortVector3f, INDEX_TYPE>& uniqueVertex); QEM_Data_List mQEM_Data; QEM_Data_Package mQEM_Data_Package; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Utils/CoordinateConvertor.h
<reponame>Naimin/Zephyr #ifndef COORDINATE_CONVERTOR_H #define COORDINATE_CONVERTOR_H #include "stdfx.h" #include <cmath> namespace Zephyr { namespace Common { const float PI = 3.14159265358979323846f; const float PI_OVER_180 = PI / 180.0f; const float OVER_180_PI = 180.0f / PI; struct ZEPHYR_COMMON_API CoordinateConvertor { // polar coordinate is R, Inclination angle, azimuth angle static Common::Vector3f CartesianToPolar(const Common::Vector3f& cartesianVec) { Common::Vector3f polar; polar.x() = cartesianVec.norm(); polar.y() = std::acos(cartesianVec.z() / polar.x()); polar.z() = std::atan2f(cartesianVec.y(), cartesianVec.x()); return polar; } static Common::Vector3f PolarToCartesian(const Common::Vector3f& polarVec) { Common::Vector3f cartesian; cartesian.x() = polarVec.x() * std::cos(polarVec.y()) * std::sin(polarVec.z()); cartesian.y() = polarVec.x() * std::sin(polarVec.y()) * std::sin(polarVec.z()); cartesian.z() = polarVec.x() * std::cos(polarVec.z()); return cartesian; } static float RadianToDegree(const float radian) { return radian * OVER_180_PI; } static float DegreeToRadian(const float degree) { return degree * PI_OVER_180; } }; } } #endif
Naimin/Zephyr
Zephyr_GPU/src/Algorithm/Decimate.h
<gh_stars>1-10 #ifndef ZEPHYR_GPU_ALGORITHM_DECIMATE_H #define ZEPHYR_GPU_ALGORITHM_DECIMATE_H #include "../stdfx.h" #include <Decimate/Decimate.h> namespace Zephyr { namespace GPU { int ZEPHYR_GPU_API decimate(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount, unsigned int binSize, Algorithm::DecimationType type); int ZEPHYR_GPU_API decimateMC(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount, unsigned int binSize); int ZEPHYR_GPU_API decimateSuperVertex(Common::OpenMeshMesh& mesh, unsigned int targetFaceCount, unsigned int binSize); } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/StringUtils.h
<filename>Zephyr_Graphics/src/StringUtils.h #ifndef STRING_UTILS_H #define STRING_UTILS_H #include <locale> #include <codecvt> #include <string> namespace Zephyr { namespace Utils { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; } } #endif
Naimin/Zephyr
Zephyr_Common/src/stdfx.h
<filename>Zephyr_Common/src/stdfx.h #pragma once #ifdef ZEPHYR_COMMON_EXPORTS #define ZEPHYR_COMMON_API __declspec(dllexport) #else #define ZEPHYR_COMMON_API __declspec(dllimport) #endif #ifndef NOMINMAX #define NOMINMAX #endif #include "GeometryMath.h"
Naimin/Zephyr
Zephyr_Common/src/Primitive/Line.h
#ifndef Line_H #define Line_H #include "Point.h" namespace Zephyr { namespace Common { struct Line { Line(const Point p1 = Point(), const Point p2 = Point()) { mPoint[0] = p1; mPoint[1] = p2; } Point mPoint[2]; }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/stdfx.h
<gh_stars>1-10 #pragma once #ifdef ZEPHYR_GRAPHICS_EXPORTS #define ZEPHYR_GRAPHICS_API __declspec(dllexport) #else #define ZEPHYR_GRAPHICS_API __declspec(dllimport) #endif #include <memory> #include <functional> #include <map> #include <vector> #include <unordered_map> #include <iostream> // custom shared_ptr for directX resource #include "SharedPtr.h" #include <d3d12.h> #include <dxgi1_4.h> #include <d3dcompiler.h> #include <DirectXMath.h> #include "d3dx12.h" #include <d3d12sdklayers.h>
Naimin/Zephyr
Zephyr_App/src/App.h
#ifndef ZEPHYR_APP_H #define ZEPHYR_APP_H #include <Zephyr_Graphics.h> #include <Camera.h> namespace Zephyr { const std::string DEFAULT_RENDERPASS_NAME = "BasicRenderPass"; class UI; class AppEvents; class Common::Camera; class App { public: App(const std::string& windowTitle, unsigned int width = 800, unsigned int height = 600, bool bFullScreen = false); virtual ~App(); bool initialize(); bool start(); std::shared_ptr<Graphics::GraphicsEngine> getGraphicsEngine(); std::shared_ptr<UI> getUI(); std::shared_ptr<Common::Camera> getCamera(); HWND& getHwnd(); unsigned int getWidth() const; unsigned int getHeight() const; private: std::shared_ptr<Graphics::GraphicsEngine> mpEngine; std::shared_ptr<UI> mpUI; std::shared_ptr<AppEvents> mpAppEvents; std::shared_ptr<Common::Camera> mpCamera; HWND mHwnd; unsigned int mWidth; unsigned int mHeight; bool mbFullScreen; }; } #endif
Naimin/Zephyr
Zephyr_Common/src/IO/MeshExporter.h
<reponame>Naimin/Zephyr #ifndef MESH_EXPORTER_H #define MESH_EXPORTER_H #include "../stdfx.h" #include "../Mesh/Model.h" namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API MeshExporter { public: MeshExporter(); virtual ~MeshExporter(); static bool exportMesh(const std::string& path, Model* pModel); }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/MeshConverter.h
#ifndef MESH_CONVERTER_H #define MESH_CONVERTER_H #include "stdfx.h" #include "Mesh/Model.h" namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API MeshLoader { public: MeshLoader(); virtual ~MeshLoader(); static bool loadFile(const std::string& path, Model* pModel); }; } } #endif
Naimin/Zephyr
Zephyr_Algorithm/src/Segmentation/MeshSegmentation.h
<filename>Zephyr_Algorithm/src/Segmentation/MeshSegmentation.h<gh_stars>1-10 #ifndef MESH_SEGMENTATION_H #define MESH_SEGMENTATION_H namespace Zephyr { namespace Algorithm { class MeshSegmentation { public: MeshSegmentation(); virtual ~MeshSegmentation(); protected: }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/GeometryMath.h
<reponame>Naimin/Zephyr #ifndef GEOMETRY_MATH_H #define GEOMETRY_MATH_H #include <Eigen/Eigen> // this interface so we can easily switch out the math library if we want to namespace Zephyr { namespace Common { typedef Eigen::Vector2f Vector2f; typedef Eigen::Vector3f Vector3f; typedef Eigen::Vector4f Vector4f; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Utils/LNormUtil.h
<reponame>Naimin/Zephyr #ifndef L_NORM_UTIL_H #define L_NORM_UTIL_H #include "../stdfx.h" #include <algorithm> #include <cmath> namespace Zephyr { namespace Common { struct ZEPHYR_COMMON_API LNormUtil { static float L1Norm(const Vector3f vec); static float L2Norm(const Vector3f vec); static float LInfinityNorm(const Vector3f vec); }; } } #endif
Naimin/Zephyr
Zephyr_GPU/src/Zephyr_GPU.h
<gh_stars>1-10 #include "stdfx.h" void ZEPHYR_GPU_API dummy();
Naimin/Zephyr
Zephyr_Common/src/Primitive/Vertex.h
<reponame>Naimin/Zephyr<filename>Zephyr_Common/src/Primitive/Vertex.h<gh_stars>1-10 #ifndef VERTEX_H #define VERTEX_H #include "../stdfx.h" namespace Zephyr { namespace Common { struct ZEPHYR_COMMON_API Vertex { Vertex(float x = -1.0f, float y = -1.0f, float z = -1.0f, float nx = -1.0f, float ny = -1.0f, float nz = -1.0f, float u = -1.0f, float v = -1.0f); bool operator==(const Vertex& rhs); bool operator!=(const Vertex& rhs); bool operator<(const Vertex& rhs); Vector4f pos; Vector4f color; Vector3f normal; Vector2f uv; }; ZEPHYR_COMMON_API bool operator<(const Vertex& lhs, const Vertex& rhs); ZEPHYR_COMMON_API bool operator==(const Vertex& lhs, const Vertex& rhs); } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/Fence.h
#ifndef FENCE_H #define FENCE_H #include "stdfx.h" namespace Zephyr { namespace Graphics { class CommandQueue; class ZEPHYR_GRAPHICS_API Fence { public: Fence(SharedPtr<ID3D12Device> pDevice); virtual ~Fence(); UINT64 current(); // get current value; void increment(); // increment fence value void signal(); // CPU signal bool signal(SharedPtr<ID3D12CommandQueue> pCommandQueue); // GPU signal // non-blocking check bool isDone(); // blocking void waitForFence(); void waitAndIncrement(); public: ID3D12Fence* mFence; UINT64 mFenceValue; HANDLE mFenceEvent; }; } } #endif
Naimin/Zephyr
Zephyr_Algorithm/src/Segmentation/TriDualGraph.h
<gh_stars>1-10 #ifndef TRI_DUAL_GRAPH_H #define TRI_DUAL_GRAPH_H #include "iDualGraph.h" #include <Primitive/Triangle.h> #include <Primitive/Line.h> #include <Mesh/Model.h> namespace Zephyr { namespace Algorithm { struct TriEdge; struct TriNode : public Common::Triangle { TriNode() {} TriNode(const Common::Vertex v0, const Common::Vertex v1, const Common::Vertex v2) : Triangle(v0,v1,v2) {} int label; }; struct TriEdge { TriEdge() : weight(-1.0f) { } float weight; }; // specialization of iDualGraph class ZEPHYR_ALGORITHM_API TriDualGraph : public DualGraph<TriNode, TriEdge> { public: TriDualGraph(Common::Mesh* mesh); virtual ~TriDualGraph(); void build(const Common::Mesh& mesh); // return the face id of the in each inStroke segment after passing the user inStrokes (multiple) Common::Model segment(const std::vector<std::vector<int>>& inStrokes); private: Common::Mesh* mpMesh; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Mesh/Mesh.h
#ifndef MESH_H #define MESH_H #include "../Primitive/Vertex.h" namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API Mesh { public: Mesh(); virtual ~Mesh(); std::vector<Vertex>& getVertices(); const std::vector<Vertex>& getVertices() const; int getVerticesCount() const; void resizeVertices(const int size); std::vector<int>& getIndices(); const std::vector<int>& getIndices() const; int getIndicesCount() const; void resizeIndices(const int size); int getFaceCount() const; int getMaterialId() const; void setMaterialId(const int id); protected: std::vector<Vertex> mVertices; std::vector<int> mIndices; int mMaterialId; }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/Primitive/Point.h
#ifndef POINT_H #define POINT_H #include "../stdfx.h" namespace Zephyr { namespace Common { struct ZEPHYR_COMMON_API Point { Point(float x = 0, float y = 0, float z = 0) : position(x,y,z) { } Vector3f position; }; } } #endif
Naimin/Zephyr
Zephyr_Algorithm/src/Zephyr_Algorithm.h
<filename>Zephyr_Algorithm/src/Zephyr_Algorithm.h #ifndef ZEPHYR_ALGORITHM_H #define ZEPHYR_ALGORITHM_H #include "stdfx.h" #include "OM_Mesh.h" namespace Zephyr { namespace Algorithm { class ZEPHYR_ALGORITHM_API Algorithm { public: Algorithm(); virtual ~Algorithm(); }; } } #endif
Naimin/Zephyr
Zephyr_Graphics/src/BasicRenderPass.h
#ifndef BASIC_RENDER_PASS_H #define BASIC_RENDER_PASS_H #include "IRenderPass.h" #include "RenderableModel.h" #include <Camera.h> namespace Zephyr { namespace Graphics { using namespace DirectX; class ZEPHYR_GRAPHICS_API BasicRenderPass : public IRenderPass { public: struct ConstantBuffer { XMFLOAT4X4 wvpMat; }; public: BasicRenderPass(const int frameBufferCount, GraphicsEngine* pEngine); virtual ~BasicRenderPass(); void setCamera(const Common::Camera& camera); std::shared_ptr<Common::Camera> initalizeCamera(const Common::Vector3f& cameraPos, const Common::Vector3f& cameraTarget, const Common::Vector3f& cameraUp, const float fov, // in radian const float nearClip, const float farClip, const int screenWidth, const int screenHeight); std::shared_ptr<Common::Camera> getCamera(); const std::shared_ptr<Common::Camera> getCamera() const; void updateCameraMatrix(); void setClearColor(float r, float g, float b, float a); virtual bool loadModel(const std::string& modelPath); virtual RenderableModel* getModel(); virtual bool initialize(); virtual void update(const int frameIndex, const double deltaTime); std::string getModelPath() const; protected: std::string mModelPath; float clearColor[4]; std::shared_ptr<RenderableModel> mpModel; ConstantBuffer mConstantBuffer; std::shared_ptr<Common::Camera> mpCamera; XMFLOAT4X4 cameraProjMat; // this will store our projection matrix XMFLOAT4X4 cameraViewMat; // this will store our view matrix /*XMFLOAT4 cameraPosition; // this is our cameras position vector XMFLOAT4 cameraTarget; // a vector describing the point in space our camera is looking at XMFLOAT4 cameraUp; // the worlds up vector*/ XMFLOAT4X4 cube1WorldMat; // our first cubes world matrix (transformation matrix) XMFLOAT4X4 cube1RotMat; // this will keep track of our rotation for the first cube XMFLOAT4 cube1Position; // our first cubes position in space }; } } #endif
Naimin/Zephyr
Zephyr_Common/src/IO/MeshConverter.h
#ifndef MESH_CONVERTER_H #define MESH_CONVERTER_H #include "../stdfx.h" #include "../Mesh/Model.h" #include "../Mesh/OM_Mesh.h" namespace Zephyr { namespace Common { class ZEPHYR_COMMON_API MeshConverter { public: MeshConverter(); virtual ~MeshConverter(); static OpenMeshMesh ModelToOpenMesh(const Model& model); static Model OpenMeshToModel(const OpenMeshMesh& omesh); }; } } #endif
Naimin/Zephyr
Zephyr_App/src/AppEvents.h
#ifndef ZEPHYR_APP_EVENTS_H #define ZEPHYR_APP_EVENTS_H #include "App.h" #include "UI.h" namespace Zephyr { namespace Algorithm { enum DecimationType; } class AppEvents { public: AppEvents(App* pApp, UI* pUI); virtual ~AppEvents(); bool initialize(); protected: virtual void setupLoadButtonEvents(std::shared_ptr<nana::button> pButton); virtual void setupSegmentButtonEvents(std::shared_ptr<nana::button> pButton); virtual void setupGreedyDecimationButtonEvents(std::shared_ptr<nana::button> pButton, std::shared_ptr<nana::slider> pSlider, std::shared_ptr<nana::slider> pBinSlider); virtual void setupRandomDecimationButtonEvents(std::shared_ptr<nana::button> pButton, std::shared_ptr<nana::slider> pSlider, std::shared_ptr<nana::slider> pBinSlider); virtual void setupVertexRandomDecimationButtonEvents(std::shared_ptr<nana::button> pButton, std::shared_ptr<nana::slider> pSlider, std::shared_ptr<nana::slider> pBinSlider); virtual void setupGPURandomDecimationButtonEvents(std::shared_ptr<nana::button> pButton, std::shared_ptr<nana::slider> pSlider, std::shared_ptr<nana::slider> pBinSlider); virtual void setupDecimationSlider(std::shared_ptr<nana::slider> pSlider, std::shared_ptr<nana::label> pLabel); virtual void setupBinSlider(std::shared_ptr<nana::slider> pSlider, std::shared_ptr<nana::label> pLabel); // helper function virtual void setupDecimationButtonEvents(std::shared_ptr<nana::button> pButton, std::shared_ptr<nana::slider> pSlider, std::shared_ptr<nana::slider> pBinSlider, Algorithm::DecimationType decimationType); virtual std::string getExportPath(); // use FileBox to get export path private: App* mpApp; UI* mpUI; }; } #endif
Naimin/Zephyr
Zephyr_Graphics/src/Pipeline.h
<reponame>Naimin/Zephyr #ifndef PIPELINE_H #define PIPELINE_H #include "stdfx.h" namespace Zephyr { namespace Graphics { class GraphicsEngine; struct ZEPHYR_GRAPHICS_API PipelineOption { D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlag; std::wstring vertexShader; std::wstring vertexShaderPath; std::wstring pixelShader; std::wstring pixelShaderPath; std::vector<D3D12_INPUT_ELEMENT_DESC> inputLayout; int frameBufferCount; int constantBufferSize; }; class ZEPHYR_GRAPHICS_API Pipeline { public: Pipeline(GraphicsEngine* pEngine); virtual ~Pipeline(); virtual bool initialize(const PipelineOption& option); public: ID3D12PipelineState* getPipeline() const; ID3D12RootSignature* getRootSignature() const; ID3D12DescriptorHeap* getDepthStencilDescriptorHeap() const; UINT8* getConstantBufferGPUAddress(const int frameIndex) const; ID3D12Resource* getConstantBufferUploadHeap(const int frameIndex) const; ID3D12DescriptorHeap* getConstantBufferDescriptorHeap(const int frameIndex) const; protected: virtual bool createRootSignature(const D3D12_ROOT_SIGNATURE_FLAGS& flag); virtual bool createConstantBuffer(const int frameBufferCount, const int constantBufferSize); virtual bool createInputLayout(const std::vector<D3D12_INPUT_ELEMENT_DESC>& inputLayout); virtual bool createShaders(const std::wstring& vertexShader, const std::wstring& vertexShaderPath, const std::wstring& pixelShader, const std::wstring& pixelShaderPath); virtual bool createDepthStencil(); virtual bool createSampler(); virtual bool createPipeline(); protected: GraphicsEngine* mpEngine; ID3D12PipelineState* mpPipelineState; // pso containing a pipeline state std::vector<D3D12_INPUT_ELEMENT_DESC> mInputElements; D3D12_INPUT_LAYOUT_DESC mInputLayout; ID3D12RootSignature* mpRootSignature; ID3D12DescriptorHeap* mpDSDescriptorHeap; // This is a heap for our depth/stencil buffer descriptor std::vector<D3D12_SHADER_BYTECODE> mShaderByteCodes; std::vector<ID3D12DescriptorHeap*> mConstantBufferDescriptorHeap; std::vector<ID3D12Resource*> mConstantBufferUploadHeap; std::vector<UINT8*> mConstantBufferGPUAddress; std::vector<D3D12_STATIC_SAMPLER_DESC> mSamplerDesc; }; } } #endif