repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
chuffa/ITensor
|
itensor/all_mps.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_ALL_MPS_H
#define __ITENSOR_ALL_MPS_H
//
// all_mps.h - convenience header file that
// includes all headers related
// to MPS and MPO such as
// DMRG, methods for time-evolving
// MPS, 2D lattice helpers, etc.
//
// (the headers explicitly included
// here are not meant to be an
// exhaustive list, but are
// a minimal set which pull in
// the key features)
//
#include "itensor/all_basic.h"
#include "itensor/util/stats.h"
#include "itensor/mps/dmrg.h"
#include "itensor/mps/tevol.h"
#include "itensor/mps/autompo.h"
#include "itensor/mps/lattice/square.h"
#include "itensor/mps/lattice/triangular.h"
#include "itensor/mps/sites/spinhalf.h"
#include "itensor/mps/sites/spinone.h"
#include "itensor/mps/sites/spintwo.h"
#include "itensor/mps/sites/customspin.h"
#include "itensor/mps/sites/boson.h"
#include "itensor/mps/sites/electron.h"
#include "itensor/mps/sites/fermion.h"
#include "itensor/mps/sites/tj.h"
#include "itensor/mps/sites/Z3.h"
#endif
|
chuffa/ITensor
|
itensor/util/autovector.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_AUTOVECTOR_H
#define __ITENSOR_AUTOVECTOR_H
#include <vector>
#include <iostream>
namespace itensor {
using lint = long int;
//
// autovector SRW 8/26/14
//
// vector class that supports any index minimum and maximum.
// Assigning elements outside index range automatically adjusts range
// Const access outside index range returns default value
/* Example usage:
autovector<double> v;
v.ref(-4) = 3.0; // index range is -4 to -4
v.ref(5) = 2.0; // Now index range is -4 to 5
double t = v(5); // t == 2.0
double x = v(6); // x == 0.0; index range is still -4 to 5
double y = v.fast(3);// y = 0.0; no checking; must be inside range
v.fastref(3) = 4.0; // v(3) == 4; no checking; must be inside range
*/
template<typename T>
class autovector // returns T() outside range or unassigned
{
private:
lint mini_,
maxi_, // minimum and maximum indices i set so far
miniloc_; // offset of mini in storage
std::vector<T> dat_;
static const T&
defaultRef()
{
static auto default_ = T();
return default_;
}
public:
autovector()
: mini_(1), maxi_(0), miniloc_(0) { }
autovector(lint min_i,
lint max_i,
T t = T())
: mini_(min_i),
maxi_(max_i),
miniloc_(0),
dat_(maxi_-mini_+1,t)
{ }
lint
mini() const { return mini_; }
lint
maxi() const { return maxi_; }
void
clear() { dat_.clear(); }
lint
size() const { return 1+(maxi_-mini_); }
T*
begin() { return &dat_[miniloc_]; }
T*
end() { return 1+&dat_[maxi_-mini_+miniloc_]; }
const T*
begin() const { return &dat_[miniloc_]; }
const T*
end() const { return 1+&dat_[maxi_-mini_+miniloc_]; }
const T*
cbegin() const { return &dat_[miniloc_]; }
const T*
cend() const { return 1+&dat_[maxi_-mini_+miniloc_]; }
const T&
operator()(lint i) const
{
if(dat_.empty() || i < mini_ || i > maxi_) return defaultRef();
return dat_[i-mini_+miniloc_];
}
void
operator()(lint i, T val)
{
ref(i) = val;
}
T&
ref(lint i)
{
if(dat_.empty())
{
dat_.resize(9);
miniloc_ = 4;
mini_ = maxi_ = i;
}
else if(i < mini_ || i > maxi_)
{
lint newmini = std::min(i,mini_);
lint newmaxi = std::max(i,maxi_);
lint j = i - mini_ + miniloc_;
if(j >= 0 && j < lint(dat_.size())) // don't have to resize
{
miniloc_ += newmini - mini_;
}
else
{ // resize
lint newlen = (lint)((newmaxi - newmini + 8) * 2);
lint newminiloc = (newlen - (newmaxi - newmini + 1)) / 2;
std::vector<T> newdat(newlen);
lint oldbegin = miniloc_,
oldend = miniloc_ + maxi_ - mini_;
lint newbegin = newminiloc-newmini+mini_; // location of mini in newdat
for(auto n = oldbegin; n <= oldend; ++n)
newdat[newbegin + n - oldbegin] = dat_[n];
dat_.swap(newdat);
miniloc_ = newminiloc;
}
mini_ = newmini;
maxi_ = newmaxi;
}
return dat_[i-mini_+miniloc_];
}
const T&
fast(lint i) const // User must make sure mini() <= i <= maxi()
{
return dat_[i-mini_+miniloc_];
}
T&
fastref(lint i) // User must make sure mini() <= i <= maxi()
{
return dat_[i-mini_+miniloc_];
}
const T&
operator[](lint i) const { return fast(i); }
T&
operator[](lint i) { return fastref(i); }
};
template<typename T>
T
dot(const autovector<T>& a, const autovector<T>& b)
{
lint imin = std::max(a.mini(),b.mini()),
imax = std::min(a.maxi(),b.maxi());
auto res = T();
for(auto i = imin; i <= imax; ++i)
res += a.fast(i) * b.fast(i);
return res;
}
template<typename T>
std::ostream&
operator<<(std::ostream & s,
autovector<T> const& v)
{
if(v.size()==0l) return s;
auto j = v.mini();
for(; j < v.maxi(); ++j)
{
s << v[j] << ",";
}
s << v[j];
return s;
}
} //namespace itensor
#endif
|
chuffa/ITensor
|
sample/src/ising.h
|
#include "itensor/all.h"
using namespace itensor;
ITensor
ising(Index const& sh,
Index const& sv,
Real beta,
bool sz = false)
{
auto d = dim(sh);
auto shp = prime(sh);
auto svp = prime(sv);
auto T = ITensor(sh, shp, sv, svp);
for(auto i : range1(d)){ T.set(i, i, i, i, 1.0); }
if(sz) { T.set(1, 1, 1, 1, -1.0); }
auto th = sim(sh);
auto thp = sim(shp);
auto tv = sim(sv);
auto tvp = sim(svp);
auto Tp = T * delta(sh, th) *
delta(shp, thp) *
delta(sv, tv) *
delta(svp, tvp);
// Analytic square root of the bond matrix:
// [exp( beta) exp(-beta)
// exp(-beta) exp( beta)]
auto lambda_p = sqrt(exp(beta) + exp(-beta));
auto lambda_m = sqrt(exp(beta) - exp(-beta));
auto x_p = 0.5 * (lambda_p + lambda_m);
auto x_m = 0.5 * (lambda_p - lambda_m);
auto Xh = ITensor(th, sh);
Xh.set(1, 1, x_p);
Xh.set(2, 1, x_m);
Xh.set(1, 2, x_m);
Xh.set(2, 2, x_p);
auto Xhp = replaceInds(Xh, {th, sh}, {thp, shp});
auto Xv = replaceInds(Xh, {th, sh}, {tv, sv });
auto Xvp = replaceInds(Xh, {th, sh}, {tvp, svp});
return Tp * Xhp * Xvp * Xh * Xv;
}
//
// Dual partition function
//
//ITensor
//ising(Index const& sh, Index const& sv,
// Real beta)
// {
// int dim0 = 2;
// auto T = ITensor(sh, prime(sh), sv, prime(sv));
//
// // Fill the T tensor with correct Boltzmann weights:
// auto Sig = [](int s) { return 1. - 2. * (s - 1); };
// for(auto ssh : range1(dim0))
// for(auto ssvp : range1(dim0))
// for(auto sshp : range1(dim0))
// for(auto ssv : range1(dim0))
// {
// auto E = Sig(ssh) * Sig(ssvp) +
// Sig(ssvp) * Sig(sshp) +
// Sig(sshp) * Sig(ssv) +
// Sig(ssv) * Sig(ssh);
// auto P = exp(-beta * E);
// T.set(sh = ssh, prime(sh) = sshp, sv = ssv, prime(sv) = ssvp, P);
// }
// return T;
// }
|
chuffa/ITensor
|
itensor/util/static_count.h
|
#ifndef __ITENSOR_STATIC_COUNT_H__
#define __ITENSOR_STATIC_COUNT_H__
#include "itensor/util/print.h"
namespace itensor {
//
// Usage:
//
// static auto sc = StaticCount("Incremented %d times");
// ++sc;
// //will automatically print "Incremented ## times"
// //when program ends
//
struct StaticCount
{
long count = 0;
const char* fstring = "";
StaticCount(const char* fstring_) : fstring(fstring_) { }
~StaticCount()
{
printfln(fstring,count);
}
void
operator++() { ++count; }
};
} //namespace itensor
#endif
|
chuffa/ITensor
|
unittest/mps_mpo_test_helper.h
|
#ifndef __ITENSOR_MPS_MPO_TEST_HELPER_H
#define __ITENSOR_MPS_MPO_TEST_HELPER_H
#include "itensor/mps/autompo.h"
namespace itensor {
bool inline
checkTags(MPO const& K,
std::string const& siteTagsBra = "Site,0",
std::string const& siteTagsKet = "Site,1",
std::string const& linkTags = "Link,0")
{
auto N = length(K);
for(auto n : range1(N))
{
if( n < N )
{
auto l = linkIndex(K,n);
if( !hasTags(l,linkTags+",l="+str(n)) ) return false;
}
auto s = siteInds(K,n);
if( !findIndex(s,siteTagsBra+",n="+str(n)) ) return false;
if( !findIndex(s,siteTagsKet+",n="+str(n)) ) return false;
}
return true;
}
bool inline
checkTags(MPS const& psi,
std::string const& siteTags = "Site,0",
std::string const& linkTags = "Link,0")
{
auto N = length(psi);
for(auto n : range1(N))
{
if( n < N )
{
auto l = linkIndex(psi,n);
if( !hasTags(l,linkTags+",l="+str(n)) ) return false;
}
auto s = siteIndex(psi,n);
if( !hasTags(s,siteTags+",n="+str(n)) ) return false;
}
return true;
}
Real inline
diff(MPS const& psi, MPS const& phi)
{
auto norm_psi = real(innerC(psi,psi));
auto norm_phi = real(innerC(phi,phi));
auto psi_phi = innerC(psi,phi);
return std::sqrt(std::abs(norm_psi/norm_phi+1.-2.*real(psi_phi)/norm_phi));
}
MPO inline
randomUnitaryMPO(SiteSet const& sites, Args const& args = Args::global())
{
auto tau = args.getReal("Timestep",0.1);
auto N = length(sites);
//Use AutoMPO as a trick to get
//an MPO with bond dimension > 1
auto ampo = AutoMPO(sites);
auto J1 = detail::quickran();
auto J2 = detail::quickran();
auto J3 = detail::quickran();
for(auto j : range1(N-1))
{
ampo += J1,"Sz",j,"Sz",j+1;
ampo += 0.5*J2,"S+",j,"S-",j+1;
ampo += 0.5*J3,"S-",j,"S+",j+1;
}
auto U = toExpH(ampo,tau*Cplx_i);
return U;
}
}
#endif
|
chuffa/ITensor
|
sample/src/trg.h
|
<gh_stars>100-1000
#include "itensor/all.h"
using namespace itensor;
std::tuple<ITensor, Real>
trg(ITensor const& A0,
int maxdim, int topscale,
Real cutoff = 0.0)
{
auto A = A0;
auto is = findInds(A, "0");
auto sh = is(1);
auto sv = is(2);
// Keep track of partition function per site, z = Z^(1/N)
Real z = 1.0;
for(auto scale : range1(topscale))
{
//printfln("\n---------- Scale %d -> %d ----------",scale-1,scale);
// Get the upper-left and lower-right tensors
auto [Fh, Fhp] = factor(A, {prime(sh), prime(sv)}, {sh, sv},
{"MaxDim = ", maxdim,
"Tags = ", "horiz",
"SVDMethod = ", "gesdd",
"Cutoff = ", cutoff,
"ShowEigs = ", false});
// Grab the new left Index
auto sh_new = commonIndex(Fh, Fhp);
Fhp *= delta(sh_new, prime(sh_new));
// Get the upper-right and lower-left tensors
auto [Fv, Fvp] = factor(A, {sh, prime(sv)}, {prime(sh), sv},
{"MaxDim = ", maxdim,
"Tags = ", "vert",
"SVDMethod = ", "gesdd",
"Cutoff = ", cutoff,
"ShowEigs = ", false});
// Grab the new up Index
auto sv_new = commonIndex(Fv, Fvp);
Fvp *= delta(sv_new, prime(sv_new));
A = (Fh * delta(prime(sh), sh)) *
(Fv * delta(prime(sv), sv)) *
(Fhp * delta(sh, prime(sh))) *
(Fvp * delta(sv, prime(sv)));
// Update the indices
sh = sh_new;
sv = sv_new;
// Normalize the current tensor and keep track of
// the total normalization
Real TrA = elt(A * delta(sh, prime(sh)) * delta(sv, prime(sv)));
A /= TrA;
z *= pow(TrA, 1.0 / pow(2, scale));
// If using the dual Ising partition function
//z *= pow(TrA, 1.0 / pow(2, 1 + scale));
}
//printfln("log(Z)/N = %.12f",log(z));
return std::tuple<ITensor, Real>({A, z});
}
|
chuffa/ITensor
|
itensor/indexset.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_INDEXSET_H
#define __ITENSOR_INDEXSET_H
#include <algorithm>
#include "itensor/util/safe_ptr.h"
#include "itensor/index.h"
#include "itensor/tensor/contract.h"
#include "itensor/tensor/range.h"
#include "itensor/tensor/types.h"
#include "itensor/tensor/permutation.h"
namespace itensor {
class IndexSet;
using IndexSetBuilder = RangeBuilderT<IndexSet>;
template<typename I>
class IndexSetIter;
//
// IndexSet
//
// When constructed from a collection of indices,
// (as an explicit set of arguments or via
// a container) puts the indices with m>1 to the
// front and those with m==1 at the back but otherwise
// keeps the indices in the order given.
//
void
checkQNConsistent(IndexSet const&);
class IndexSet : public RangeT<Index>
{
public:
using extent_type = index_type;
using range_type = RangeT<Index>;
using parent = RangeT<Index>;
using size_type = typename range_type::size_type;
using storage_type = typename range_type::storage_type;
using value_type = Index;
using iterator = IndexSetIter<Index>;
using const_iterator = IndexSetIter<const Index>;
public:
IndexSet() { }
// construct from 1 or more indices
template <typename... Inds>
explicit
IndexSet(Index const& i1,
Inds&&... inds)
: parent(i1,std::forward<Inds>(inds)...)
{
checkQNConsistent(*this);
}
IndexSet(std::initializer_list<Index> const& ii)
: parent(ii)
{
checkQNConsistent(*this);
}
IndexSet(std::vector<Index> const& ii)
: parent(ii)
{
checkQNConsistent(*this);
}
template<size_t N>
IndexSet(std::array<Index,N> const& ii)
: parent(ii)
{
checkQNConsistent(*this);
}
template<typename IndxContainer>
explicit
IndexSet(IndxContainer && ii)
: parent(std::forward<IndxContainer>(ii))
{
checkQNConsistent(*this);
}
explicit
IndexSet(storage_type && store)
: parent(std::move(store))
{
checkQNConsistent(*this);
}
// construct from 2 IndexSets
IndexSet(IndexSet const& is1,
IndexSet const& is2)
{
auto N1 = is1.order();
auto N2 = is2.order();
auto N = N1+N2;
auto inds = IndexSetBuilder(N);
for( auto n1 : range1(N1) )
inds.nextIndex(std::move(is1(n1)));
for( auto n2 : range1(N2) )
inds.nextIndex(std::move(is2(n2)));
*this = inds.build();
checkQNConsistent(*this);
}
// construct from an Index and IndexSet
IndexSet(Index const& i,
IndexSet const& is)
{
auto N = is.order();
auto inds = IndexSetBuilder(N+1);
inds.nextIndex(std::move(i));
for( auto n : range1(N) )
inds.nextIndex(std::move(is(n)));
*this = inds.build();
checkQNConsistent(*this);
}
// construct from an Index and IndexSet
IndexSet(IndexSet const& is,
Index const& i)
{
auto N = is.order();
auto inds = IndexSetBuilder(N+1);
for( auto n : range1(N) )
inds.nextIndex(std::move(is(n)));
inds.nextIndex(std::move(i));
*this = inds.build();
checkQNConsistent(*this);
}
explicit operator bool() const { return !parent::empty(); }
long
extent(size_type i) const { return parent::extent(i); }
size_type
stride(size_type i) const { return parent::stride(i); }
// Get the number of indices
long
order() const { return parent::order(); }
// Get the number of indices (alternative)
long
length() const { return this->order(); }
// 0-indexed access
Index &
operator[](size_type i)
{
#ifdef DEBUG
if(i >= parent::size()) throw ITError("IndexSet[i] arg out of range");
#endif
return parent::index(i);
}
// 1-indexed access
Index &
operator()(size_type I)
{
#ifdef DEBUG
if(I < 1 || I > parent::size()) throw ITError("IndexSet(i) arg out of range");
#endif
return operator[](I-1);
}
// Deprecated
Index &
index(size_type I) { return operator()(I); }
// 0-indexed access
Index const&
operator[](size_type i) const
{
#ifdef DEBUG
if(i >= parent::size()) throw ITError("IndexSet[i] arg out of range");
#endif
return parent::index(i);
}
// 1-indexed access
Index const&
operator()(size_type I) const
{
#ifdef DEBUG
if(I < 1 || I > parent::size()) throw ITError("IndexSet(i) arg out of range");
#endif
return operator[](I-1);
}
// Deprecated
Index const&
index(size_type I) const { return operator()(I); }
parent const&
range() const { return *this; }
IndexSet&
dag();
void
swap(IndexSet & other) { parent::swap(other); }
Index const&
front() const { return parent::front().ind; }
Index const&
back() const { return parent::back().ind; }
iterator
begin();
iterator
end();
const_iterator
begin() const;
const_iterator
end() const;
const_iterator
cbegin() const;
const_iterator
cend() const;
//
// Tag methods
//
IndexSet&
setTags(TagSet const& tsnew);
IndexSet&
setTags(TagSet const& tsnew,
IndexSet const& ismatch);
template<typename... VarArgs>
IndexSet&
setTags(TagSet const& tsnew,
Index const& imatch1,
VarArgs&&... vargs)
{
setTags(tsnew,IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
setTags(TagSet const& tsnew,
TagSet const& tsmatch);
IndexSet&
noTags();
IndexSet&
noTags(IndexSet const& ismatch);
template<typename... VarArgs>
IndexSet&
noTags(Index const& imatch1,
VarArgs&&... vargs)
{
noTags(IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
noTags(TagSet const& tsmatch);
IndexSet&
addTags(TagSet const& tsadd);
IndexSet&
addTags(TagSet const& tsadd,
IndexSet const& ismatch);
template<typename... VarArgs>
IndexSet&
addTags(TagSet const& tsadd,
Index const& imatch1,
VarArgs&&... vargs)
{
addTags(tsadd,IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
addTags(TagSet const& tsadd,
TagSet const& tsmatch);
IndexSet&
removeTags(TagSet const& tsremove);
IndexSet&
removeTags(TagSet const& tsremove,
IndexSet const& ismatch);
template<typename... VarArgs>
IndexSet&
removeTags(TagSet const& tsremove,
Index const& imatch1,
VarArgs&&... vargs)
{
removeTags(tsremove,IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
removeTags(TagSet const& tsremove,
TagSet const& tsmatch);
IndexSet&
replaceTags(TagSet const& tsold,
TagSet const& tsnew);
IndexSet&
replaceTags(TagSet const& tsold,
TagSet const& tsnew,
IndexSet const& ismatch);
template<typename... VarArgs>
IndexSet&
replaceTags(TagSet const& tsold,
TagSet const& tsnew,
Index const& imatch1,
VarArgs&&... vargs)
{
replaceTags(tsold,tsnew,IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
replaceTags(TagSet const& tsold,
TagSet const& tsnew,
TagSet const& tsmatch);
template<typename... VarArgs>
IndexSet&
swapTags(TagSet const& ts1,
TagSet const& ts2,
VarArgs&&... vargs);
//
// Integer tag convenience functions
//
//
// Set the integer tag of indices to plnew
//
IndexSet&
setPrime(int plnew);
IndexSet&
setPrime(int plnew,
IndexSet const& ismatch);
template<typename... VarArgs>
IndexSet&
setPrime(int plnew,
Index const& imatch1,
VarArgs&&... vargs)
{
setPrime(plnew,IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
setPrime(int plnew,
TagSet const& tsmatch);
IndexSet&
mapPrime(int plold, int plnew);
IndexSet&
mapPrime(int plold, int plnew,
IndexSet const& ismatch);
template<typename... VarArgs>
IndexSet&
mapPrime(int plold, int plnew,
Index const& imatch1,
VarArgs&&... vargs)
{
mapPrime(plold,plnew,IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
mapPrime(int plold, int plnew,
TagSet const& tsmatch);
template<typename... VarArgs>
IndexSet&
swapPrime(int pl1,
int pl2,
VarArgs&&... vargs);
template<typename... VarArgs>
IndexSet&
noPrime(VarArgs&&... vargs)
{
setPrime(0,std::forward<VarArgs>(vargs)...);
return *this;
}
//
// Increase the integer tag of indices by plinc
//
IndexSet&
prime(int plinc);
IndexSet&
prime()
{
prime(1);
return *this;
}
IndexSet&
prime(int plinc,
IndexSet const& ismatch);
IndexSet&
prime(IndexSet const& ismatch)
{
prime(1,ismatch);
return *this;
}
template<typename... VarArgs>
IndexSet&
prime(int plinc,
Index const& imatch1,
VarArgs&&... vargs)
{
prime(plinc,IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
template<typename... VarArgs>
IndexSet&
prime(Index const& imatch1,
VarArgs&&... vargs)
{
prime(IndexSet(imatch1,std::forward<VarArgs>(vargs)...));
return *this;
}
IndexSet&
prime(int plinc,
TagSet const& tsmatch);
IndexSet&
prime(TagSet const& tsmatch)
{
prime(1,tsmatch);
return *this;
}
// Remove QNs from all indices in the IndexSet
IndexSet&
removeQNs();
//
// Deprecated
//
long
r() const { return this->order(); }
void
prime(Index const& imatch,
int plinc)
{
Error("Error: .prime(Index,int) is no longer supported, use .prime(int,Index) instead.");
}
};
void
read(std::istream& s, IndexSet & is);
void
write(std::ostream& s, IndexSet const& is);
auto inline
rangeBegin(IndexSet const& is) -> decltype(is.range().begin())
{
return is.range().begin();
}
auto inline
rangeEnd(IndexSet const& is) -> decltype(is.range().end())
{
return is.range().end();
}
long
order(IndexSet const& is);
long
length(IndexSet const& is);
IndexSet
dag(IndexSet is);
template<typename... VarArgs>
IndexSet
setTags(IndexSet A,
VarArgs&&... vargs)
{
A.setTags(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
noTags(IndexSet A,
VarArgs&&... vargs)
{
A.noTags(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
addTags(IndexSet A,
VarArgs&&... vargs)
{
A.addTags(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
removeTags(IndexSet A,
VarArgs&&... vargs)
{
A.removeTags(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
replaceTags(IndexSet A,
VarArgs&&... vargs)
{
A.replaceTags(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
swapTags(IndexSet A,
VarArgs&&... vargs)
{
A.swapTags(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
prime(IndexSet A,
VarArgs&&... vargs)
{
A.prime(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
setPrime(IndexSet A,
VarArgs&&... vargs)
{
A.setPrime(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
mapPrime(IndexSet A,
VarArgs&&... vargs)
{
A.mapPrime(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
swapPrime(IndexSet A,
VarArgs&&... vargs)
{
A.swapPrime(std::forward<VarArgs>(vargs)...);
return A;
}
template<typename... VarArgs>
IndexSet
noPrime(IndexSet A,
VarArgs&&... vargs)
{
A.noPrime(std::forward<VarArgs>(vargs)...);
return A;
}
//Replace all indices with 'similar' indices
//with the same properties but which don't compare equal
//to the indices they replace (using sim(Index) function)
IndexSet
sim(IndexSet is);
IndexSet
sim(IndexSet is,
IndexSet const& ismatch);
IndexSet
sim(IndexSet is,
TagSet const& tsmatch);
//
// IndexSet helper methods
//
//
// Given IndexSet iset and Index I,
// return int j such that iset[j] == I.
// If not found, returns -1
//
int
indexPosition(IndexSet const& is,
Index const& imatch);
std::vector<int>
indexPositions(IndexSet const& is,
IndexSet const& ismatch);
Arrow
dir(IndexSet const& is, Index const& I);
// Return true if the Index `imatch` is in
// `is`
bool
hasIndex(IndexSet const& is,
Index const& imatch);
// Return true if all indices of `ismatch`
// are in `is`
bool
hasInds(IndexSet const& is,
IndexSet const& ismatch);
template<typename... Inds>
bool
hasInds(IndexSet const& is,
Index const& i1, Inds&&... inds)
{
return hasInds(is,IndexSet(i1,std::forward<Inds>(inds)...));
}
// Return true if IndexSet `is1` and `is2` have
// the same indices
bool
hasSameInds(IndexSet const& is1,
IndexSet const& is2);
// IndexSets are equal if they are the
// same size and contain equal indices
// in equal ordering (i.e. equals({i,j},{i,j}) -> true)
// but equals({i,j},{j,i}) -> false).
// For set equality, you can use hasSameInds(is1,is2).
bool
equals(IndexSet const& is1,
IndexSet const& is2);
long
minDim(IndexSet const& iset);
long
maxDim(IndexSet const& iset);
void
contractIS(IndexSet const& Lis,
IndexSet const& Ris,
IndexSet & Nis,
bool sortResult = false);
template<class LabelT>
void
contractIS(IndexSet const& Lis,
LabelT const& Lind,
IndexSet const& Ris,
LabelT const& Rind,
IndexSet & Nis,
LabelT & Nind,
bool sortResult = false);
template<class LabelT>
void
contractISReplaceIndex(IndexSet const& Lis,
LabelT const& Lind,
IndexSet const& Ris,
LabelT const& Rind,
IndexSet & Nis);
template<class LabelT>
void
ncprod(IndexSet const& Lis,
LabelT const& Lind,
IndexSet const& Ris,
LabelT const& Rind,
IndexSet & Nis,
LabelT & Nind);
std::ostream&
operator<<(std::ostream& s, IndexSet const& is);
template<typename index_type_>
class IndexSetIter
{
public:
using index_type = stdx::remove_const_t<index_type_>;
using value_type = index_type;
using reference = index_type_&;
using difference_type = std::ptrdiff_t;
using pointer = index_type_*;
using iterator_category = std::random_access_iterator_tag;
using indexset_type = stdx::conditional_t<std::is_const<index_type_>::value,
const IndexSet,
IndexSet>;
using range_ptr = typename RangeT<index_type>::value_type*;
using const_range_ptr = const typename RangeT<index_type>::value_type*;
using data_ptr = stdx::conditional_t<std::is_const<index_type_>::value,
const_range_ptr,
range_ptr>;
private:
size_t off_ = 0;
indexset_type* p_;
public:
IndexSetIter() : p_(nullptr) { }
explicit
IndexSetIter(indexset_type & is) : p_(&is) { }
size_t
offset() const { return off_; }
IndexSetIter&
operator++()
{
++off_;
return *this;
}
IndexSetIter
operator++(int)
{
auto tmp = *this; //save copy of this
++off_;
return tmp;
}
IndexSetIter&
operator+=(difference_type x)
{
off_ += x;
return *this;
}
IndexSetIter&
operator--( )
{
--off_;
return *this;
}
IndexSetIter
operator--(int)
{
auto tmp = *this; //save copy of this
--off_;
return tmp;
}
IndexSetIter&
operator-=(difference_type x)
{
off_ -= x;
return *this;
}
reference
operator[](difference_type n) { return p_->operator[](n); }
reference
operator*() { return p_->operator[](off_); }
pointer
operator->() { return &(p_->operator[](off_)); }
IndexSetIter static
makeEnd(indexset_type & is)
{
IndexSetIter end;
end.p_ = &is;
end.off_ = is.size();
return end;
}
};
template <typename T>
bool
operator==(const IndexSetIter<T>& x, const IndexSetIter<T>& y)
{
return x.offset() == y.offset();
}
template <typename T>
bool
operator!=(const IndexSetIter<T>& x, const IndexSetIter<T>& y)
{
return x.offset() != y.offset();
}
template <typename T>
bool
operator<(const IndexSetIter<T>& x, const IndexSetIter<T>& y)
{
return x.offset() < y.offset();
}
template <typename T>
IndexSetIter<T>
operator+(IndexSetIter<T> x,
typename IndexSetIter<T>::difference_type d)
{
return x += d;
}
template <typename T>
IndexSetIter<T>
operator+(typename IndexSetIter<T>::difference_type d,
IndexSetIter<T> x)
{
return x += d;
}
//
// IndexValIter - helper for iterInds
//
namespace detail {
struct IndexValIter
{
IndexSet const& is;
detail::GCounter count;
bool done = false;
IndexValIter(IndexSet const& is_)
: is(is_),
count(is_.size())
{
for(auto n : range(is.size()))
{
count.setRange(n,0,is[n].dim()-1);
}
}
IndexValIter
begin() const { return *this; }
IndexValIter
end() const
{
auto eit = *this;
eit.done = true;
//for(auto n : range(is.size()))
// {
// eit.count.setRange(n,is[n].dim()-1,is[n].dim()-1);
// }
return eit;
}
bool
operator!=(IndexValIter const& other) { return done != other.done; }
std::vector<IndexVal>
operator*()
{
auto res = std::vector<IndexVal>(is.size());
for(auto n : range(is.size()))
{
res.at(n) = is[n](1+count[n]);
}
return res;
}
IndexValIter&
operator++()
{
++count;
done = !count.notDone();
return *this;
}
};
} //namespace detail
detail::IndexValIter
iterInds(IndexSet const& is);
bool
hasQNs(IndexSet const& is);
QN
flux(std::vector<IndexVal> const& ivs);
void
checkIndexSet(IndexSet const& is);
void
checkIndexPositions(std::vector<int> const& is);
//
// IndexSet set operations
//
// Find the Indices containing tags in the specified TagSet
IndexSet
findInds(IndexSet const& is,
TagSet const& tsmatch);
// Convert an order one IndexSet into an Index
// Throws an error if more than one Index is in the IndexSet
// If no indices are found, returns a null Index
Index
findIndex(IndexSet const& is);
// Find the Index containing tags in the specified TagSet
// Throws an error if more than one Index is found
// If no indices are found, returns a null Index
Index
findIndex(IndexSet const& is,
TagSet const& tsmatch);
// Find the Indices not containing tags in the specified TagSet
// Same as uniqueInds(is,findInds(is,tsmatch))
IndexSet
findIndsExcept(IndexSet const& is,
TagSet const& tsmatch);
// Intersection of two IndexSets
IndexSet
commonInds(IndexSet const& is1,
IndexSet const& is2);
// Union of two IndexSets (is1+is2)
// Preserves the ordering of the original
// IndexSets
IndexSet
unionInds(IndexSet const& is1,
IndexSet const& is2);
IndexSet
unionInds(Index const& i,
IndexSet const& is);
IndexSet
unionInds(IndexSet const& is,
Index const& i);
IndexSet
unionInds(std::vector<IndexSet> const& is1);
// Difference of two IndexSets (is1-is2)
IndexSet
uniqueInds(IndexSet const& is1,
IndexSet const& is2);
// Difference of IndexSet from a set
// of other IndexSets (is1-(is2+is3+...))
IndexSet
uniqueInds(IndexSet const& is1,
std::vector<IndexSet> const& is2);
// Symmetric difference of two IndexSets
// (union(is1-is2,is2-is1))
IndexSet
noncommonInds(IndexSet const& is1,
IndexSet const& is2);
#ifdef ITENSOR_USE_HDF5
void
h5_write(h5::group parent, std::string const& name, IndexSet const& is);
void
h5_read(h5::group parent, std::string const& name, IndexSet & is);
#endif
} //namespace itensor
#include "itensor/indexset_impl.h"
#endif
|
chuffa/ITensor
|
itensor/decomp_impl.h
|
<gh_stars>100-1000
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_DECOMP_IMPL_H
#define __ITENSOR_DECOMP_IMPL_H
namespace itensor {
namespace detail {
Args inline
makeIndexSetArgs(std::vector<Index>& inds, Args const& args)
{
return args;
}
Args inline
makeIndexSetArgs(std::vector<Index>& inds, Index const& i)
{
inds.push_back(i);
return Args::global();
}
template <typename... IndsArgs>
Args
makeIndexSetArgs(std::vector<Index>& inds,
Index const& i1,
IndsArgs&&... indsargs)
{
inds.push_back(i1);
return makeIndexSetArgs(inds, indsargs...);
}
template <typename... IndsArgs>
std::tuple<IndexSet,Args>
makeIndexSetArgs(Index const& i1, IndsArgs&&... indsargs)
{
auto inds = std::vector<Index>();
auto args = makeIndexSetArgs(inds,i1,indsargs...);
auto is = IndexSet(inds);
return std::make_tuple(is,args);
}
} //namespace detail
template <typename... IndsArgs>
std::tuple<ITensor,ITensor,ITensor>
svd(ITensor const& T, Index const& i1, IndsArgs&&... indsargs)
{
auto [is,args] = detail::makeIndexSetArgs(i1,indsargs...);
return svd(T,is,args);
}
template <typename... IndsArgs>
std::tuple<ITensor,ITensor>
qr(ITensor const& T, Index const& i1, IndsArgs&&... indsargs)
{
auto [is,args] = detail::makeIndexSetArgs(i1,indsargs...);
return qr(T,is,args);
}
template <typename... IndsArgs>
std::tuple<ITensor,ITensor>
factor(ITensor const& T, Index const& i1, IndsArgs&&... indsargs)
{
auto [is,args] = detail::makeIndexSetArgs(i1,indsargs...);
return factor(T,is,args);
}
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/util/flstring.h
|
<filename>itensor/util/flstring.h
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef _ITENSOR_STRING_H_
#define _ITENSOR_STRING_H_
#include <string>
#include "itensor/tensor/types.h"
#include "itensor/util/error.h"
namespace itensor {
//
// Fixed length string.
// Allocates memory on the stack
// for efficiency purposes.
//
template <size_t Maxlen>
class FLString
{
public:
FLString();
FLString(const char* str);
FLString(const std::string& str);
size_t
length() const;
size_t
size() const { return length(); }
bool
empty() const { return (data_[0] == '\0'); }
operator bool() const { return !empty(); }
std::string
toString() const { return std::string(data_); }
char
operator[](size_t n) const;
const char*
data() const { return &(data_[0]); }
private:
char data_[Maxlen+1];
};
template <size_t Maxlen>
std::ostream&
operator<<(std::ostream &s, const FLString<Maxlen>& a);
template <size_t Maxlen>
bool
operator==(const FLString<Maxlen>& s1, const FLString<Maxlen>& s2);
template <size_t Maxlen>
bool
operator!=(const FLString<Maxlen>& s1, const FLString<Maxlen>& s2) { return !operator==(s1,s2); }
template <size_t Maxlen>
bool
operator==(const FLString<Maxlen>& s1, const std::string& s2);
template <size_t Maxlen>
bool
operator==(const std::string& s1, const FLString<Maxlen>& s2) { return operator==(s2,s1); }
template <size_t Maxlen>
bool
operator!=(const FLString<Maxlen>& s1, const std::string& s2) { return !operator==(s1,s2); }
template <size_t Maxlen>
bool
operator!=(const std::string& s1, const FLString<Maxlen>& s2) { return !operator==(s2,s1); }
template <size_t Maxlen>
bool
operator==(const FLString<Maxlen>& s1, const char* s2);
template <size_t Maxlen>
bool
operator==(const char* s1, const FLString<Maxlen>& s2) { return operator==(s2,s1); }
template <size_t Maxlen>
bool
operator!=(const FLString<Maxlen>& s1, const char* s2) { return !operator==(s1,s2); }
template <size_t Maxlen>
bool
operator!=(const char* s1, const FLString<Maxlen>& s2) { return !operator==(s2,s1); }
//
// Implementations
//
template <size_t Maxlen>
FLString<Maxlen>::
FLString()
{
for(size_t n = 0; n <= Maxlen; ++n)
{
data_[n] = '\0';
}
}
template <size_t Maxlen>
FLString<Maxlen>::
FLString(const char* str)
{
size_t n = 0;
for(;str[n] != '\0' && n < Maxlen; ++n)
{
data_[n] = str[n];
}
#ifdef DEBUG
if(n == Maxlen && str[n] != '\0')
{
std::cout << "Warning: input to FLString exceeds " << Maxlen << " characters, truncating." << std::endl;
}
#endif
for(;n <= Maxlen; ++n) data_[n] = '\0';
}
template <size_t Maxlen>
FLString<Maxlen>::
FLString(const std::string& str)
{
size_t ll = std::min(str.size(),Maxlen);
size_t n = 0;
for(; n < ll; ++n)
{
data_[n] = str[n];
}
#ifdef DEBUG
if(str.size() > Maxlen)
{
std::cout << "Warning: input to FLString exceeds " << Maxlen << " characters, truncating." << std::endl;
}
#endif
for(;n <= Maxlen; ++n) data_[n] = '\0';
}
template <size_t Maxlen>
char FLString<Maxlen>::
operator[](size_t n) const
{
#ifdef DEBUG
if(n >= Maxlen) Error("FLString index out of range");
#endif
return data_[n];
}
template <size_t Maxlen>
size_t FLString<Maxlen>::
length() const
{
size_t l = 0;
while(data_[l] != '\0' && l < Maxlen)
{
++l;
}
return l;
}
template <size_t Maxlen>
std::ostream&
operator<<(std::ostream& s, const FLString<Maxlen>& str)
{
size_t n = 0;
const char* d = str.data();
for(; d[n] != '\0' && n < Maxlen; ++n)
{
s << d[n];
}
return s;
}
template <size_t Maxlen>
bool
operator==(const FLString<Maxlen>& s1, const FLString<Maxlen>& s2)
{
for(size_t n = 0; n < Maxlen; ++n)
{
if(s1[n] != s2[n]) return false;
}
return true;
}
template <size_t Maxlen>
bool
operator==(const FLString<Maxlen>& s1,
const std::string& s2)
{
const size_t ll = std::min(s2.size(),Maxlen);
for(size_t n = 0; n < ll; ++n)
{
if(s1[n] != s2[n]) return false;
}
return true;
}
template <size_t Maxlen>
bool
operator==(const FLString<Maxlen>& s1, const char* s2)
{
for(size_t n = 0; n < Maxlen; ++n)
{
if(s1[n] != s2[n]) return false;
if(s2[n] == '\0') break;
}
return true;
}
//template <size_t Maxlen>
//bool
//operator==(const FLString<Maxlen>& s1, const char s2[7])
// {
// size_t N = 7;
// const size_t ll = std::min(N,Maxlen);
// for(size_t n = 0; n < ll; ++n)
// {
// if(s1[n] != s2[n]) return false;
// }
// return true;
// }
//
//template <size_t Maxlen, size_t N>
//bool
//operator==(const char s1[7], const FLString<Maxlen>& s2)
// {
// size_t N = 7;
// const size_t ll = std::min(N,Maxlen);
// for(size_t n = 0; n < ll; ++n)
// {
// if(s1[n] != s2[n]) return false;
// }
// return true;
// }
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/tensor/sliceten.h
|
<filename>itensor/tensor/sliceten.h
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_SLICETEN_H_
#define __ITENSOR_SLICETEN_H_
#include "itensor/util/iterate.h"
#include "itensor/tensor/ten.h"
#include "itensor/tensor/slicemat.h"
#include "itensor/tensor/slicerange.h"
namespace itensor {
template<typename Ten_, typename C1, typename C2>
ref_type<Ten_>
subTensor(Ten_ && T,
C1 const& start,
C2 const& stop);
template<typename Ten_>
ref_type<Ten_>
subIndex(Ten_ && T,
size_t ind,
size_t start,
size_t stop);
//group contiguous indices
template<typename Ten_>
ref_type<Ten_>
groupInds(Ten_ && T,
size_t istart,
size_t iend);
template<typename Ten_, typename Perm_>
ref_type<Ten_>
permute(Ten_ const& t,
Perm_ const& P);
///
/// Implementations
///
template<typename Ten_, typename C1, typename C2>
auto
subTensor(Ten_ && T,
C1 const& start,
C2 const& stop) -> ref_type<Ten_>
{
static_assert(!std::is_same<Ten_&&,Tensor&&>::value,"Cannot pass temp/rvalue Tensor to subTensor");
static_assert(!std::is_same<Ten_&&,Vector&&>::value,"Cannot pass temp/rvalue Vector to subTensor");
static_assert(!std::is_same<Ten_&&,Matrix&&>::value,"Cannot pass temp/rvalue Matrix to subTensor");
auto r = T.order();
#ifdef DEBUG
using stop_type = decltype(*stop.begin());
if(r != decltype(r)(start.size())) throw std::runtime_error("subTensor: wrong size of start");
if(r != decltype(r)(stop.size())) throw std::runtime_error("subTensor: wrong size of stop");
auto st_ = start.begin();
auto sp_ = stop.begin();
for(decltype(r) j = 0; j < r; ++j, ++st_, ++sp_)
{
if(*sp_ > stop_type(T.extent(j))) throw std::runtime_error("subTensor: stop value too large");
if(*st_ >= *sp_) throw std::runtime_error("subTensor: start value >= stop value");
}
#endif
size_t offset = 0;
auto rb = RangeBuilder(r);
auto st = start.begin();
auto sp = stop.begin();
for(decltype(r) j = 0; j < r; ++j, ++st, ++sp)
{
offset += T.stride(j) * (*st);
rb.setIndStr(j,(*sp)-(*st),T.stride(j));
}
return makeRef(T.store()+offset,rb.build());
}
template<typename Ten_>
auto
subIndex(Ten_ && T,
size_t ind,
size_t start,
size_t stop) -> ref_type<Ten_>
{
static_assert(!std::is_same<Ten_&&,Tensor&&>::value,"Cannot pass temp/rvalue Tensor to subIndex");
static_assert(!std::is_same<Ten_&&,Vector&&>::value,"Cannot pass temp/rvalue Vector to subIndex");
static_assert(!std::is_same<Ten_&&,Matrix&&>::value,"Cannot pass temp/rvalue Matrix to subIndex");
#ifdef DEBUG
if(ind >= size_t(T.order())) throw std::runtime_error("subIndex: index out of range");
#endif
auto R = T.range();
R[ind].ind = stop-start;
return makeRef(T.store()+T.stride(ind)*start,std::move(R));
}
template<typename Ten_>
auto
groupInds(Ten_ && T,
size_t istart,
size_t iend) -> ref_type<Ten_>
{
return makeRef(T.store(),groupIndsRange(T.range(),istart,iend));
}
template<typename Ten_, typename Perm_>
auto
permute(Ten_ && t,
Perm_ const& P) -> ref_type<Ten_>
{
return makeRef(t.store(),permuteRange(t.range(),P));
}
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/util/error.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef _error_h
#define _error_h
#include <cstdlib>
#include <stdexcept>
#include <iostream>
namespace itensor{
void error(const std::string& s);
void error(const std::string& s, int line,const char* file);
#define Error(exp) error(exp, __LINE__, __FILE__)
struct ITError : std::runtime_error
{
explicit
ITError(const std::string& message = "")
: std::runtime_error(message) { }
virtual
~ITError() { }
};
struct ResultIsZero : ITError
{
ResultIsZero(const std::string& message)
: ITError(message)
{ }
};
inline std::ostream&
operator<<(std::ostream& s, const ITError& e)
{
s << e.what();
return s;
}
void inline
error(const std::string& s)
{
std::cerr << std::endl << s << std::endl;
std::cout << std::endl << s << std::endl;
std::cout.flush();
abort();
}
void inline
error(const std::string& s, int line, const char* file = 0)
{
std::cerr << "From line " << line;
if(file != 0) std::cerr << ", file " << file;
std::cerr << std::endl;
std::cerr << std::endl << s << std::endl;
std::cout << std::endl << s << std::endl;
std::cout.flush();
std::cerr.flush();
abort();
}
}
#endif
|
chuffa/ITensor
|
itensor/util/multalloc.h
|
<gh_stars>100-1000
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_MULTALLOC_H
#define __ITENSOR_MULTALLOC_H
#include <memory>
#include <vector>
#include "itensor/global.h"
#ifdef DEBUG
#define CHECK_IND(X) check_ind(X);
#else
#define CHECK_IND(X)
#endif
#ifdef DEBUG
#define CHECK_SIZE(X) check_size(X);
#else
#define CHECK_SIZE(X)
#endif
#ifdef DEBUG
#define CHECK_NOT_FULL check_not_full();
#else
#define CHECK_NOT_FULL
#endif
#ifdef DEBUG
#define CHECK_NOT_EMPTY check_not_empty();
#else
#define CHECK_NOT_EMPTY
#endif
#ifdef DEBUG
#define CHECK_ALLOCATED check_allocated();
#else
#define CHECK_ALLOCATED
#endif
namespace itensor {
//
// //Sample usage:
// MultAlloc<Real,3> ma;
// ma.add(size0);
// ma.add(size1);
// ma.allocate(); //do single allocation for both memory ranges
// //ma.add(size2); //error: can't request more memory, idea is to only allocate once
// auto* p0 = ma[0];
// auto* p1 = ma[1];
//
template<typename T, size_t MaxNAlloc>
class MultAlloc
{
public:
using size_type = std::size_t;
using pointer = T*;
private:
struct SizeOff
{
size_type size = 0;
size_type offset = 0;
SizeOff() { }
SizeOff(size_type s, size_type o) : size(s), offset(o) { }
};
size_type arrsize_ = 0;
std::array<SizeOff,MaxNAlloc> sos_;
std::vector<T> v_;
//T* p_ = nullptr;
public:
MultAlloc() { }
//~MultAlloc()
// {
// if(p_)
// {
// if(Global::debug1()) println("<<<< Deallocating MultAlloc, p_=",p_);
// CHECK_NOT_EMPTY
// auto totsize = sos_[arrsize_-1].offset+sos_[arrsize_-1].size;
// a_.deallocate(p_,totsize);
// }
// }
size_type
size() const { return arrsize_; }
size_type
data_size() const { return v_.size(); }
size_type
size(size_type i) const
{
CHECK_IND(i)
return sos_[i].size;
}
size_type constexpr
max_nalloc() const { return MaxNAlloc; }
void
add(size_type size)
{
CHECK_NOT_FULL
//if(p_) throw std::runtime_error("Can't add to MultAlloc after allocated");
if(!v_.empty()) throw std::runtime_error("Can't add to MultAlloc after allocated");
if(arrsize_==0)
{
sos_[arrsize_] = SizeOff(size,0);
}
else
{
auto& prev = sos_[arrsize_-1];
sos_[arrsize_] = SizeOff(size,prev.offset+prev.size);
}
++arrsize_;
}
void
allocate()
{
CHECK_NOT_EMPTY
auto totsize = sos_[arrsize_-1].offset+sos_[arrsize_-1].size;
v_.resize(totsize);
}
pointer
operator[](size_type i)
{
CHECK_IND(i)
CHECK_ALLOCATED
CHECK_SIZE(i)
#ifdef DEBUG
if(sos_[i].offset+sos_[i].size > v_.size()) throw std::out_of_range("data out of range in MultAlloc");
#endif
return v_.data()+sos_[i].offset;
}
private:
void
check_ind(size_type i) const
{
if(i >= arrsize_) throw std::out_of_range("index out of range in MultAlloc");
}
void
check_size(size_type i) const
{
if(sos_[i].size==0) throw std::out_of_range("attempted to access size zero element of MultAlloc");
}
void
check_not_empty() const
{
if(arrsize_==0) throw std::out_of_range("MultAlloc is empty");
}
void
check_not_full() const
{
if(arrsize_ >= max_nalloc()) throw std::out_of_range("exceeded max number in MultAlloc");
}
void
check_allocated() const
{
if(v_.empty()) throw std::runtime_error("MultAlloc has not been allocated");
}
};
#undef CHECK_IND
#undef CHECK_SIZE
#undef CHECK_NOT_FULL
#undef CHECK_NOT_EMPTY
#undef CHECK_ALLOCATED
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/mps/sites/spintwo.h
|
<reponame>chuffa/ITensor
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// 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.
//
#pragma once
#include "itensor/mps/siteset.h"
#include "itensor/mps/sites/spinhalf.h"
#include "itensor/util/str.h"
// Code written by <NAME>
namespace itensor {
class SpinTwo : public SiteSet
{
public:
SpinTwo() { }
SpinTwo(int N,
Args const& args = Args::global());
void
read(std::istream& s);
};
class SpinTwoSite
{
Index s;
public:
SpinTwoSite(Index I) : s(I) { }
SpinTwoSite(Args const& args = Args::global())
{
auto ts = TagSet("Site,S=2");
if( args.defined("SiteNumber") )
ts.addTags("n="+str(args.getInt("SiteNumber")));
auto conserveQNs = args.getBool("ConserveQNs",true);
auto conserveSz = args.getBool("ConserveSz",conserveQNs);
if(conserveSz)
{
s = Index{QN({"Sz",+4}),1,
QN({"Sz",+2}),1,
QN({"Sz",0}),1,
QN({"Sz",-2}),1,
QN({"Sz",-4}),1,Out,ts};
}
else
{
s = Index{5,ts};
}
}
Index
index() const { return s; }
IndexVal
state(std::string const& state)
{
if (state == "Up" || state == "4")
{
return s(1);
}
else if (state == "Upi" || state == "2")
{
return s(2);
}
else if (state == "Z0" || state == "0")
{
return s(3);
}
else if (state == "Dni" || state == "-2")
{
return s(4);
}
else if (state == "Dn" || state == "-4")
{
return s(5);
}
else
{
throw ITError("State " + state + " not recognized");
}
return IndexVal{};
}
ITensor
op(std::string const& opname,
Args const& args) const
{
const Real val1 = std::sqrt(6.0)/2.0;
const Real val2 = std::sqrt(6.0);
auto sP = prime(s);
auto Up = s(1);
auto UpP = sP(1);
auto Upi = s(2);
auto UpiP = sP(2);
auto Z0 = s(3);
auto Z0P = sP(3);
auto Dni = s(4);
auto DniP = sP(4);
auto Dn = s(5);
auto DnP = sP(5);
auto Op = ITensor(dag(s),sP);
if (opname == "Sz")
{
Op.set(Up,UpP,+2.0);
Op.set(Upi,UpiP,+1.0);
Op.set(Dni,DniP,-1.0);
Op.set(Dn,DnP,-2.0);
}
else if (opname == "Sx")
{
Op.set(Up,UpiP,1.0);
Op.set(Upi,UpP,1.0);
Op.set(Upi,Z0P,val1); // val1 = sqrt(6)/2 = = 1.2247...
Op.set(Z0,UpiP,val1);
Op.set(Z0,DniP,val1);
Op.set(Dni,Z0P,val1);
Op.set(Dni,DnP,1.0);
Op.set(Dn,DniP,1.0);
}
else if (opname == "ISy") // defined as i*Sy
{
Op.set(Up,UpiP,-1.0);
Op.set(Upi,UpP,1.0);
Op.set(Upi,Z0P,-val1);
Op.set(Z0,UpiP,val1);
Op.set(Z0,DniP,-val1);
Op.set(Dni,Z0P,val1);
Op.set(Dni,DnP,-1.0);
Op.set(Dn,DniP,1.0);
}
else if (opname == "Sy")
{
Op.set(Up,UpiP,1.0*Cplx_i);
Op.set(Upi,UpP,-1.0*Cplx_i);
Op.set(Upi,Z0P,val1*Cplx_i);
Op.set(Z0,UpiP,-val1*Cplx_i);
Op.set(Z0,DniP,val1*Cplx_i);
Op.set(Dni,Z0P,-val1*Cplx_i);
Op.set(Dni,DnP,1.0*Cplx_i);
Op.set(Dn,DniP,-1.0*Cplx_i);
}
else if (opname == "Sp" || opname == "S+")
{
Op.set(Upi,UpP,2.0);
Op.set(Z0,UpiP,val2);
Op.set(Dni,Z0P,val2);
Op.set(Dn,DniP,2.0);
}
else if (opname == "Sm" || opname == "S-")
{
Op.set(Up,UpiP,2.0);
Op.set(Upi,Z0P,val2);
Op.set(Z0,DniP,val2);
Op.set(Dni,DnP,2.0);
}
else if (opname == "Sz2")
{
Op.set(Up,UpP,4);
Op.set(Upi,UpiP,1);
Op.set(Dni,DniP,1);
Op.set(Dn,DnP,4);
}
else if (opname == "Sx2")
{
Op.set(Up,UpP,1.0);
Op.set(Up,Z0P,val1);
Op.set(Upi,UpiP,2.5);
Op.set(Upi,DniP,1.5);
Op.set(Z0,UpP,val1);
Op.set(Z0,Z0P,3.0);
Op.set(Z0,DnP,val1);
Op.set(Dni,UpiP,1.5);
Op.set(Dni,DniP,2.5);
Op.set(Dn,Z0P,val1);
Op.set(Dn,DnP,1.0);
}
else if (opname == "Sy2")
{
Op.set(Up,UpP,1.0);
Op.set(Up,Z0P,-val1);
Op.set(Upi,UpiP,2.5);
Op.set(Upi,DniP,-1.5);
Op.set(Z0,UpP,-val1);
Op.set(Z0,Z0P,3.0);
Op.set(Z0,DnP,-val1);
Op.set(Dni,UpiP,-1.5);
Op.set(Dni,DniP,2.5);
Op.set(Dn,Z0P,-val1);
Op.set(Dn,DnP,1.0);
}
else if (opname == "projUp")
{
Op.set(Up,UpP,1);
}
else if (opname == "projUpi")
{
Op.set(Upi,UpiP,1);
}
else if (opname == "projZ0")
{
Op.set(Z0,Z0P,1);
}
else if (opname == "projDni")
{
Op.set(Dni,DniP,1);
}
else if (opname == "projDn")
{
Op.set(Dn,DnP,1);
}
else if (opname == "S2")
{
Op.set(Up,UpP,6);
Op.set(Upi,UpiP,6);
Op.set(Z0,Z0P,6);
Op.set(Dni,DniP,6);
Op.set(Dn,DniP,6);
}
else
{
throw ITError("Operator " + opname + " name not recognized");
}
return Op;
}
//
// Deprecated, for backwards compatibility
//
SpinTwoSite(int n, Args const& args = Args::global())
{
*this = SpinTwoSite({args,"SiteNumber=",n});
}
}; //SpinTwoSite
inline SpinTwo::
SpinTwo(int N,
Args const& args)
{
auto shedge = args.getBool("SHalfEdge",false);
auto Lshedge = args.getBool("SHalfLeftEdge",false);
auto sites = SiteStore(N);
auto start = 1;
if(shedge || Lshedge)
{
if(args.getBool("Verbose",false)) println("Placing a S=1/2 at site 1");
sites.set(1,SpinHalfSite({args,"SiteNumber=",1}));
start = 2;
}
for(int j = start; j < N; ++j)
{
sites.set(j,SpinTwoSite({args,"SiteNumber=",j}));
}
if(shedge)
{
if(args.getBool("Verbose",false)) println("Placing a S=1/2 at site N=",N);
sites.set(N,SpinHalfSite({args,"SiteNumber=",N}));
}
else
{
sites.set(N,SpinTwoSite({args,"SiteNumber=",N}));
}
SiteSet::init(std::move(sites));
}
void inline SpinTwo::
read(std::istream& s)
{
int N = itensor::read<int>(s);
if(N > 0)
{
auto store = SiteStore(N);
for(int j = 1; j <= N; ++j)
{
auto I = Index{};
I.read(s);
if(dim(I) == 5) store.set(j,SpinTwoSite(I));
else if(dim(I) == 2) store.set(j,SpinHalfSite(I));
else throw ITError(format("SpinTwo cannot read index of size %d",dim(I)));
}
init(std::move(store));
}
}
} //namespace itensor
|
chuffa/ITensor
|
itensor/tensor/rangeiter.h
|
<reponame>chuffa/ITensor<filename>itensor/tensor/rangeiter.h
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_RANGEITER_H_
#define __ITENSOR_RANGEITER_H_
#include <iterator>
#include "itensor/tensor/types.h"
namespace itensor {
template<typename range_type_>
class RangeIter
{
public:
using range_type = range_type_;
using size_type = typename range_type::size_type;
using offset_type = size_type;
using reference = size_type &;
using iterator_category = std::forward_iterator_tag;
using ind_type = InfArray<size_type,11ul>;
using const_ind_iterator = typename ind_type::const_iterator;
private:
range_type const* prange_ = nullptr;
offset_type off_ = 0;
ind_type ind_;
public:
RangeIter()
: prange_(nullptr),
off_(0)
{ }
RangeIter(range_type const& R)
: prange_(&R),
off_(0),
ind_(R.order(),R.start())
{ }
RangeIter const&
operator*() const { return *this; }
size_type const&
operator[](size_type n) const { return ind_[n]; }
size_type
size() const { return ind_.size(); }
offset_type
offset() const { return off_; }
ind_type
index() const { return ind_; }
range_type const&
range() const { return *prange_; }
bool
notDone() const
{
return off_ != std::numeric_limits<offset_type>::max();
}
RangeIter&
operator++() { increment(); return *this; }
RangeIter
operator++(int) { auto ct = *this; ct.increment(); return ct; }
bool
operator==(RangeIter const& o) const
{
#ifdef DEBUG
if(prange_ != o.prange_)
Error("Can't compare RangeIter created from different range objects");
#endif
return off_==o.off_;
}
bool
operator!=(RangeIter const& o) const { return !operator==(o); }
const_ind_iterator
begin() const { return ind_.begin(); }
const_ind_iterator
end() const { return ind_.end(); }
private:
void
increment()
{
using rextent = decltype(range().extent(0));
#ifdef DEBUG
if(range().order() == 0) Error("Can't increment RangeIter made from order 0 range");
#endif
auto r = range().order();
ind_[0] += 1;
off_ += range().stride(0);
if(rextent(ind_[0]-range().start()) == range().extent(0))
{
for(decltype(r) n = 1; n < r; ++n)
{
ind_[n-1] = range().start();
off_ -= range().extent(n-1)*range().stride(n-1);
ind_[n] += 1;
off_ += range().stride(n);
if(rextent(ind_[n]-range().start()) < range().extent(n)) return;
}
//will only reach this line when totally done
off_ = std::numeric_limits<offset_type>::max();
}
}
public:
//For developer use only; for making end iterator
RangeIter static
makeEnd(range_type const& R)
{
RangeIter end;
end.off_ = std::numeric_limits<offset_type>::max();
end.prange_ = &R;
return end;
}
};
template<typename R>
std::ostream&
operator<<(std::ostream & s,
RangeIter<R> const& it)
{
auto r = it.range().order();
s << format("%*d",3,it.offset()) << " (";
for(decltype(r) j = 0; j < r; ++j)
{
s << it[j];
if(1+j != r) s << ",";
}
s << ")";
return s;
}
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/index.h
|
<gh_stars>1-10
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_INDEX_H
#define __ITENSOR_INDEX_H
#include "itensor/global.h"
#include "itensor/tagset.h"
#include "itensor/arrow.h"
#include "itensor/qn.h"
#include <thread>
namespace itensor {
//Forward declarations
class IndexVal;
using QNInt = std::pair<QN,long>;
namespace detail {
struct RandomID
{
using rng_type = std::mt19937_64;
using result_type = typename rng_type::result_type;
std::hash<std::thread::id> hasher;
RandomID()
: rng(std::clock() + hasher(std::this_thread::get_id()))
{ }
result_type
operator()() { return rng(); }
private:
rng_type rng;
};
struct SequentialID
{
using result_type = std::uint_fast32_t;
SequentialID() : id(1) { }
result_type
operator()()
{
auto res = id;
id += 1;
return res;
}
private:
result_type id = 0;
};
} //namespace detail
//
// Index
//
// Represents a tensor index of fixed bond dimension m.
//
// Can be compared with == operator (returns true if both
// are copies of the same Index instance).
//
class IQIndexDat;
class Index
{
public:
using IDGenerator = detail::RandomID;
using id_type = IDGenerator::result_type;
using extent_type = int;
using qnstorage = std::vector<QNInt>;
using qn_ptr = std::shared_ptr<IQIndexDat>;
private:
id_type id_;
extent_type dim_;
Arrow dir_ = Out;
qn_ptr pd;
TagSet tags_;
public:
Index();
explicit
Index(long dim,
TagSet const& ts = TagSet("0"));
// Deprecated
explicit
Index(std::string s,
long m)
{
Error("Index(string,int) constructor deprecated, use Index(int,...) instead");
}
template<typename... QN_Sizes>
Index(QN const& q1, long size1,
QN_Sizes const&... qnsizes);
Index(qnstorage && qns,
TagSet const& ts = TagSet("0"));
Index(qnstorage && qns,
Arrow dir,
TagSet const& ts = TagSet("0"));
// Returns the dimension of this Index
long
dim() const { return dim_; }
// Returns the prime level
int
primeLevel() const { return tags_.primeLevel(); }
// Returns the TagSet
TagSet
tags() const { return tags_; }
id_type
id() const { return id_; }
// Evaluates to false if Index is default constructed.
explicit operator bool() const;
// (Explicitly) convertible to integer types
explicit operator int() const { return dim(); }
explicit operator long() const { return dim(); }
explicit operator size_t() const { return dim(); }
// Add tags
Index&
addTags(const TagSet& t) { tags_.addTags(t); return *this; }
// Remove tags
Index&
removeTags(const TagSet& t) { tags_.removeTags(t); return *this; }
// Set tags
Index&
setTags(const TagSet& t) { tags_.setTags(t); return *this; }
// Remove all tags
Index&
noTags() { tags_.noTags(); return *this; }
// Set tags
Index&
replaceTags(const TagSet& tsold, const TagSet& tsnew) { tags_.replaceTags(tsold,tsnew); return *this; }
// Sets the prime level to a specified value.
Index&
setPrime(int p);
// Sets the prime level to 0.
Index&
noPrime();
// Increase primelevel by 1 (or by optional amount inc)
Index&
prime(int inc = 1);
//Return an IndexVal with specified value
IndexVal
operator()(long val) const;
IndexVal
operator=(long val) const;
//define size()==dim() in order to do
//for(auto n : range(I)) { ... } for some Index I
long
size() const { return dim(); }
// Write Index to binary output stream.
void
write(std::ostream& s) const;
// Read Index from binary input stream.
Index&
read(std::istream& s);
//
// QN related functions
//
//number of quantum number blocks
long
nblock() const;
//1-indexed
long
blocksize(long i) const;
//1-indexed
QN const&
qn(long i) const;
Arrow
dir() const { return dir_; }
void
setDir(Arrow ndir) { dir_ = ndir; }
Index&
dag() { dir_ = -dir_; return *this; }
qn_ptr const&
store() const { return pd; }
Index&
sim(Index const& I)
{
*this = I;
id_ = generateID();
return *this;
}
private:
void
makeStorage(qnstorage && qi);
Index::id_type
generateID();
public:
//
// Advanced / developer methods.
// Not intended for normal usage.
//
// Constructor taking a QN pointer
Index(qn_ptr const& p,
TagSet const& tags = TagSet());
Index(qn_ptr const& p,
Arrow dir,
TagSet const& tags);
Index(id_type id,
long dim,
Arrow dir,
TagSet const& ts);
//0-indexed
long
blocksize0(long i) const;
void
removeQNs() { pd.reset(); }
public:
//Deprecated: prefer to use I.dim() or dim(I)
//long
//m() const
// {
// Global::warnDeprecated(".m() is deprecated in favor of dim(Index)");
// return this->dim();
// }
}; //class Index
// i1 compares equal to i2 if i2 is a copy of i1 with same primelevel
bool
operator==(Index const& i1, Index const& i2);
bool
operator!=(Index const& i1, Index const& i2);
// Useful for sorting Index objects
bool
operator<(Index const& i1, Index const& i2);
bool
operator>(Index const& i1, Index const& i2);
//
// IndexVal
//
// Class pairing an Index of dimension m
// with a specific value i where 1 <= i <= m
//
class IndexVal
{
public:
Index index;
long val;
IndexVal();
IndexVal(const Index& index, long val_);
long
dim() const { return index.dim(); }
explicit operator bool() const { return bool(index); }
// Add tags
IndexVal&
addTags(const TagSet& t) { index.addTags(t); return *this; }
// Remove tags
IndexVal&
removeTags(const TagSet& t) { index.removeTags(t); return *this; }
// Set tags
IndexVal&
setTags(const TagSet& t) { index.setTags(t); return *this; }
// Remove all tags
IndexVal&
noTags() { index.noTags(); return *this; }
// Set tags
IndexVal&
replaceTags(const TagSet& tsold, const TagSet& tsnew) { index.replaceTags(tsold,tsnew); return *this; }
// Sets the prime level to a specified value.
IndexVal&
setPrime(int p) { index.setPrime(p); return *this; }
// Sets the prime level to 0.
IndexVal&
noPrime() { index.noPrime(); return *this; }
// Increase primelevel by 1 (or by optional amount inc)
IndexVal&
prime(int inc = 1) { index.prime(inc); return *this; }
IndexVal&
dag();
QN const&
qn() const;
//Deprecated: prefer to use .dim()
long
m() const
{
Global::warnDeprecated(".m() is deprecated in favor of dim(IndexVal)");
return this->dim();
}
};
bool
operator==(IndexVal const& iv1, IndexVal const& iv2);
bool
operator!=(IndexVal const& iv1, IndexVal const& iv2);
bool
operator==(IndexVal const& iv, Index const& I);
bool
operator==(Index const& I, IndexVal const& iv);
Index::id_type
id(Index const& I);
long
dim(Index const& I);
long
dim(IndexVal const& I);
int
primeLevel(Index const& I);
TagSet
tags(Index const& I);
//
// Check if Index I contains the tags tsmatch.
//
bool
hasTags(Index I, TagSet const& tsmatch);
bool
hasQNs(Index const& I);
Index
removeQNs(Index I);
bool
hasQNs(IndexVal const& iv);
Index
dag(Index res);
IndexVal
dag(IndexVal res);
QN const&
qn(Index const& i, long b);
QN const&
qn(IndexVal const& iv);
Arrow
dir(Index const& res);
Arrow
dir(IndexVal const& res);
Index const&
index(IndexVal const& res);
long
val(IndexVal const& res);
long
nblock(Index const& i);
long
blocksize(Index const& i, long b);
//
// Tag functions
//
Index
addTags(Index I, TagSet const& t);
Index
removeTags(Index I, TagSet const& t);
Index
setTags(Index I, TagSet const& t);
Index
noTags(Index I);
Index
replaceTags(Index I, TagSet const& tsold, TagSet const& tsnew);
Index
prime(Index I, int plinc = 1);
Index
setPrime(Index I, int plev);
Index
noPrime(Index I);
IndexVal
addTags(IndexVal I, TagSet const& t);
IndexVal
removeTags(IndexVal I, TagSet const& t);
IndexVal
setTags(IndexVal I, TagSet const& t);
IndexVal
noTags(IndexVal I);
IndexVal
replaceTags(IndexVal I, TagSet const& tsold, TagSet const& tsnew);
IndexVal
prime(IndexVal I, int plinc = 1);
IndexVal
setPrime(IndexVal I, int plev);
IndexVal
noPrime(IndexVal I);
// Get the direct sum of two indices
Index
directSum(Index const& i,
Index const& j,
Args const& args = Args::global());
//Make a new index with same properties as I,
//but a different id number (will not compare equal)
Index
sim(Index const& I);
//Returns a string version of this Index's bond dimension.
std::string
showDim(Index const& I);
std::ostream&
operator<<(std::ostream & s, Index const& t);
std::ostream&
operator<<(std::ostream& s, IndexVal const& iv);
void
add(Args& args,
Args::Name const& name,
TagSet const& ts);
TagSet
getTagSet(Args const& args,
Args::Name const& name);
TagSet
getTagSet(Args const& args,
Args::Name const& name,
TagSet const& default_val);
long
QNblock(Index const& I,
QN const& Q);
long
QNblockSize(Index const& I,
QN const& Q);
void
write(std::ostream & s, QNInt const& q);
void
read(std::istream & s, QNInt & q);
bool
isFermionic(Index const& I);
#ifdef ITENSOR_USE_HDF5
void
h5_write(h5::group parent, std::string const& name, Index const& I);
void
h5_read(h5::group parent, std::string const& name, Index & I);
#endif
} //namespace itensor
#include "itensor/index_impl.h"
#endif
|
chuffa/ITensor
|
itensor/tensor/ten.h
|
<reponame>chuffa/ITensor<gh_stars>100-1000
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_TEN_H_
#define __ITENSOR_TEN_H_
#include "itensor/detail/algs.h"
#include "itensor/tensor/teniter.h"
#include "itensor/tensor/range.h"
#include "itensor/tensor/lapack_wrap.h"
namespace itensor {
template<typename range_type, typename T = Real>
class Ten;
template<typename range_type, typename T = Real>
class TenRefc;
template<typename range_type, typename T = Real>
class TenRef;
//Specialize to range_type==Range
using Tensor = Ten<Range,Real>;
using TensorRef = TenRef<Range,Real>;
using TensorRefc = TenRefc<Range,Real>;
using CTensor = Ten<Range,Cplx>;
using CTensorRef = TenRef<Range,Cplx>;
using CTensorRefc = TenRefc<Range,Cplx>;
//1-indexed versions
using Tensor1 = Ten<Range1,Real>;
using TensorRef1 = TenRef<Range1,Real>;
using TensorRefc1 = TenRefc<Range1,Real>;
using CTensor1 = Ten<Range1,Cplx>;
using CTensorRef1 = TenRef<Range1,Cplx>;
using CTensorRefc1 = TenRefc<Range1,Cplx>;
class TensorType { };
template<typename Derived>
struct isTensor
{
constexpr isTensor() { }
bool static constexpr value = std::is_base_of<TensorType,stdx::decay_t<Derived>>::value;
constexpr operator bool() const noexcept { return value; }
};
template<typename Ten_, typename range_type = Range>
using ref_type = typename stdx::decay_t<Ten_>::template ref_type<range_type>;
template<typename Ten_>
using range_type = typename stdx::decay_t<Ten_>::range_type;
template<typename T, bool istensor = isTensor<T>::value >
struct ValTypeHelper { using type = typename stdx::decay_t<T>::value_type; };
template<typename T>
struct ValTypeHelper<T,false> { using type = T; };
template<typename T>
using val_type = typename ValTypeHelper<T>::type;
template<typename TA, typename TB>
using common_type = stdx::conditional_t<(std::is_same<val_type<TA>,Cplx>::value || std::is_same<val_type<TB>,Cplx>::value),
Cplx,
Real>;
template<typename range_type_,typename value_type_>
class TenRefc : public TensorType
{
static_assert(not std::is_const<value_type_>::value,
"value type template argument of TenRefc should not be const");
public:
using range_type = stdx::remove_const_t<range_type_>;
using value_type = value_type_;
using iterator = TenIter<const value_type*,range_type>;
using const_iterator = iterator;
using pointer = const value_type*;
using reference = const value_type&;
using size_type = size_t;
using tensor_type = Ten<range_type,value_type>;
using storage_type = DataRange<const value_type>;
template<typename R_>
using ref_type = TenRefc<R_,value_type>;
template<typename R_>
using const_ref_type = TenRefc<R_,value_type>;
private:
storage_type d_;
const range_type* prange_ = nullptr;
range_type range_;
public:
TenRefc() { }
TenRefc(storage_type dat,
range_type const& range)
: d_(dat),
prange_(&range)
{ }
TenRefc(storage_type dat,
range_type && range)
: d_(dat),
range_(std::move(range))
{
prange_ = &range_;
}
TenRefc(storage_type dat,
const range_type* prange)
: d_(dat),
prange_(prange)
{ }
TenRefc(TenRefc const& t)
{
operator=(t);
}
TenRefc&
operator=(TenRefc const& t);
TenRefc(TenRefc && t)
{
operator=(std::move(t));
}
TenRefc&
operator=(TenRefc && t);
TenRefc(tensor_type const& t) { pointTo(t); }
TenRefc&
operator=(tensor_type const& t) { pointTo(t); return *this; }
TenRefc(tensor_type&& t) = delete;
TenRefc&
operator=(tensor_type&& t) = delete;
bool
ownRange() const { return prange_ == &range_; }
size_type
order() const { return prange_->order(); }
// Deprecated
size_type
r() const { return this->order(); }
size_type
size() const { return dim(*prange_); }
explicit operator bool() const { return bool(d_.data());}
size_type
extent(size_type i) const { return prange_->extent(i); }
size_type
stride(size_type i) const { return prange_->stride(i); }
range_type const&
range() const { return *prange_; }
storage_type const&
store() const { return d_; }
// direct access to data
pointer
data() const { return d_.data(); }
reference
operator()() const;
template <typename... Inds>
reference
operator()(Inds&&... ii) const;
reference
operator[](size_t n) const;
void
clear() { d_.clear(); prange_ = nullptr; }
const_iterator
begin() const { return iterator(d_,*prange_); }
const_iterator
end() const { return iterator::makeEnd(*prange_); }
const_iterator
cbegin() const { return const_iterator(d_,*prange_); }
const_iterator
cend() const { return const_iterator::makeEnd(*prange_); }
void
pointTo(tensor_type const& t);
};
template<typename range_type_, typename value_type_>
class TenRef : public TenRefc<range_type_,value_type_>
{
static_assert(not std::is_const<value_type_>::value,
"value type template argument of TenRef should not be const");
public:
using parent = TenRefc<range_type_,value_type_>;
using range_type = typename parent::range_type;
using value_type = typename parent::value_type;
using iterator = TenIter<value_type*,range_type>;
using const_iterator = TenIter<const value_type*,range_type>;
using pointer = value_type*;
using const_pointer = const value_type*;
using reference = value_type&;
using const_reference = const value_type&;
using size_type = typename parent::size_type;
using tensor_type = typename parent::tensor_type;
using storage_type = DataRange<value_type>;
template<typename R_>
using ref_type = TenRef<R_,value_type>;
template<typename R_>
using const_ref_type = TenRefc<R_,value_type>;
TenRef() { }
TenRef(storage_type dat,
range_type const& range)
: parent(dat,range)
{ }
TenRef(storage_type dat,
range_type && range)
: parent(dat,std::move(range))
{ }
TenRef(storage_type dat,
const range_type* prange)
: parent(dat,prange)
{ }
TenRef(TenRef const& t)
{
operator=(t);
}
TenRef&
operator=(TenRef const& t)
{
parent::operator=(t);
return *this;
}
TenRef(TenRef && t)
{
operator=(std::move(t));
}
TenRef&
operator=(TenRef && t) { parent::operator=(std::move(t)); return *this; }
TenRef(tensor_type & t) { parent::pointTo(t); }
TenRef&
operator=(tensor_type & t) { parent::pointTo(t); return *this; }
storage_type
store() const { return storage_type(data(),parent::store().size()); }
pointer
data() const { return const_cast<pointer>(parent::data()); }
reference
operator()() const { return const_cast<reference>(parent::operator()()); }
template <typename... Inds>
reference
operator()(Inds&&... ii) const
{
return const_cast<reference>(parent::operator()(std::forward<Inds>(ii)...));
}
reference
operator[](size_t n) const;
iterator
begin() const { return iterator(store(),parent::range()); }
iterator
end() const { return iterator::makeEnd(parent::range()); }
};
//Assign to referenced data
template<typename R1, typename R2, typename T>
void
operator&=(TenRef<R1,T> const& A, TenRefc<R2,T> const& B);
//Assign to referenced data
template<typename R1, typename R2, typename T>
void
operator&=(TenRef<R1,T> const& A, Ten<R2,T> const& B);
template<typename R1, typename R2, typename T>
void
operator+=(TenRef<R1,T> const& a, TenRefc<R2,T> const& b);
template<typename R, typename T>
void
operator+=(TenRef<R,T> const& a, Ten<Range,T> const& b);
template<typename R,typename T>
void
operator+=(Ten<Range,T> & a, TenRefc<R,T> const& b);
//template<typename R, typename T>
//void
//operator+=(Ten<R,T> & a, Ten<R,T> const& b);
template<typename R1, typename T1,
typename R2, typename T2,
typename Op>
void
transform(TenRefc<R1,T1> const& from,
TenRef<R2,T2> const& to,
Op&& op);
template<typename V, typename range_type>
auto
makeTenRef(V * p,
size_t max_size,
const range_type* prange)
-> TenRef<stdx::decay_t<stdx::remove_pointer_t<range_type>>,V>
{
using R = stdx::decay_t<stdx::remove_pointer_t<range_type>>;
return TenRef<R,V>({p,max_size},prange);
}
template<typename V, typename range_type>
auto
makeTenRef(V const* p,
size_t max_size,
range_type const* prange)
-> TenRefc<stdx::decay_t<stdx::remove_pointer_t<range_type>>,V>
{
using R = stdx::decay_t<stdx::remove_pointer_t<range_type>>;
return TenRefc<R,V>({p,max_size},prange);
}
template<typename V, typename range_type,
class = stdx::enable_if_t<std::is_rvalue_reference<range_type&&>::value
&& !std::is_pointer<range_type>::value> >
auto
makeTenRef(V * p,
size_t max_size,
range_type && range)
-> TenRef<stdx::decay_t<range_type>,V>
{
using R = stdx::decay_t<range_type>;
static_assert(!std::is_pointer<R>::value,"Error: range type is of pointer type");
return TenRef<R,V>({p,max_size},std::move(range));
}
template<typename V, typename range_type,
class = stdx::enable_if_t<std::is_rvalue_reference<range_type&&>::value
&& !std::is_pointer<range_type>::value> >
auto
makeTenRef(V const* p,
size_t max_size,
range_type && range)
-> TenRefc<stdx::decay_t<range_type>,V>
{
using R = stdx::decay_t<range_type>;
static_assert(!std::is_pointer<R>::value,"Error: range_type is of pointer type");
return TenRefc<R,V>({p,max_size},std::move(range));
}
template<typename V, typename range_type>
auto
makeTenRef(V * p,
size_t offset,
size_t max_size,
range_type const* prange)
-> TenRef<stdx::decay_t<stdx::remove_pointer_t<range_type>>,V>
{
using R = stdx::decay_t<stdx::remove_pointer_t<range_type>>;
return TenRef<R,V>({p,offset,max_size},prange);
}
template<typename V, typename range_type>
auto
makeTenRef(V const* p,
size_t offset,
size_t max_size,
range_type const* prange)
-> TenRefc<stdx::decay_t<stdx::remove_pointer_t<range_type>>,V>
{
using R = stdx::decay_t<stdx::remove_pointer_t<range_type>>;
return TenRefc<R,V>({p,offset,max_size},prange);
}
template<typename V, typename range_type,
class = stdx::enable_if_t<std::is_rvalue_reference<range_type&&>::value
&& !std::is_pointer<range_type>::value> >
auto
makeTenRef(V * p,
size_t offset,
size_t max_size,
range_type && range)
-> TenRef<stdx::decay_t<range_type>,V>
{
using R = stdx::decay_t<range_type>;
static_assert(!std::is_pointer<R>::value,"Error: range_type is of pointer type");
return TenRef<R,V>({p,offset,max_size},std::move(range));
}
template<typename V, typename range_type,
class = stdx::enable_if_t<std::is_rvalue_reference<range_type&&>::value
&& !std::is_pointer<range_type>::value> >
auto
makeTenRef(V const* p,
size_t offset,
size_t max_size,
range_type && range)
-> TenRefc<stdx::decay_t<range_type>,V>
{
using R = stdx::decay_t<range_type>;
static_assert(!std::is_pointer<R>::value,"Error: range_type is of pointer type");
return TenRefc<R,V>({p,offset,max_size},std::move(range));
}
template<typename range_type,typename T>
auto
makeRef(DataRange<T> const& store,
range_type const* prange)
-> TenRef<stdx::decay_t<stdx::remove_pointer_t<range_type>>,T>
{
using R = stdx::decay_t<stdx::remove_pointer_t<range_type>>;
return TenRef<R,T>(store,prange);
}
template<typename range_type,typename T>
auto
makeRef(DataRange<const T> const& store,
range_type const* prange)
-> TenRefc<stdx::decay_t<stdx::remove_pointer_t<range_type>>,T>
{
using R = stdx::decay_t<stdx::remove_pointer_t<range_type>>;
return TenRefc<R,T>(store,prange);
}
template<typename range_type,
typename T,
class = stdx::enable_if_t<std::is_rvalue_reference<range_type&&>::value
&& !std::is_pointer<range_type>::value> >
auto
makeRef(DataRange<T> const& store,
range_type && range)
-> TenRef<stdx::decay_t<range_type>,T>
{
using R = stdx::decay_t<range_type>;
static_assert(!std::is_pointer<R>::value,"Error: range_type is of pointer type");
return TenRef<R,T>(store,std::move(range));
}
template<typename range_type,
typename T,
class = stdx::enable_if_t<std::is_rvalue_reference<range_type&&>::value
&& !std::is_pointer<range_type>::value> >
auto
makeRef(DataRange<const T> const& store,
range_type && range)
-> TenRefc<stdx::decay_t<range_type>,T>
{
using R = stdx::decay_t<range_type>;
static_assert(!std::is_pointer<R>::value,"Error: range_type is of pointer type");
return TenRefc<R,T>(store,std::move(range));
}
template<typename range_type_, typename value_type_>
class Ten : public TensorType
{
public:
using value_type = value_type_;
using storage_type = std::vector<value_type>;
using ref_storage_type = DataRange<value_type>;
using const_ref_storage_type = DataRange<const value_type>;
using iterator = typename storage_type::iterator;
using const_iterator = typename storage_type::const_iterator;
using pointer = stdx::add_pointer_t<value_type>;
using const_pointer = stdx::add_pointer_t<const value_type>;
using reference = typename storage_type::reference;
using const_reference = typename storage_type::const_reference;
using range_type = range_type_;
template<typename R_>
using ref_type = TenRef<R_,value_type>;
template<typename R_>
using const_ref_type = TenRefc<R_,value_type>;
using size_type = typename ref_type<range_type>::size_type;
private:
static_assert(not std::is_const<value_type>::value,
"value type template argument of Ten should not be const");
range_type range_;
storage_type data_;
public:
Ten() { }
template<typename... Dims>
explicit
Ten(size_type d1, Dims&&... rest)
: range_(d1,std::forward<Dims>(rest)...)
{
init();
}
Ten(storage_type && store,
range_type && range)
: range_(std::move(range)),
data_(std::move(store))
{
#ifdef DEBUG
if(!isContiguous(range_)) Error("Tensor required to have contiguous range");
#endif
}
template<typename R>
explicit
Ten(TenRefc<R,value_type> const& ref) { assignFromRef(ref); }
// To cover case like Mat<Cplx>(A) where A is Mat<Real>
template<typename R, typename T>
explicit
Ten(TenRefc<R,T> const& ref) { assignFromRef(ref); }
template<typename R>
Ten&
operator=(TenRefc<R,value_type> const& ref) { assignFromRef(ref); return *this; }
explicit operator bool() const { return !data_.empty(); }
size_type
order() const { return range_.order(); }
// Deprecated
size_type
r() const { return this->order(); }
size_type
size() const { return data_.size(); }
size_type
extent(size_type i) const { return range_.extent(i); }
size_type
stride(size_type i) const { return range_.stride(i); }
range_type const&
range() const { return range_; }
value_type
operator()() const;
template <typename... Inds>
const_reference
operator()(Inds&&... ii) const;
reference
operator()();
template <typename... Inds>
reference
operator()(Inds&&... ii);
const_reference
operator[](size_t n) const;
reference
operator[](size_t n);
//template<typename Indices>
//reference
//operator()(Indices const& ii);
//template<typename Indices>
//const_reference
//operator()(Indices const& ii) const;
iterator
begin() { return data_.begin(); }
iterator
end() { return data_.end(); }
const_iterator
begin() const { return data_.cbegin(); }
const_iterator
end() const { return data_.cend(); }
const_iterator
cbegin() const { return data_.cbegin(); }
const_iterator
cend() const { return data_.cend(); }
pointer
data() { return data_.data(); }
const_pointer
data() const { return data_.data(); }
void
clear() { data_.clear(); range_.clear(); }
ref_storage_type
store() { return ref_storage_type(data(),size()); }
const_ref_storage_type
store() const { return const_ref_storage_type(data(),size()); }
storage_type &
storage() { return data_; }
storage_type const&
storage() const { return data_; }
void
resize(range_type const& newrange)
{
range_ = newrange;
data_.resize(dim(range_));
}
void
swap(Ten & other)
{
range_.swap(other.range_);
data_.swap(other.data_);
}
void
read(std::istream& s)
{
itensor::read(s,range_);
itensor::read(s,data_);
}
void
write(std::ostream& s) const
{
itensor::write(s,range_);
itensor::write(s,data_);
}
private:
void
init()
{
auto len = dim(range_);
#ifdef DEBUG
if(!isContiguous(range_))
throw std::runtime_error("Tensor can only be constructed from contiguous range");
if(len == 0)
throw std::runtime_error("Zero dim in tensor");
#endif
data_.assign(len,0.);
}
template<typename R>
void
assignFromRef(TenRefc<R,value_type> const& ref)
{
range_ = normalRange(ref.range());
data_.resize(dim(range_));
makeRef(*this) &= ref;
}
template<typename R, typename T>
void
assignFromRef(TenRefc<R,T> const& ref)
{
range_ = normalRange(ref.range());
data_.resize(dim(range_));
makeRef(*this) &= ref;
}
};
template<typename R, typename T, typename... VArgs>
auto
offset(TenRefc<R,T> const& t, VArgs&&... vargs) -> size_t
{ return offset(t.range(),std::forward<VArgs>(vargs)...); }
template<typename R, typename T, typename... VArgs>
auto
offset(Ten<R,T> const& t, VArgs&&... vargs) -> size_t
{ return offset(t.range(),std::forward<VArgs>(vargs)...); }
//
// makeRef functions
//
template<typename R,typename T>
auto constexpr
makeRef(TenRef<R,T> const& t) -> decltype(t) { return t; }
template<typename R,typename T>
auto constexpr
makeRef(TenRefc<R,T> const& t) -> decltype(t) { return t; }
template<typename R,typename T>
auto
makeRef(Ten<R,T> & t) -> TenRef<R,T> { return TenRef<R,T>{t}; }
template<typename R,typename T>
auto
makeRef(Ten<R,T> const& t) -> TenRefc<R,T> { return TenRefc<R,T>{t}; }
template<typename R, typename T, typename Arg, typename... Rest>
auto
makeRef(TenRef<R,T> const& t, Arg&& arg, Rest&&... rest)
-> TenRef<R,T>
{
return TenRef<R,T>(t.store(),std::forward<Arg>(arg),std::forward<Rest>(rest)...);
}
template<typename R, typename T, typename Arg, typename... Rest>
auto
makeRef(TenRefc<R,T> const& t, Arg&& arg, Rest&&... rest)
-> TenRefc<R,T>
{
return TenRefc<R,T>(t.store(),std::forward<Arg>(arg),std::forward<Rest>(rest)...);
}
template<typename R,typename T, typename Arg, typename... Rest>
auto
makeRef(Ten<R,T> & t, Arg&& arg, Rest&&... rest)
-> TenRef<R,T>
{
return TenRef<R,T>(t.store(),std::forward<Arg>(arg),std::forward<Rest>(rest)...);
}
template<typename R,typename T, typename Arg, typename... Rest>
auto
makeRef(Ten<R,T> const& t, Arg&& arg, Rest&&... rest)
-> TenRefc<R,T>
{
return TenRefc<R,T>(t.store(),std::forward<Arg>(arg),std::forward<Rest>(rest)...);
}
//This version of makeRef intended to fail instantiation,
//forbids explicitly making TenRefs to temporaries
template<typename R,typename T, typename... VArgs>
auto
makeRef(Ten<R,T> && t, VArgs&&... args)
-> TenRefc<R,T>
{
static_assert(stdx::false_regardless_of<R,VArgs...>::value,"Cannot call makeRef on temporary/rvalue Ten object");
return TenRefc<R,T>{};
}
//
// makeRefc functions
//
template<typename R,typename T>
auto
makeRefc(TenRef<R,T> const& t) -> TenRefc<R,T> { return TenRefc<R,T>{t}; }
template<typename R, typename T>
auto constexpr
makeRefc(TenRefc<R,T> const& t) -> decltype(t) { return t; }
template<typename R,typename T>
auto
makeRefc(Ten<R,T> const& t) -> TenRefc<R,T> { return TenRefc<R,T>{t}; }
//This version of makeRefc intended to fail instantiation,
//forbids explicitly making TenRefs to temporaries
template<typename R,typename T, typename... VArgs>
auto
makeRefc(Ten<R,T> && t, VArgs&&... args)
-> TenRefc<R,T>
{
static_assert(stdx::false_regardless_of<R,T,VArgs...>::value,"Cannot call makeRefc on temporary/rvalue Ten<R>");
return TenRefc<R,T>{};
}
//
// Other functions
//
template<typename R,typename T>
auto
order(TenRefc<R,T> const& t) -> decltype(order(t.range())) { return order(t.range()); }
template<typename R,typename T>
auto
order(Ten<R,T> const& t) -> decltype(order(t.range())) { return order(t.range()); }
template<typename R, typename V>
Real
norm(TenRefc<R,V> const& t);
template<typename R, typename T>
Real
norm(Ten<R,T> const& t) { return norm(makeRefc(t)); }
template<typename R, typename T>
bool
isContiguous(TenRefc<R,T> const& t) { return isContiguous(t.range()); }
template<typename R, typename T>
bool
isContiguous(Ten<R,T> const& t) { return isContiguous(t.range()); }
//Make a scalar (order 0) tensor with value val
Tensor
scalarTen(Real val);
template<typename R, typename V>
void
randomize(TenRef<R,V> const& t);
template<typename R, typename V>
void
randomize(Ten<R,V> & t);
template<typename R>
Data
realData(TenRef<R,Real> const& t) { return Data(t.data(),t.size()); }
template<typename R>
Datac
realData(TenRefc<R,Real> const& t) { return Datac(t.data(),t.size()); }
template<typename R>
Data
realData(TenRef<R,Cplx> const& t) { return Data(reinterpret_cast<Real*>(t.data()),2*t.size()); }
template<typename R>
Datac
realData(TenRefc<R,Cplx> const& t) { return Datac(reinterpret_cast<const Real*>(t.data()),2*t.size()); }
template<typename T, class = stdx::require<isTensor<T>> >
bool constexpr
isReal(T const& t) { return std::is_same<typename T::value_type,Real>::value; }
template<typename T, class = stdx::require<isTensor<T>> >
bool constexpr
isCplx(T const& t) { return std::is_same<typename T::value_type,Cplx>::value; }
//conjugate in-place, modifying elements
template<typename R, typename V>
void
conjugate(TenRef<R,V> const& T);
template<typename R, typename V>
void
conjugate(Ten<R,V> & T);
//return conjugated copy
template<typename R, typename V>
Ten<R,V>
conj(TenRefc<R,V> const& T);
template<typename R, typename V>
Ten<R,V>
conj(Ten<R,V> T);
template<typename R, typename V>
std::ostream&
operator<<(std::ostream & s, TenRef<R,V> const& T);
template<typename R, typename V>
std::ostream&
operator<<(std::ostream & s, TenRefc<R,V> const& T);
template<typename R, typename V>
std::ostream&
operator<<(std::ostream & s, Ten<R,V> const& T);
} //namespace itensor
#include "ten_impl.h"
#endif
|
chuffa/ITensor
|
sample/src/ctmrg.h
|
#include "itensor/all.h"
using namespace itensor;
std::tuple<ITensor, ITensor>
ctmrg(ITensor T,
ITensor Clu,
ITensor Al,
int maxdim,
int nsteps,
Real cutoff = 0.0)
{
auto sh = commonIndex(T, Al);
auto sv = uniqueIndex(T, {Al, prime(Al)}, "0");
auto lv = commonIndex(Clu, Al);
auto lh = uniqueIndex(Clu, Al);
auto Au = replaceInds(Al, {lv, prime(lv), sh},
{lh, prime(lh), sv});
ITensor Uv;
for(auto i : range1(nsteps))
{
// Get the grown corner transfer matrix (CTM)
auto Clu_new = Al * Clu * Au * T;
Clu_new.noPrime();
Clu_new.replaceInds({lh, sh}, {prime(lv), prime(sv)});
// Diagonalize the grown CTM
std::tie(Uv, Clu) = diagPosSemiDef(Clu_new,
{"MaxDim = ", maxdim,
"Tags = ", tags(lv),
"Cutoff = ", cutoff});
lv = commonIndex(Clu, Uv);
lh = setTags(lv, tags(lh));
Clu = toDense(Clu);
Clu.replaceInds({prime(lv)}, {lh});
// The renormalized CTM is the diagonal matrix of eigenvalues
// Normalize the CTM
auto Cl = Clu * prime(dag(Clu), lh);
auto normC = pow(elt(Cl * dag(Cl)), 0.25);
Clu /= normC;
// Calculate the renormalized half row transfer matrix (HRTM)
Uv.noPrime();
Al = Al * Uv * T * dag(prime(Uv));
Al = replaceInds(Al, {prime(sh)}, {sh});
// Normalize the HRTM
auto ACl = Al * Clu * prime(dag(Clu));
auto normA = sqrt(elt(ACl * dag(ACl)));
Al /= normA;
Au = replaceInds(Al, {lv, prime(lv), sh},
{lh, prime(lh), sv});
}
return std::tuple<ITensor, ITensor>({Clu, Al});
}
|
lispysnake/lispysnake2d
|
src/core/input-manager.c
|
<reponame>lispysnake/lispysnake2d
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
static void ls2d_input_manager_destroy(Ls2DInputManager *self);
static void ls2d_input_manager_init(Ls2DInputManager *self);
/**
* Opaque Ls2DInputManager implementation
*/
struct Ls2DInputManager {
Ls2DObject object; /*< Parent */
LsHashmap *key_callbacks;
struct {
ls2d_mouse_button_callback cb;
void *userdata;
} mouse_button;
struct {
ls2d_mouse_motion_callback cb;
void *userdata;
} mouse_motion;
};
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable input_manager_vtable = {
.init = (ls2d_object_vfunc_init)ls2d_input_manager_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_input_manager_destroy,
.obj_name = "Ls2DInputManager",
};
Ls2DInputManager *ls2d_input_manager_new()
{
return LS2D_NEW(Ls2DInputManager, input_manager_vtable);
}
static void ls2d_input_manager_init(Ls2DInputManager *self)
{
self->key_callbacks = ls_hashmap_new(ls_hashmap_simple_hash, ls_hashmap_simple_equal);
}
Ls2DInputManager *ls2d_input_manager_unref(Ls2DInputManager *self)
{
return ls2d_object_unref(self);
}
static void ls2d_input_manager_destroy(Ls2DInputManager *self)
{
if (ls_likely(self->key_callbacks != NULL)) {
ls_hashmap_free(self->key_callbacks);
}
}
static inline bool ls2d_input_manager_process_key(Ls2DInputManager *self, SDL_KeyboardEvent *event,
Ls2DFrameInfo *frame)
{
return false;
}
static inline bool ls2d_input_manager_process_mouse_button(Ls2DInputManager *self,
SDL_MouseButtonEvent *event,
Ls2DFrameInfo *frame)
{
if (ls_unlikely(!self->mouse_button.cb)) {
return false;
}
return self->mouse_button.cb(event, frame, self->mouse_button.userdata);
}
static inline bool ls2d_input_manager_process_mouse_motion(Ls2DInputManager *self,
SDL_MouseMotionEvent *event,
Ls2DFrameInfo *frame)
{
if (ls_unlikely(!self->mouse_motion.cb)) {
return false;
}
return self->mouse_motion.cb(event, frame, self->mouse_motion.userdata);
}
bool ls2d_input_manager_process(Ls2DInputManager *self, SDL_Event *event, Ls2DFrameInfo *frame)
{
switch (event->type) {
case SDL_KEYUP:
case SDL_KEYDOWN:
return ls2d_input_manager_process_key(self, &event->key, frame);
case SDL_MOUSEMOTION:
return ls2d_input_manager_process_mouse_motion(self, &event->motion, frame);
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEBUTTONDOWN:
return ls2d_input_manager_process_mouse_button(self, &event->button, frame);
default:
return false;
}
}
void ls2d_input_manager_set_mouse_button_callback(Ls2DInputManager *self,
ls2d_mouse_button_callback cb, void *userdata)
{
if (ls_unlikely(!self)) {
return;
}
if (ls_likely(cb != NULL)) {
self->mouse_button.cb = cb;
self->mouse_button.userdata = userdata;
} else {
self->mouse_button.cb = NULL;
self->mouse_button.userdata = userdata;
}
}
void ls2d_input_manager_set_mouse_motion_callback(Ls2DInputManager *self,
ls2d_mouse_motion_callback cb, void *userdata)
{
if (ls_unlikely(!self)) {
return;
}
if (ls_likely(cb != NULL)) {
self->mouse_motion.cb = cb;
self->mouse_motion.userdata = userdata;
} else {
self->mouse_motion.cb = NULL;
self->mouse_motion.userdata = userdata;
}
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/entities/tilemap-tmx.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <libxml/xmlreader.h>
#include <unistd.h>
#include "tilemap-private.h"
static bool ls2d_tilemap_walk_tmx(Ls2DTileMap *self, Ls2DTileMapTMX *parser, xmlTextReader *reader);
static bool ls2d_tilemap_load_tileset(Ls2DTileMap *self, Ls2DTileMapTMX *parser,
xmlTextReader *reader);
bool ls2d_tilemap_load_tmx(Ls2DTileMap *self, Ls2DTextureCache *cache, const char *filename)
{
int fd = 0;
autofree(xmlTextReader) *reader = NULL;
bool ret = false;
int r = 0;
Ls2DTileMapTMX parser = { 0 };
parser.cache = cache;
fd = open(filename, O_RDONLY);
if (fd < 0) {
goto fail;
}
/* Not portable. Improve for Windows. */
(void)posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
reader = xmlReaderForFd(fd, filename, NULL, 0);
if (!reader) {
goto fail;
}
while ((r = xmlTextReaderRead(reader)) > 0) {
if (!ls2d_tilemap_walk_tmx(self, &parser, reader)) {
goto fail;
}
}
ret = true;
fail:
if (fd >= 0) {
close(fd);
}
return ret;
}
static bool ls2d_tilemap_load_csv(Ls2DTileMap *self, Ls2DTileMapTMX *parser, const xmlChar *text)
{
autofree(char) *dup = strdup((const char *)text);
int key = 0;
char *csv = NULL;
int x = 0, y = 0;
if (!dup) {
return false;
}
csv = strtok(dup, ",\n");
while (csv) {
key = atoi(csv);
if (!ls2d_tilemap_set_internal(self, parser->layer.idx, x, y, key)) {
return false;
}
++x;
if (x >= parser->map.width) {
x = 0;
y++;
}
csv = strtok(NULL, ",\n");
}
return true;
}
static bool ls2d_tilemap_walk_tmx(Ls2DTileMap *self, Ls2DTileMapTMX *parser, xmlTextReader *reader)
{
const xmlChar *name = NULL;
const xmlChar *value = NULL;
name = xmlTextReaderConstName(reader);
if (!name) {
return true;
}
/* Encountered tileset */
if (parser->in_map && xmlStrEqual(name, BAD_CAST "tileset")) {
if (!ls2d_tilemap_load_tileset(self, parser, reader)) {
return false;
}
return true;
}
/* Encountered layer definition */
if (parser->in_map && xmlStrEqual(name, BAD_CAST "layer")) {
parser->in_layer = !parser->in_layer;
if (!parser->in_layer) {
parser->layer.idx++;
return true;
}
ls2d_tilemap_get_int_attr(reader, &parser->layer.id, "id");
ls2d_tilemap_get_int_attr(reader, &parser->layer.width, "width");
ls2d_tilemap_get_int_attr(reader, &parser->layer.height, "height");
fprintf(stderr,
"Layer %d, %dx%d\n",
parser->layer.id,
parser->layer.width,
parser->layer.height);
if (!ls2d_tilemap_add_layer(self, parser->layer.id)) {
return false;
}
return true;
}
/* Encountered data definition */
if (parser->in_layer && xmlStrEqual(name, BAD_CAST "data")) {
parser->in_data = !parser->in_data;
/* TODO: Determine blob type */
return true;
}
/* Encountered map definition */
if (xmlStrEqual(name, BAD_CAST "map")) {
parser->in_map = true;
if (!parser->in_map) {
return true;
}
/* Handle map attributes */
ls2d_tilemap_get_int_attr(reader, &parser->map.width, "width");
ls2d_tilemap_get_int_attr(reader, &parser->map.tile_width, "tilewidth");
ls2d_tilemap_get_int_attr(reader, &parser->map.height, "height");
ls2d_tilemap_get_int_attr(reader, &parser->map.tile_height, "tileheight");
/* Set up basic attributes now */
self->width = (uint16_t)parser->map.width;
self->height = (uint16_t)parser->map.height;
self->size = self->width * self->height;
/* TODO: Move away from tile_size increments and have tile_height/tile_width */
self->tile_size = parser->map.tile_width;
return true;
}
if (parser->in_data) {
value = xmlTextReaderConstValue(reader);
if (!ls2d_tilemap_load_csv(self, parser, value)) {
return false;
}
}
return true;
}
static bool ls2d_tilemap_load_tileset(Ls2DTileMap *self, Ls2DTileMapTMX *parser,
xmlTextReader *reader)
{
int first_gid = 0;
autofree(xmlChar) *source = NULL;
autofree(Ls2DTileSheet) *tsx = NULL;
ls2d_tilemap_get_int_attr(reader, &first_gid, "firstgid");
source = xmlTextReaderGetAttribute(reader, BAD_CAST "source");
if (!source) {
return false;
}
fprintf(stderr, "Load %s with firstgid %d\n", source, first_gid);
tsx = ls2d_tile_sheet_new(parser->cache, (const char *)source);
if (!tsx) {
return false;
}
ls2d_tilemap_add_tilesheet(self, tsx);
return true;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/entities/basic-entity.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
static void ls2d_basic_entity_init(Ls2DBasicEntity *self);
static void ls2d_basic_entity_destroy(Ls2DBasicEntity *self);
static void ls2d_basic_entity_draw(Ls2DEntity *entity, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame);
static void ls2d_basic_entity_update(Ls2DEntity *entity, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame);
static void ls2d_basic_entity_add_component(Ls2DEntity *entity, Ls2DComponent *component);
static Ls2DComponent *ls2d_basic_entity_get_component(Ls2DEntity *entity, int component_id);
struct Ls2DBasicEntity {
Ls2DEntity parent;
const char *name;
bool had_init;
/* components storage */
LsPtrArray *components;
};
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable entity_vtable = {
.init = (ls2d_object_vfunc_init)ls2d_basic_entity_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_basic_entity_destroy,
.obj_name = "Ls2DBasicEntity",
};
Ls2DEntity *ls2d_basic_entity_new(const char *name)
{
Ls2DBasicEntity *self = LS2D_NEW(Ls2DBasicEntity, entity_vtable);
if (ls_unlikely(!self)) {
return NULL;
}
self->name = name;
return (Ls2DEntity *)self;
}
static void ls2d_basic_entity_init(Ls2DBasicEntity *self)
{
self->components = ls_ptr_array_new();
self->parent.draw = ls2d_basic_entity_draw;
self->parent.update = ls2d_basic_entity_update;
self->parent.add_component = ls2d_basic_entity_add_component;
self->parent.get_component = ls2d_basic_entity_get_component;
}
Ls2DBasicEntity *ls2d_basic_entity_unref(Ls2DBasicEntity *self)
{
return ls2d_object_unref(self);
}
static inline void free_component(void *v)
{
(void)ls2d_component_unref(v);
}
static void ls2d_basic_entity_destroy(Ls2DBasicEntity *self)
{
ls_array_free(self->components, free_component);
}
static void ls2d_basic_entity_add_component(Ls2DEntity *entity, Ls2DComponent *component)
{
Ls2DBasicEntity *self = (Ls2DBasicEntity *)entity;
if (ls_unlikely(!self) || ls_unlikely(!component)) {
SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Ls2DBasicEntity not correctly initialised");
return;
}
ls2d_component_set_parent_entity(component, (Ls2DEntity *)self);
ls_array_add(self->components, ls2d_object_ref(component));
}
/**
* Inform the entity that all components need to draw now
*/
static void ls2d_basic_entity_draw(Ls2DEntity *entity, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame)
{
Ls2DBasicEntity *self = (Ls2DBasicEntity *)entity;
for (uint16_t i = 0; i < self->components->len; i++) {
Ls2DComponent *comp = self->components->data[i];
ls2d_component_draw(comp, cache, frame);
}
}
/**
* Inform the entity that all components need to update now.
*/
static void ls2d_basic_entity_update(Ls2DEntity *entity, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame)
{
Ls2DBasicEntity *self = (Ls2DBasicEntity *)entity;
bool had_init = self->had_init;
for (uint16_t i = 0; i < self->components->len; i++) {
Ls2DComponent *comp = self->components->data[i];
if (!had_init) {
ls2d_component_init(comp, cache, frame);
}
ls2d_component_update(comp, cache, frame);
}
if (!had_init) {
self->had_init = true;
}
}
static Ls2DComponent *ls2d_basic_entity_get_component(Ls2DEntity *entity, int component_id)
{
Ls2DBasicEntity *self = (Ls2DBasicEntity *)entity;
self = (Ls2DBasicEntity *)entity;
/* Easier to have a map in future. */
for (uint16_t i = 0; i < self->components->len; i++) {
Ls2DComponent *comp = self->components->data[i];
if (comp->comp_id == component_id) {
return comp;
}
}
return NULL;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/texture-cache.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include "ls2d.h"
struct Ls2DTextureNode {
SDL_Texture *texture; /**< The real SDL_Texture */
SDL_Rect area; /**< Displayable area for the texture. */
char *filename; /**<The filename we come from */
bool subregion; /**< Whether this node is a subregion. */
struct Ls2DTextureNode *parent;
};
/**
* Construct a new Ls2DTextureCache Object
*/
Ls2DTextureCache *ls2d_texture_cache_new(void);
/**
* Unref an allocated Ls2DTextureCache
*/
Ls2DTextureCache *ls2d_texture_cache_unref(Ls2DTextureCache *self);
/**
* Allocate a texture handle by loading from the given file.
* @note: The texture should ONLY be loaded when an SDL window is available!
*/
Ls2DTextureHandle ls2d_texture_cache_load_file(Ls2DTextureCache *self, const char *filename);
/**
* Create a texture handle subregion from a parent texture.
* This allows us to split up texture into subtextures when using tilesheets.
*/
Ls2DTextureHandle ls2d_texture_cache_subregion(Ls2DTextureCache *self, Ls2DTextureHandle parent,
SDL_Rect subregion);
/**
* Lookup a texture for rendering
*/
const Ls2DTextureNode *ls2d_texture_cache_lookup(Ls2DTextureCache *self, Ls2DFrameInfo *frame,
Ls2DTextureHandle handle);
DEF_AUTOFREE(Ls2DTextureCache, ls2d_texture_cache_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/object.c
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <assert.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include "ls2d.h"
void *ls2d_object_ref(void *v)
{
Ls2DObject *object = v;
if (!v) {
return NULL;
}
int ref_count = atomic_fetch_add(&(object->ref_count), 1);
assert(ref_count >= 0);
return v;
}
void *ls2d_object_unref(void *v)
{
Ls2DObject *object = v;
if (!v) {
return NULL;
}
int ref_count = atomic_fetch_sub(&(object->ref_count), 1);
assert(ref_count > 0);
if (ref_count == 1) {
printf("Killing object %s* %p\n", object->vtable->obj_name, (void *)object);
if (object->vtable->destroy) {
object->vtable->destroy(v);
} else {
free(object);
}
return NULL;
}
return v;
}
void *ls2d_object_init(Ls2DObject *object, Ls2DObjectTable *vtable)
{
assert(object != NULL);
assert(vtable != NULL);
object->ref_count = ATOMIC_VAR_INIT(1);
object->vtable = vtable;
if (ls_unlikely(!object->vtable->init)) {
return object;
}
printf("Init object %s* %p\n", object->vtable->obj_name, (void *)object);
/* TODO: Ensure init passes..? */
object->vtable->init(object);
return object;
}
Ls2DObject *ls2d_object_new(size_t size, Ls2DObjectTable *vtable)
{
void *obj = NULL;
assert(size > sizeof(struct Ls2DObject));
obj = calloc(1, size);
if (!obj) {
fprintf(stderr, "Failed to allocate object %s\n", vtable->obj_name);
return NULL;
}
return ls2d_object_init((Ls2DObject *)obj, vtable);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/demo/demo.c
|
<reponame>lispysnake/lispysnake2d
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <SDL.h>
#include <stdlib.h>
#include "libls.h"
#include "ls2d.h"
/**
* Return an entity that will become the main player.
*/
static Ls2DEntity *demo_add_player(Ls2DScene *scene, Ls2DTextureHandle handle,
Ls2DAnimation *animation)
{
Ls2DEntity *entity = NULL;
autofree(Ls2DComponent) *sprite = NULL;
autofree(Ls2DComponent) *pos = NULL;
autofree(Ls2DComponent) *anim = NULL;
entity = ls2d_basic_entity_new("player");
if (!entity) {
return NULL;
}
sprite = ls2d_sprite_component_new();
if (!sprite) {
return NULL;
}
pos = ls2d_position_component_new();
if (!pos) {
return NULL;
}
anim = ls2d_animation_component_new();
if (!anim) {
return NULL;
}
ls2d_animation_component_add_animation((Ls2DAnimationComponent *)anim,
"walking",
animation);
ls2d_sprite_component_set_texture((Ls2DSpriteComponent *)sprite, handle);
ls2d_entity_add_component(entity, sprite);
ls2d_entity_add_component(entity, pos);
ls2d_entity_add_component(entity, anim);
ls2d_position_component_set_xy((Ls2DPositionComponent *)pos,
(SDL_Point){ .x = 690, .y = 1097 });
ls2d_scene_add_entity(scene, entity);
return entity;
}
/**
* Return an entity that will become an NPC
*/
static Ls2DEntity *demo_add_npc(Ls2DScene *scene, Ls2DTextureHandle handle,
Ls2DAnimation *animation)
{
Ls2DEntity *entity = NULL;
autofree(Ls2DComponent) *sprite = NULL;
autofree(Ls2DComponent) *pos = NULL;
autofree(Ls2DComponent) *anim = NULL;
entity = ls2d_basic_entity_new("npc");
if (!entity) {
return NULL;
}
sprite = ls2d_sprite_component_new();
if (!sprite) {
return NULL;
}
pos = ls2d_position_component_new();
if (!pos) {
return NULL;
}
anim = ls2d_animation_component_new();
if (!anim) {
return NULL;
}
ls2d_animation_component_add_animation((Ls2DAnimationComponent *)anim,
"walking",
animation);
ls2d_sprite_component_set_texture((Ls2DSpriteComponent *)sprite, handle);
ls2d_entity_add_component(entity, sprite);
ls2d_entity_add_component(entity, pos);
ls2d_entity_add_component(entity, anim);
ls2d_position_component_set_xy((Ls2DPositionComponent *)pos,
(SDL_Point){ .x = 610, .y = 1097 });
ls2d_scene_add_entity(scene, entity);
return entity;
}
static uint32_t gids[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 65, 58, 0, 0, 0, 0, 0, 133, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 135, 135, 135, 16, 16, 16, 0, 133,
0, 0, 0, 0, 133, 133, 64, 135, 135, 135, 135, 52, 155, 155, 155, 139, 139, 139,
135, 135, 135, 135, 135, 135, 135, 135, 52, 155, 155, 155, 155, 155, 155, 155, 155, 8,
8, 8, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155,
155, 8, 8, 8
};
static uint32_t gids_2[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 0, 0, 121, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static Ls2DEntity *add_tilemap(Ls2DScene *scene, Ls2DTextureCache *cache)
{
Ls2DEntity *entity = NULL;
autofree(Ls2DTileSheet) *sheet_tsx = NULL;
entity = ls2d_tilemap_new(70, 20, 20);
if (!entity) {
abort();
return NULL;
}
ls2d_scene_add_entity(scene, entity);
sheet_tsx = ls2d_tile_sheet_new_from_tsx(cache, "demo_data/platformer_tiles.tsx");
ls2d_tilemap_set_tilesheet((Ls2DTileMap *)entity, sheet_tsx);
ls2d_tilemap_add_layer((Ls2DTileMap *)entity, 0);
ls2d_tilemap_add_layer((Ls2DTileMap *)entity, 1);
for (int x = 0; x < 20; x++) {
for (int y = 0; y < 20; y++) {
const int index = x + 20 * y;
ls2d_tilemap_set_tile((Ls2DTileMap *)entity,
0,
x,
y,
(Ls2DTile){ .gid = gids[index] });
ls2d_tilemap_set_tile((Ls2DTileMap *)entity,
1,
x,
y,
(Ls2DTile){ .gid = gids_2[index] });
}
}
return entity;
}
static Ls2DEntity *add_tilemap2(Ls2DScene *scene, Ls2DTextureCache *cache)
{
Ls2DEntity *entity = NULL;
entity = ls2d_tilemap_new_from_tmx("demo_data/platformer.tmx");
if (!entity) {
abort();
return NULL;
}
ls2d_scene_add_entity(scene, entity);
return entity;
}
static bool mouse_callback(SDL_MouseMotionEvent *event, Ls2DFrameInfo *frame, void *userdata)
{
Ls2DCamera *camera = userdata;
ls2d_camera_set_xy(camera, (SDL_Point){ .x = event->x, .y = event->y });
return true;
}
static bool demo_init(Ls2DGame *game)
{
fprintf(stderr, "Game init\n");
return true;
}
static void demo_destroy(Ls2DGame *game)
{
fprintf(stderr, "Game end\n");
}
/**
* Main entry point to the demo.
*/
int main(__ls_unused__ int argc, __ls_unused__ char **argv)
{
autofree(Ls2DEngine) *engine = NULL;
autofree(Ls2DScene) *scene = NULL;
autofree(Ls2DEntity) *player = NULL;
autofree(Ls2DEntity) *npc = NULL;
autofree(Ls2DEntity) *tilemap = NULL;
autofree(Ls2DTileSheet) *sheet = NULL;
autofree(Ls2DTileSheet) *sheet_npc = NULL;
autofree(Ls2DAnimation) *walking = NULL;
autofree(Ls2DAnimation) *walking_npc = NULL;
autofree(Ls2DCamera) *camera = NULL;
Ls2DInputManager *imanager = NULL;
Ls2DGame game = { 0 };
game.funcs = (Ls2DGameVTable){
.init = demo_init,
.destroy = demo_destroy,
};
SDL_Rect world_bounds = { 0 };
world_bounds.w = 1024;
world_bounds.h = 2468;
Ls2DTextureCache *cache = NULL;
/* Construct new engine */
engine = ls2d_engine_new(1366, 768);
if (!engine) {
return EXIT_FAILURE;
}
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
ls2d_engine_set_fps_cap(engine, 60);
/* Create root scene */
scene = ls2d_scene_new();
ls2d_engine_add_scene(engine, scene);
/* Grab our textures */
cache = ls2d_scene_get_texture_cache(scene);
sheet = ls2d_tile_sheet_new_from_xml(cache, "demo_data/platform/spritesheet_player1.xml");
sheet_npc =
ls2d_tile_sheet_new_from_xml(cache, "demo_data/platform/spritesheet_player3.xml");
walking = ls2d_animation_new();
ls2d_animation_set_looping(walking, true);
uint32_t duration = 1000 / 20;
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk01.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk02.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk03.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk04.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk05.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk06.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk07.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk08.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk09.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk10.png"), duration);
ls2d_animation_add_frame(walking, ls2d_tile_sheet_lookup(sheet, "p1_walk11.png"), duration);
tilemap = add_tilemap(scene, cache);
/* Sort out our player */
player = demo_add_player(scene, ls2d_tile_sheet_lookup(sheet, "p1_stand.png"), walking);
walking_npc = ls2d_animation_new();
duration = 1000 / 25;
ls2d_animation_set_looping(walking_npc, true);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk01.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk02.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk03.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk04.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk05.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk06.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk07.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk08.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk09.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk10.png"),
duration);
ls2d_animation_add_frame(walking_npc,
ls2d_tile_sheet_lookup(sheet_npc, "p3_walk11.png"),
duration);
npc = demo_add_npc(scene, ls2d_tile_sheet_lookup(sheet_npc, "p3_stand.png"), walking_npc);
camera = ls2d_camera_new(scene);
ls2d_camera_set_world_bounds(camera, world_bounds);
ls2d_camera_set_xy(camera, (SDL_Point){ .x = 0, .y = 500 });
ls2d_scene_add_camera(scene, "primary", camera);
imanager = ls2d_engine_get_input_manager(engine);
ls2d_input_manager_set_mouse_motion_callback(imanager, mouse_callback, camera);
int ret = ls2d_engine_run(engine, &game);
return ret;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/tilesheet/tilesheet-private.h
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <libxml/xmlreader.h>
#include "ls2d.h"
/**
* Opaque Ls2DTileSheet implementation
*/
struct Ls2DTileSheet {
Ls2DObject object; /*< Parent */
Ls2DTextureCache *cache;
LsPtrArray *animations;
LsArray *texture_objs;
};
/**
* Each cell in the table has a handle and a potential animation.
*/
typedef struct Ls2DTileSheetCell {
Ls2DTextureHandle handle;
Ls2DAnimation *animation;
} Ls2DTileSheetCell;
/**
* Private API headers for the Ls2DTileSheet implementation
*/
/**
* TSX instance parser
*/
typedef struct Ls2DTileSheetTSX {
bool in_tileset;
bool in_image;
bool in_grid;
bool in_tile;
bool in_animation;
bool in_frame;
bool sheet; /**<Whether this is a simple tilesheet */
Ls2DAnimation *animation;
struct {
int width; /**< Tile height */
int height; /**< Tile width */
int count; /**< How many tiles? */
int columns; /**<How many across is it? */
int spacing; /**<Spacing between tiles */
int margin; /**<How much margin is present in the main image */
} tileset;
struct {
int id;
} tile;
struct {
int orientation;
int width;
int height;
} grid;
struct {
int width;
int height;
char *source;
} image;
} Ls2DTileSheetTSX;
__attribute__((always_inline)) static inline Ls2DTileSheetCell *ls2d_tile_sheet_get_cell(
void *cache, uint32_t index)
{
Ls2DTileSheetCell *root = cache;
return &(root[index]);
}
/**
* Attempt to load XML file.
*/
bool ls2d_tile_sheet_parse_tsx(Ls2DTileSheet *self, const char *filename);
DEF_AUTOFREE(xmlTextReader, xmlFreeTextReader)
DEF_AUTOFREE(xmlChar, xmlFree)
static inline void ls2d_tile_sheet_get_int_attr(xmlTextReader *reader, int *storage, const char *id)
{
autofree(xmlChar) *attr = NULL;
/* TODO: Proper error checking of atoi, etc. */
attr = xmlTextReaderGetAttribute(reader, BAD_CAST id);
if (!attr) {
*storage = 0;
return;
}
*storage = atoi((const char *)attr);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/animation.h
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include "ls2d.h"
/**
* Constructs a new Ls2DAnimation object.
*/
Ls2DAnimation *ls2d_animation_new(void);
/**
* Unrefs a previously allocated animation object.
*/
Ls2DAnimation *ls2d_animation_unref(Ls2DAnimation *self);
/**
* Add a frame to the animation. Duration is given in ms.
*/
bool ls2d_animation_add_frame(Ls2DAnimation *self, Ls2DTextureHandle handle, uint32_t duration);
/**
* Update the animation. This should only be called by the owning objects.
*/
void ls2d_animation_update(Ls2DAnimation *self, Ls2DFrameInfo *frame);
/**
* Set the animation to loop.
* Typically we loop by default.
*/
void ls2d_animation_set_looping(Ls2DAnimation *self, bool looping);
/**
* Reset to first frame
*/
void ls2d_animation_reset(Ls2DAnimation *self);
Ls2DTextureHandle ls2d_animation_get_texture(Ls2DAnimation *self);
/**
* Stop the animation.
*/
void ls2d_animation_stop(Ls2DAnimation *self);
DEF_AUTOFREE(Ls2DAnimation, ls2d_animation_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/components/animation-component.h
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include "ls2d.h"
/**
* ls2d_animation_component adds drawable behaviours to an Ls2DEntity.
*/
typedef struct Ls2DAnimationComponent Ls2DAnimationComponent;
/**
* Construct a new AnimationComponent object.
*/
Ls2DComponent *ls2d_animation_component_new(void);
/**
* Unref an allocated AnimationComponent. This will also deference any
* attached resources.
*/
Ls2DAnimationComponent *ls2d_animation_component_unref(Ls2DAnimationComponent *self);
/**
* Insert an animation into this component by a string ID.
* We can then activate animations by their name.
*/
bool ls2d_animation_component_add_animation(Ls2DAnimationComponent *self, const char *id,
Ls2DAnimation *animation);
/**
* Set the current animation
*/
bool ls2d_animation_component_set_animation(Ls2DAnimationComponent *self, const char *id);
/**
* Return the currently renderable animation frame
*/
Ls2DTextureHandle ls2d_animation_component_get_texture(Ls2DAnimationComponent *self);
DEF_AUTOFREE(Ls2DAnimationComponent, ls2d_animation_component_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/entities/image.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
#include "tilemap-private.h"
static void ls2d_image_destroy(Ls2DImage *self);
static void ls2d_image_init(Ls2DImage *self);
static void ls2d_image_draw(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame);
static void ls2d_image_update(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame);
struct Ls2DImage {
Ls2DEntity parent;
Ls2DTextureHandle handle;
};
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable image_vtable = {
.obj_name = "Ls2DImage",
.init = (ls2d_object_vfunc_init)ls2d_image_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_image_destroy,
};
Ls2DEntity *ls2d_image_new(Ls2DTextureHandle handle)
{
Ls2DImage *self = LS2D_NEW(Ls2DImage, image_vtable);
if (ls_unlikely(!self)) {
return NULL;
}
self->handle = handle;
return (Ls2DEntity *)self;
}
static void ls2d_image_init(Ls2DImage *self)
{
self->parent.draw = ls2d_image_draw;
self->parent.update = ls2d_image_update;
}
Ls2DImage *ls2d_image_unref(Ls2DImage *self)
{
return ls2d_object_unref(self);
}
static void ls2d_image_destroy(Ls2DImage *self)
{
free(self);
}
static void ls2d_image_draw(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame)
{
Ls2DImage *self = (Ls2DImage *)entity;
const Ls2DTextureNode *node = NULL;
SDL_Rect view = { 0 };
SDL_Rect draw = { 0 };
SDL_Rect source = { 0 };
SDL_Rect bounds = { 0 };
node = ls2d_texture_cache_lookup(cache, frame, self->handle);
if (ls_unlikely(!node)) {
return;
}
if (!ls2d_camera_get_view(frame->camera, &view)) {
return;
}
if (!ls2d_camera_get_world_bounds(frame->camera, &bounds)) {
return;
}
draw.x = 0;
draw.y = 0;
/* Set the X offset */
source.x = node->area.x;
source.y = node->area.y;
/* Clamp renderable width to camera */
source.w = view.w;
source.h = view.h;
draw.w = source.w;
draw.h = source.h;
double fraction = (double)view.x / (double)bounds.w;
double mid_x = node->area.w / 2.0;
mid_x *= 0.15;
double new_x = mid_x * fraction;
source.x = new_x;
fraction = (double)view.y / (double)bounds.h;
double mid_y = node->area.h / 2.0;
mid_y *= 0.15;
double new_y = mid_y * fraction;
source.x = new_x;
source.y = new_y;
SDL_RenderCopy(frame->renderer, node->texture, &source, &draw);
}
static void ls2d_image_update(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame)
{
/* TODO: Update on camera offsets */
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/camera.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <assert.h>
#include "ls2d.h"
struct Ls2DCamera {
Ls2DObject parent;
SDL_Rect world_bounds; /**< The current world size. */
SDL_Rect view; /**< The current view size */
SDL_Point look_at; /**<Where we're aimed at. */
Ls2DScene *scene;
};
Ls2DObjectTable camera_vtable = {
.obj_name = "Ls2DCamera",
};
Ls2DCamera *ls2d_camera_new(Ls2DScene *scene)
{
Ls2DCamera *self = LS2D_NEW(Ls2DCamera, camera_vtable);
if (ls_unlikely(!self)) {
return NULL;
}
self->scene = scene;
return self;
}
Ls2DCamera *ls2d_camera_unref(Ls2DCamera *self)
{
return ls2d_object_unref(self);
}
void ls2d_camera_set_world_bounds(Ls2DCamera *self, SDL_Rect world_bounds)
{
if (ls_unlikely(!self)) {
return;
}
assert(world_bounds.w > 0);
assert(world_bounds.h > 0);
self->world_bounds = world_bounds;
}
void ls2d_camera_set_xy(Ls2DCamera *self, SDL_Point look_at)
{
if (ls_unlikely(!self)) {
return;
}
self->look_at = look_at;
if (self->look_at.x < 0) {
self->look_at.x = 0;
}
if (self->look_at.y < 0) {
self->look_at.y = 0;
}
/*
if (self->look_at.x + self->view.w > self->world_bounds.w) {
self->look_at.x = self->world_bounds.w - self->view.w;
}*/
if (self->look_at.y + self->view.h > self->world_bounds.h) {
self->look_at.y = self->world_bounds.h - self->view.h;
}
if (self->look_at.x + self->view.w > self->world_bounds.w) {
self->look_at.x = self->world_bounds.w - self->view.w;
}
/* TODO: Update camera properly. */
}
static bool ls2d_camera_get_entity_position(Ls2DEntity *entity, int *pos_x, int *pos_y)
{
*pos_x = 0;
*pos_y = 0;
Ls2DComponent *position = NULL;
SDL_Point real_pos = { 0 };
position = ls2d_entity_get_component(entity, LS2D_COMP_ID_POSITION);
if (!ls2d_position_component_get_xy((Ls2DPositionComponent *)position, &real_pos)) {
return false;
}
*pos_x = real_pos.x;
*pos_y = real_pos.y;
return true;
}
bool ls2d_camera_convert_entity_position(Ls2DCamera *self, Ls2DEntity *entity, int *pos_x,
int *pos_y)
{
int r_pos_x = 0, r_pos_y = 0;
if (ls_unlikely(!self) || ls_unlikely(!entity)) {
return false;
}
if (!ls2d_camera_get_entity_position(entity, &r_pos_x, &r_pos_y)) {
return false;
}
*pos_x = r_pos_x - self->look_at.x;
*pos_y = r_pos_y - self->look_at.y;
return true;
}
bool ls2d_camera_entity_in_bounds(Ls2DCamera *self, Ls2DEntity *entity)
{
int pos_x = 0, pos_y = 0;
if (ls_unlikely(!self) || ls_unlikely(!entity)) {
return false;
}
if (!ls2d_camera_get_entity_position(entity, &pos_x, &pos_y)) {
return true;
}
if (pos_x > self->world_bounds.w || pos_x < self->world_bounds.x) {
return false;
}
if (pos_y > self->world_bounds.h || pos_y < self->world_bounds.y) {
return false;
}
return true;
}
void ls2d_camera_update(Ls2DCamera *self, Ls2DFrameInfo *frame)
{
if (ls_unlikely(!self)) {
return;
}
/* If we have a logical size, use it. Otherwise, real size. */
SDL_RenderGetLogicalSize(frame->renderer, &self->view.w, &self->view.h);
if (self->view.w == 0) {
SDL_GetRendererOutputSize(frame->renderer, &self->view.w, &self->view.h);
}
/* TODO: Update camera to point at correct place. */
}
bool ls2d_camera_get_view(Ls2DCamera *self, SDL_Rect *view)
{
if (ls_unlikely(!self) || ls_unlikely(!view)) {
return false;
}
view->x = self->look_at.x;
view->y = self->look_at.y;
view->w = self->view.w;
view->h = self->view.h;
return true;
}
bool ls2d_camera_get_world_bounds(Ls2DCamera *self, SDL_Rect *view)
{
if (ls_unlikely(!self) || ls_unlikely(!view)) {
return false;
}
*view = self->world_bounds;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/entities/tilemap-private.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <fcntl.h>
#include <libxml/xmlreader.h>
#include <unistd.h>
#include "ls2d.h"
#define LS2D_TILE_FLIPPED_HORIZONTALLY 0x80000000
#define LS2D_TILE_FLIPPED_VERTICALLY 0x40000000
#define LS2D_TILE_FLIPPED_DIAGONALLY 0x20000000
#define LS2D_TILE_MASK \
~(LS2D_TILE_FLIPPED_HORIZONTALLY | LS2D_TILE_FLIPPED_VERTICALLY | \
LS2D_TILE_FLIPPED_DIAGONALLY)
struct Ls2DTileMap {
Ls2DEntity parent;
int tile_size;
uint16_t width;
uint16_t height;
LsArray *layers; /**<An array of Ls2DTileMapLayer */
LsArray *tilesheets; /**<An array of tilesheets */
int size;
struct {
int first_column;
int first_row;
int max_row;
int max_column;
int x_start;
int y_start;
} render;
};
typedef struct Ls2DTileMapLayer {
int render_index; /**<TODO: Shorten to uint8_t */
uint32_t *tiles;
} Ls2DTileMapLayer;
/**
* XML instance parser
*/
typedef struct Ls2DTileMapTMX {
bool in_map;
bool in_layer;
bool in_data;
struct {
int orientation;
int width;
int height;
int tile_width;
int tile_height;
/* TODO: Support infinite.. ?*/
} map;
struct {
int first_gid;
char *source;
} tileset;
struct {
int id;
char *name;
int width;
int height;
int idx;
} layer;
Ls2DTextureCache *cache;
} Ls2DTileMapTMX;
bool ls2d_tilemap_load_tmx(Ls2DTileMap *self, Ls2DTextureCache *cache, const char *filename);
bool ls2d_tilemap_set_internal(Ls2DTileMap *self, int layer_index, int x, int y, uint32_t gid);
DEF_AUTOFREE(xmlTextReader, xmlFreeTextReader)
DEF_AUTOFREE(xmlChar, xmlFree)
DEF_AUTOFREE(char, free)
static inline void ls2d_tilemap_get_int_attr(xmlTextReader *reader, int *storage, const char *id)
{
autofree(xmlChar) *attr = NULL;
/* TODO: Proper error checking of atoi, etc. */
attr = xmlTextReaderGetAttribute(reader, BAD_CAST id);
if (!attr) {
*storage = 0;
return;
}
*storage = atoi((const char *)attr);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/component.h
|
<reponame>lispysnake/lispysnake2d
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include "ls2d.h"
/**
* Ls2DComponent is a basic block of behaviour for any given entity,
* and must be added to an Ls2DEntity.
*/
struct Ls2DComponent {
Ls2DObject object;
Ls2DEntity *parent_entity;
int comp_id; /**<Public component ID */
/* Draw callback that all components should implemented */
void (*draw)(struct Ls2DComponent *, Ls2DTextureCache *, Ls2DFrameInfo *);
/* Update callback that all components should implement */
void (*update)(struct Ls2DComponent *, Ls2DTextureCache *, Ls2DFrameInfo *);
/* The component needs to be constructed */
void (*init)(struct Ls2DComponent *, Ls2DTextureCache *, Ls2DFrameInfo *);
};
void ls2d_component_init(Ls2DComponent *self, Ls2DTextureCache *, Ls2DFrameInfo *frame);
/**
* Inform the component it needs to draw now.
*/
void ls2d_component_draw(Ls2DComponent *self, Ls2DTextureCache *, Ls2DFrameInfo *info);
/**
* Inform the component it needs to update now.
*/
void ls2d_component_update(Ls2DComponent *self, Ls2DTextureCache *, Ls2DFrameInfo *info);
/**
* Return component ID
*/
int ls2d_component_get_id(Ls2DComponent *self);
/**
* Set the parent entity for this component
* @TODO: Make this private API.
*/
void ls2d_component_set_parent_entity(Ls2DComponent *self, Ls2DEntity *entity);
/**
* Grab the parent entity
*/
Ls2DEntity *ls2d_component_get_parent_entity(Ls2DComponent *self);
Ls2DComponent *ls2d_component_unref(Ls2DComponent *self);
DEF_AUTOFREE(Ls2DComponent, ls2d_component_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/texture-cache.c
|
<reponame>lispysnake/lispysnake2d
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <SDL.h>
#include <SDL_image.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "ls2d.h"
#define DEFAULT_CACHE_SIZE 2800
DEF_AUTOFREE(SDL_Surface, SDL_FreeSurface)
static void ls2d_texture_cache_init(Ls2DTextureCache *self);
static void ls2d_texture_cache_destroy(Ls2DTextureCache *self);
/**
* Opaque Ls2DTextureCache implementation
*/
struct Ls2DTextureCache {
Ls2DObject object; /*< Parent */
LsArray *cache; /*< Cache of textures in an array */
};
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable texture_cache_vtable = {
.init = (ls2d_object_vfunc_init)ls2d_texture_cache_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_texture_cache_destroy,
.obj_name = "Ls2DTextureCache",
};
Ls2DTextureCache *ls2d_texture_cache_new()
{
return LS2D_NEW(Ls2DTextureCache, texture_cache_vtable);
}
static void ls2d_texture_cache_init(Ls2DTextureCache *self)
{
self->cache = ls_array_new_size(sizeof(struct Ls2DTextureNode), DEFAULT_CACHE_SIZE);
}
Ls2DTextureCache *ls2d_texture_cache_unref(Ls2DTextureCache *self)
{
return ls2d_object_unref(self);
}
static SDL_Texture *load_texture_internal(Ls2DTextureNode *node, Ls2DFrameInfo *frame)
{
autofree(SDL_Surface) *img_surface = NULL;
autofree(SDL_Surface) *opt_surface = NULL;
SDL_Surface *win_surface = NULL;
img_surface = IMG_Load(node->filename);
if (!img_surface) {
fprintf(stderr, "Failed to load %s: %s\n", node->filename, IMG_GetError());
return NULL;
}
/* If the window has no surface, we can't optimize it */
win_surface = SDL_GetWindowSurface(frame->window);
if (!win_surface) {
return SDL_CreateTextureFromSurface(frame->renderer, img_surface);
}
/* Try to optimize it */
opt_surface = SDL_ConvertSurfaceFormat(img_surface, SDL_PIXELFORMAT_RGBA8888, 0);
if (!opt_surface) {
fprintf(stderr,
"Failed to optimize surface %s: %s\n",
node->filename,
SDL_GetError());
return SDL_CreateTextureFromSurface(frame->renderer, img_surface);
}
return SDL_CreateTextureFromSurface(frame->renderer, opt_surface);
}
static SDL_Texture *load_texture(Ls2DTextureNode *node, Ls2DFrameInfo *frame)
{
SDL_Texture *texture = NULL;
texture = load_texture_internal(node, frame);
if (ls_unlikely(!texture)) {
return NULL;
}
/* Find out real width and height
* TODO: Don't bother for subregions.
*/
SDL_QueryTexture(texture, NULL, NULL, &node->area.w, &node->area.h);
return texture;
}
/**
* Clear out the allocated texture.
*/
static void clear_texture(Ls2DTextureNode *node)
{
if (node->subregion) {
return;
}
if (node->texture) {
SDL_DestroyTexture(node->texture);
}
if (node->filename) {
free(node->filename);
}
}
__attribute__((always_inline)) static inline Ls2DTextureNode *lookup_node(void *cache,
Ls2DTextureHandle handle)
{
Ls2DTextureNode *root = cache;
return &(root[handle]);
}
static void ls2d_texture_cache_destroy(Ls2DTextureCache *self)
{
for (uint16_t i = 0; i < self->cache->len; i++) {
clear_texture(lookup_node(self->cache->data, i));
}
ls_array_free(self->cache, NULL);
}
Ls2DTextureHandle ls2d_texture_cache_load_file(Ls2DTextureCache *self, const char *filename)
{
struct Ls2DTextureNode *node = NULL;
uint32_t index = 0;
/* Preallocate cached texture */
ls_array_add(self->cache, NULL);
index = (uint32_t)self->cache->len - 1;
node = lookup_node(self->cache->data, (Ls2DTextureHandle)index);
/* Sort out the cache */
node->filename = strdup(filename);
node->subregion = false;
node->texture = NULL;
return (Ls2DTextureHandle)index;
}
Ls2DTextureHandle ls2d_texture_cache_subregion(Ls2DTextureCache *self, Ls2DTextureHandle parent,
SDL_Rect subregion)
{
struct Ls2DTextureNode *parent_node = NULL;
struct Ls2DTextureNode *node = NULL;
uint32_t index = 0;
if (ls_unlikely(!self)) {
return 0;
}
if (ls_unlikely(parent > self->cache->len)) {
return 0;
}
parent_node = lookup_node(self->cache->data, parent);
assert(parent_node->subregion != true);
/* Preallocate cached texture */
ls_array_add(self->cache, NULL);
index = (uint32_t)self->cache->len - 1;
node = lookup_node(self->cache->data, (Ls2DTextureHandle)index);
/* Sort out the cache */
node->filename = NULL;
node->subregion = true;
node->area = subregion;
node->texture = NULL;
node->parent = parent_node;
return (Ls2DTextureHandle)index;
}
const Ls2DTextureNode *ls2d_texture_cache_lookup(Ls2DTextureCache *self, Ls2DFrameInfo *frame,
Ls2DTextureHandle handle)
{
Ls2DTextureNode *node = NULL;
if (ls_unlikely(!self)) {
return NULL;
}
if (ls_unlikely(handle > self->cache->len)) {
return NULL;
}
node = lookup_node(self->cache->data, handle);
if (ls_unlikely(!node)) {
return NULL;
}
if (!node->texture) {
if (node->parent && !node->parent->texture) {
node->parent->texture = load_texture(node->parent, frame);
node->texture = node->parent->texture;
} else if (node->parent) {
node->texture = node->parent->texture;
} else {
node->texture = load_texture(node, frame);
}
}
return (const Ls2DTextureNode *)node;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/tilesheet/sheet.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
#include "tilesheet-private.h"
static void ls2d_tile_sheet_init(Ls2DTileSheet *self);
static void ls2d_tile_sheet_destroy(Ls2DTileSheet *self);
static void ls2d_tile_sheet_destroy_cell(Ls2DTileSheetCell *cell);
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable tile_sheet_vtable = {
.init = (ls2d_object_vfunc_init)ls2d_tile_sheet_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_tile_sheet_destroy,
.obj_name = "Ls2DTileSheet",
};
Ls2DTileSheet *ls2d_tile_sheet_new(Ls2DTextureCache *cache, const char *tsx_path)
{
Ls2DTileSheet *self = LS2D_NEW(Ls2DTileSheet, tile_sheet_vtable);
if (ls_unlikely(!self)) {
return NULL;
}
self->cache = cache;
if (!ls2d_tile_sheet_parse_tsx(self, tsx_path)) {
ls2d_object_unref((Ls2DObject *)self);
return NULL;
}
return self;
}
static void ls2d_tile_sheet_init(Ls2DTileSheet *self)
{
self->animations = ls_ptr_array_new();
}
Ls2DTileSheet *ls2d_tile_sheet_unref(Ls2DTileSheet *self)
{
return ls2d_object_unref(self);
}
static void ls2d_tile_sheet_destroy(Ls2DTileSheet *self)
{
if (ls_likely(self->texture_objs != NULL)) {
for (uint32_t i = 0; i < self->texture_objs->len; i++) {
Ls2DTileSheetCell *cell =
ls2d_tile_sheet_get_cell(self->texture_objs->data, i);
ls2d_tile_sheet_destroy_cell(cell);
}
ls_array_free(self->texture_objs, NULL);
}
ls_array_free(self->animations, NULL);
}
static void ls2d_tile_sheet_destroy_cell(Ls2DTileSheetCell *cell)
{
if (ls_unlikely(cell->animation != NULL)) {
ls2d_animation_unref(cell->animation);
}
}
void ls2d_tile_sheet_update(Ls2DTileSheet *self, Ls2DFrameInfo *frame)
{
if (ls_unlikely(!self)) {
return;
}
for (uint16_t i = 0; i < self->animations->len; i++) {
Ls2DAnimation *animation = (Ls2DAnimation *)self->animations->data[i];
ls2d_animation_update(animation, frame);
}
}
Ls2DTextureHandle ls2d_tile_sheet_lookup(Ls2DTileSheet *self, uint32_t gid)
{
Ls2DTileSheetCell *cell = NULL;
Ls2DTextureHandle handle = 0;
cell = ls2d_tile_sheet_get_cell(self->texture_objs->data, gid - 1);
handle = cell->handle;
if (cell->animation) {
return ls2d_animation_get_texture(cell->animation);
}
return handle;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/demo/main.c
|
<reponame>lispysnake/lispysnake2d
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "demo.h"
static bool mouse_callback(SDL_MouseMotionEvent *event, Ls2DFrameInfo *frame, void *userdata)
{
Ls2DCamera *camera = userdata;
ls2d_camera_set_xy(camera, (SDL_Point){ .x = event->x, .y = event->y });
return true;
}
bool demo_game_init(Ls2DGame *game)
{
DemoGame *self = (DemoGame *)game;
Ls2DInputManager *imanager = NULL;
SDL_Rect world_bounds = { 0 };
world_bounds.w = 45 * 16;
world_bounds.h = 25 * 16;
fprintf(stderr, "Init begin!\n");
/* Construct scene */
self->scene = ls2d_scene_new();
imanager = ls2d_engine_get_input_manager(game->engine);
/* Camera */
self->camera = ls2d_camera_new(self->scene);
ls2d_scene_add_camera(self->scene, "main_camera", self->camera);
ls2d_camera_set_world_bounds(self->camera, world_bounds);
/* Tilesheet */
if (!demo_game_load_tilemap(self)) {
return false;
}
/* Player
if (!demo_game_make_player(self)) {
return false;
}*/
ls2d_input_manager_set_mouse_motion_callback(imanager, mouse_callback, self->camera);
ls2d_engine_add_scene(game->engine, self->scene);
fprintf(stderr, "Init end!\n");
return true;
}
void demo_game_destroy(Ls2DGame *game)
{
DemoGame *self = (DemoGame *)game;
fprintf(stderr, "Destroy begin!\n");
/* Cleanup allocations */
ls2d_scene_unref(self->scene);
ls2d_camera_unref(self->camera);
ls2d_tilemap_unref(self->tilemap);
fprintf(stderr, "Destroy end!\n");
}
int main(int argc, char **argv)
{
autofree(Ls2DEngine) *engine = NULL;
DemoGame game = { 0 };
game.parent.funcs.init = demo_game_init;
game.parent.funcs.destroy = demo_game_destroy;
engine = ls2d_engine_new(480, 270);
return ls2d_engine_run(engine, (Ls2DGame *)&game);
}
|
lispysnake/lispysnake2d
|
src/core/components/animation-component.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <string.h>
#include "ls2d.h"
static void ls2d_animation_component_destroy(Ls2DAnimationComponent *self);
static void ls2d_animation_component_init(Ls2DAnimationComponent *self);
static void ls2d_animation_component_update(Ls2DComponent *component, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame);
/**
* Opaque Ls2DAnimationComponent implementation
*/
struct Ls2DAnimationComponent {
Ls2DComponent parent; /*< Parent */
LsHashmap *anims;
Ls2DAnimation *cur_anim;
};
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable animation_component_vtable = {
.obj_name = "Ls2DAnimationComponent",
.init = (ls2d_object_vfunc_init)ls2d_animation_component_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_animation_component_destroy,
};
Ls2DComponent *ls2d_animation_component_new()
{
return (Ls2DComponent *)LS2D_NEW(Ls2DAnimationComponent, animation_component_vtable);
}
static void ls2d_animation_component_init(Ls2DAnimationComponent *self)
{
self->anims = ls_hashmap_new_full(ls_hashmap_string_hash,
ls_hashmap_string_equal,
free,
(ls_hashmap_free_func)ls2d_object_unref);
self->parent.comp_id = LS2D_COMP_ID_ANIMATION;
self->parent.update = ls2d_animation_component_update;
}
Ls2DAnimationComponent *ls2d_animation_component_unref(Ls2DAnimationComponent *self)
{
return ls2d_object_unref(self);
}
bool ls2d_animation_component_add_animation(Ls2DAnimationComponent *self, const char *id,
Ls2DAnimation *animation)
{
char *id_c = NULL;
if (ls_unlikely(!self) || ls_unlikely(!animation)) {
return false;
}
id_c = strdup(id);
if (!id_c) {
return false;
}
if (ls_unlikely(!ls_hashmap_put(self->anims, id_c, ls2d_object_ref(animation)))) {
ls2d_object_unref(animation);
return false;
}
if (ls_unlikely(!self->cur_anim)) {
self->cur_anim = animation;
ls2d_animation_reset(self->cur_anim);
}
return true;
}
bool ls2d_animation_component_set_animation(Ls2DAnimationComponent *self, const char *id)
{
Ls2DAnimation *anim = NULL;
if (ls_unlikely(!self)) {
return false;
}
anim = ls_hashmap_get(self->anims, (char *)id);
if (ls_unlikely(!anim)) {
return false;
}
self->cur_anim = anim;
ls2d_animation_reset(self->cur_anim);
return true;
}
static void ls2d_animation_component_destroy(Ls2DAnimationComponent *self)
{
if (ls_likely(self->anims != NULL)) {
ls_hashmap_free(self->anims);
}
}
static void ls2d_animation_component_update(Ls2DComponent *component,
__ls_unused__ Ls2DTextureCache *cache,
Ls2DFrameInfo *frame)
{
Ls2DAnimationComponent *self = NULL;
if (ls_unlikely(!component)) {
return;
}
self = (Ls2DAnimationComponent *)component;
if (ls_unlikely(!self->cur_anim)) {
return;
}
ls2d_animation_update(self->cur_anim, frame);
}
Ls2DTextureHandle ls2d_animation_component_get_texture(Ls2DAnimationComponent *self)
{
if (ls_unlikely(!self)) {
return 0;
}
return ls2d_animation_get_texture(self->cur_anim);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/tilesheet/tsx.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <libxml/xmlreader.h>
#include <unistd.h>
#include "ls2d.h"
#include "tilesheet-private.h"
static void ls2d_tile_sheet_walk_tsx(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser,
xmlTextReader *reader);
static void ls2d_tile_sheet_start_animation(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser);
static void ls2d_tile_sheet_end_animation(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser);
static void ls2d_tile_sheet_add_frame(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser,
xmlTextReader *reader);
/**
* Attempt to load XML file.
*/
bool ls2d_tile_sheet_parse_tsx(Ls2DTileSheet *self, const char *filename)
{
int fd = 0;
autofree(xmlTextReader) *reader = NULL;
bool ret = false;
int r = 0;
Ls2DTileSheetTSX parser = { 0 };
fd = open(filename, O_RDONLY);
if (fd < 0) {
goto fail;
}
/* Not portable. Improve for Windows. */
(void)posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
reader = xmlReaderForFd(fd, filename, NULL, 0);
if (!reader) {
goto fail;
}
while ((r = xmlTextReaderRead(reader)) > 0) {
ls2d_tile_sheet_walk_tsx(self, &parser, reader);
}
ret = true;
fail:
if (fd >= 0) {
close(fd);
}
return ret;
}
static void ls2d_tile_sheet_image_tsx(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser,
xmlTextReader *reader)
{
autofree(xmlChar) *source = NULL;
Ls2DTextureHandle handle;
Ls2DTextureHandle subhandle;
Ls2DTileSheetCell *cell = NULL;
ls2d_tile_sheet_get_int_attr(reader, &parser->image.width, "width");
ls2d_tile_sheet_get_int_attr(reader, &parser->image.height, "height");
source = xmlTextReaderGetAttribute(reader, BAD_CAST "source");
handle = ls2d_texture_cache_load_file(self->cache, (char *)source);
/* Basic sheet logic. */
if (!parser->sheet) {
ls_array_add(self->texture_objs, NULL);
fprintf(stderr, "Loading (%d): %s\n", parser->tile.id, source);
cell = ls2d_tile_sheet_get_cell(self->texture_objs->data, parser->tile.id);
cell->handle = handle;
return;
}
int x = parser->tileset.margin;
int y = parser->tileset.margin;
int column = 0;
for (int tile = 0; tile < parser->tileset.count; tile++) {
SDL_Rect region = { .x = x,
.y = y,
.w = parser->tileset.width - parser->tileset.spacing,
.h = parser->tileset.height - parser->tileset.spacing };
/* seek */
column++;
if (column == parser->tileset.columns) {
x = parser->tileset.margin;
y += parser->tileset.spacing;
y += parser->tileset.height;
column = 0;
} else {
x += parser->tileset.spacing;
x += parser->tileset.width;
}
subhandle = ls2d_texture_cache_subregion(self->cache, handle, region);
if (!ls_array_add(self->texture_objs, NULL)) {
abort();
}
cell = ls2d_tile_sheet_get_cell(self->texture_objs->data, tile);
cell->handle = subhandle;
}
}
/**
* Walk each node and then process it.
*/
static void ls2d_tile_sheet_walk_tsx(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser,
xmlTextReader *reader)
{
const xmlChar *name = NULL;
name = xmlTextReaderConstName(reader);
if (!name) {
return;
}
if (parser->in_tileset && xmlStrEqual(name, BAD_CAST "grid")) {
parser->in_grid = !parser->in_grid;
return;
}
if (parser->in_tileset && xmlStrEqual(name, BAD_CAST "tile")) {
parser->in_tile = !parser->in_tile;
ls2d_tile_sheet_get_int_attr(reader, &parser->tile.id, "id");
return;
}
if (parser->in_tile && xmlStrEqual(name, BAD_CAST "image")) {
parser->in_image = !parser->in_image;
ls2d_tile_sheet_image_tsx(self, parser, reader);
return;
} else if (parser->in_tileset && xmlStrEqual(name, BAD_CAST "image")) {
parser->in_image = !parser->in_image;
parser->sheet = !parser->sheet;
if (!parser->in_image) {
return;
}
ls2d_tile_sheet_image_tsx(self, parser, reader);
return;
}
if (parser->in_tile && xmlStrEqual(name, BAD_CAST "animation")) {
parser->in_animation = !parser->in_animation;
if (parser->in_animation) {
ls2d_tile_sheet_start_animation(self, parser);
} else {
ls2d_tile_sheet_end_animation(self, parser);
}
return;
}
if (parser->in_animation && xmlStrEqual(name, BAD_CAST "frame")) {
parser->in_frame = !parser->in_frame;
ls2d_tile_sheet_add_frame(self, parser, reader);
return;
}
if (xmlStrEqual(name, BAD_CAST "tileset")) {
parser->in_tileset = !parser->in_tileset;
if (!parser->in_tileset) {
return;
}
ls2d_tile_sheet_get_int_attr(reader, &parser->tileset.width, "tilewidth");
ls2d_tile_sheet_get_int_attr(reader, &parser->tileset.height, "tileheight");
ls2d_tile_sheet_get_int_attr(reader, &parser->tileset.spacing, "spacing");
ls2d_tile_sheet_get_int_attr(reader, &parser->tileset.margin, "margin");
ls2d_tile_sheet_get_int_attr(reader, &parser->tileset.count, "tilecount");
ls2d_tile_sheet_get_int_attr(reader, &parser->tileset.columns, "columns");
self->texture_objs =
ls_array_new_size(sizeof(Ls2DTileSheetCell), parser->tileset.count);
/* TODO: Ensure this is created! */
}
}
static void ls2d_tile_sheet_start_animation(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser)
{
if (parser->animation) {
ls2d_animation_unref(parser->animation);
}
parser->animation = ls2d_animation_new();
}
static void ls2d_tile_sheet_end_animation(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser)
{
Ls2DTileSheetCell *cell = NULL;
cell = ls2d_tile_sheet_get_cell(self->texture_objs->data, parser->tile.id);
cell->animation = parser->animation;
ls_array_add(self->animations, parser->animation);
parser->animation = NULL;
}
static void ls2d_tile_sheet_add_frame(Ls2DTileSheet *self, Ls2DTileSheetTSX *parser,
xmlTextReader *reader)
{
Ls2DTileSheetCell *old_cell = NULL;
Ls2DTileSheetCell *source_cell = NULL;
int tile_id = 0;
int duration = 0;
ls2d_tile_sheet_get_int_attr(reader, &tile_id, "tileid");
ls2d_tile_sheet_get_int_attr(reader, &duration, "duration");
source_cell = ls2d_tile_sheet_get_cell(self->texture_objs->data, tile_id);
old_cell = ls2d_tile_sheet_get_cell(self->texture_objs->data, parser->tile.id);
if (!ls2d_animation_add_frame(parser->animation, source_cell->handle, (uint32_t)duration)) {
abort();
}
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/demo/player.c
|
<filename>src/demo/player.c
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "demo.h"
static Ls2DAnimation *demo_player_animation(DemoGame *self)
{
autofree(Ls2DSpriteSheet) *sheet = NULL;
Ls2DAnimation *walking = NULL;
Ls2DTextureCache *cache = NULL;
/* Grab our textures */
cache = ls2d_scene_get_texture_cache(self->scene);
sheet = ls2d_sprite_sheet_new(cache, "demo_data/platform/spritesheet_player1.xml");
walking = ls2d_animation_new();
ls2d_animation_set_looping(walking, true);
uint32_t duration = 1000 / 20;
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk01.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk02.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk03.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk04.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk05.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk06.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk07.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk08.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk09.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk10.png"),
duration);
ls2d_animation_add_frame(walking,
ls2d_sprite_sheet_lookup(sheet, "p1_walk11.png"),
duration);
return walking;
}
bool demo_game_make_player(DemoGame *self)
{
autofree(Ls2DComponent) *sprite = NULL;
autofree(Ls2DComponent) *pos = NULL;
autofree(Ls2DComponent) *anim = NULL;
autofree(Ls2DAnimation) *animation = NULL;
self->player = ls2d_basic_entity_new("player");
sprite = ls2d_sprite_component_new();
pos = ls2d_position_component_new();
anim = ls2d_animation_component_new();
animation = demo_player_animation(self);
ls2d_animation_component_add_animation((Ls2DAnimationComponent *)anim,
"walking",
animation);
ls2d_entity_add_component(self->player, sprite);
ls2d_entity_add_component(self->player, pos);
ls2d_entity_add_component(self->player, anim);
ls2d_sprite_component_set_flip((Ls2DSpriteComponent *)sprite, SDL_FLIP_HORIZONTAL);
ls2d_position_component_set_xy((Ls2DPositionComponent *)pos,
(SDL_Point){ .x = 690, .y = 16 * 70 - 25 });
ls2d_scene_add_entity(self->scene, self->player);
return true;
}
|
lispysnake/lispysnake2d
|
src/core/engine-private.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <SDL.h>
#include <stdbool.h>
#include <stdlib.h>
#include "ls2d.h"
/** Private API headers for the engine implementation */
/**
* Ls2DEngine is responsible for managing the primary output, setting up
* the event dispatch system, etc.
*/
struct Ls2DEngine {
Ls2DObject object; /*< Parent */
int width;
int height;
uint32_t fps_delay;
SDL_Window *window;
SDL_Renderer *render;
bool running;
bool fullscreen;
/* List of scenes. */
LsList *scenes;
Ls2DScene *active_scene;
Ls2DInputManager *input_manager;
SDL_Texture *buffer;
Ls2DGame *game;
};
/**
* Process all incoming events to the engine (input/updates)
*/
void ls2d_engine_process_events(Ls2DEngine *self, Ls2DFrameInfo *frame);
/**
* Pump any and all drawing events
*/
void ls2d_engine_draw(Ls2DEngine *self, Ls2DFrameInfo *frame);
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/entities/tilemap.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <SDL.h>
#include "ls2d.h"
/**
* Helper type to help set and retrieve tile cell attributes
*/
struct Ls2DTile {
uint32_t gid;
bool flipped_horizontal;
bool flipped_diagonal;
bool flipped_vertical;
};
/**
* Construct a new Ls2DTileMap
*/
Ls2DEntity *ls2d_tilemap_new(int tilesize, uint16_t map_width, uint16_t map_height);
/**
* Construct a new Ls2DTileMap from a TMX file
*/
Ls2DEntity *ls2d_tilemap_new_from_tmx(Ls2DTextureCache *cache, const char *filename);
/**
* Attempt to insert a new layer in the map
*/
bool ls2d_tilemap_add_layer(Ls2DTileMap *map, int render_index);
/**
* Set the gid in the given layer, at X by Y
*/
bool ls2d_tilemap_set_tile(Ls2DTileMap *map, int layer_index, int x, int y, Ls2DTile tile);
void ls2d_tilemap_add_tilesheet(Ls2DTileMap *map, Ls2DTileSheet *tilesheet);
/**
* Unref a previously allocated tileMap
*/
Ls2DTileMap *ls2d_tilemap_unref(Ls2DTileMap *self);
DEF_AUTOFREE(Ls2DTileMap, ls2d_tilemap_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/spritesheet/xml.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <libxml/xmlreader.h>
#include <unistd.h>
#include "ls2d.h"
#include "spritesheet-private.h"
static void ls2d_sprite_sheet_walk_xml(Ls2DSpriteSheet *self, Ls2DSpriteSheetXML *parser,
xmlTextReader *reader);
/**
* Attempt to load XML file.
*/
bool ls2d_sprite_sheet_parse_xml(Ls2DSpriteSheet *self, const char *filename)
{
int fd = 0;
autofree(xmlTextReader) *reader = NULL;
bool ret = false;
int r = 0;
Ls2DSpriteSheetXML parser = { 0 };
fd = open(filename, O_RDONLY);
if (fd < 0) {
goto fail;
}
/* Not portable. Improve for Windows. */
(void)posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
reader = xmlReaderForFd(fd, filename, NULL, 0);
if (!reader) {
goto fail;
}
while ((r = xmlTextReaderRead(reader)) > 0) {
ls2d_sprite_sheet_walk_xml(self, &parser, reader);
}
ret = true;
fail:
if (fd >= 0) {
close(fd);
}
return ret;
}
/**
* Walk each node and then process it.
*/
static void ls2d_sprite_sheet_walk_xml(Ls2DSpriteSheet *self, Ls2DSpriteSheetXML *parser,
xmlTextReader *reader)
{
const xmlChar *name = NULL;
name = xmlTextReaderConstName(reader);
if (!name) {
return;
}
/* Are we in the texture atlas..? */
if (xmlStrEqual(name, BAD_CAST "TextureAtlas")) {
autofree(xmlChar) *image_path = NULL;
parser->in_atlas = !parser->in_atlas;
if (!parser->in_atlas) {
return;
}
/* We grabbed the texture filename */
image_path = xmlTextReaderGetAttribute(reader, BAD_CAST "imagePath");
parser->texture.handle =
ls2d_texture_cache_load_file(self->cache, (char *)image_path);
/* TODO: Check handle validity??? */
}
if (parser->in_atlas && xmlStrEqual(name, BAD_CAST "SubTexture")) {
autofree(xmlChar) *filepath = NULL;
Ls2DTextureHandle subhandle = 0;
parser->in_subtexture = !parser->in_subtexture;
ls2d_sprite_sheet_get_int_attr(reader, &parser->subtexture.x, "x");
ls2d_sprite_sheet_get_int_attr(reader, &parser->subtexture.y, "y");
ls2d_sprite_sheet_get_int_attr(reader, &parser->subtexture.width, "width");
ls2d_sprite_sheet_get_int_attr(reader, &parser->subtexture.height, "height");
filepath = xmlTextReaderGetAttribute(reader, BAD_CAST "name");
if (!filepath) {
fprintf(stderr, "Missing filepath for SubTexture. Dropping.\n");
return;
}
subhandle = ls2d_texture_cache_subregion(self->cache,
parser->texture.handle,
(SDL_Rect){
.x = parser->subtexture.x,
.y = parser->subtexture.y,
.w = parser->subtexture.width,
.h = parser->subtexture.height,
});
ls_hashmap_put(self->textures,
strdup((const char *)filepath),
LS_INT_TO_PTR(subhandle));
}
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/object.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <stdatomic.h>
/**
* The init function for an object
*/
typedef void (*ls2d_object_vfunc_init)(void *);
/**
* The destructor function for an object
*/
typedef void (*ls2d_object_vfunc_destroy)(void *);
/**
* Simple vtable definition for Ls2DObjects so that they can be
* extended.
*/
typedef struct Ls2DObjectTable {
ls2d_object_vfunc_init init;
ls2d_object_vfunc_destroy destroy;
const char *obj_name;
} Ls2DObjectTable;
/**
* Opaque object implementation.
*/
struct Ls2DObject {
atomic_int ref_count;
Ls2DObjectTable *vtable;
};
/**
* Increase reference count on the given Ls2DObject
*/
void *ls2d_object_ref(void *);
void *ls2d_object_unref(void *v);
void *ls2d_object_init(Ls2DObject *object, Ls2DObjectTable *vtable);
Ls2DObject *ls2d_object_new(size_t size, Ls2DObjectTable *vtable);
#define LS2D_NEW(x, y) (x *)ls2d_object_new(sizeof(x), &y)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/spritesheet/spritesheet-private.h
|
<filename>src/core/spritesheet/spritesheet-private.h
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <libxml/xmlreader.h>
#include "ls2d.h"
/**
* Opaque Ls2DSpriteSheet implementation
*/
struct Ls2DSpriteSheet {
Ls2DObject object; /*< Parent */
LsHashmap *textures; /*< Cache of textures in a hashmap */
Ls2DTextureCache *cache;
};
/**
* Private API headers for the Ls2DSpriteSheet implementation
*/
/**
* XML instance parser
*/
typedef struct Ls2DSpriteSheetXML {
bool in_atlas;
bool in_subtexture;
struct {
Ls2DTextureHandle handle;
} texture;
struct {
int width;
int height;
int x;
int y;
char *filename;
} subtexture;
} Ls2DSpriteSheetXML;
/**
* Attempt to load XML file.
*/
bool ls2d_sprite_sheet_parse_xml(Ls2DSpriteSheet *self, const char *filename);
DEF_AUTOFREE(xmlTextReader, xmlFreeTextReader)
DEF_AUTOFREE(xmlChar, xmlFree)
static inline void ls2d_sprite_sheet_get_int_attr(xmlTextReader *reader, int *storage,
const char *id)
{
autofree(xmlChar) *attr = NULL;
/* TODO: Proper error checking of atoi, etc. */
attr = xmlTextReaderGetAttribute(reader, BAD_CAST id);
if (!attr) {
*storage = 0;
return;
}
*storage = atoi((const char *)attr);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/component.c
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
void ls2d_component_init(Ls2DComponent *self, Ls2DTextureCache *cache, Ls2DFrameInfo *frame)
{
if (ls_unlikely(!self) || ls_unlikely(!self->init)) {
return;
}
self->init(self, cache, frame);
}
void ls2d_component_draw(Ls2DComponent *self, Ls2DTextureCache *cache, Ls2DFrameInfo *info)
{
if (ls_unlikely(!self) || ls_unlikely(!self->draw)) {
return;
}
self->draw(self, cache, info);
}
void ls2d_component_update(Ls2DComponent *self, Ls2DTextureCache *cache, Ls2DFrameInfo *info)
{
if (ls_unlikely(!self) || ls_unlikely(!self->update)) {
return;
}
self->update(self, cache, info);
}
Ls2DComponent *ls2d_component_unref(Ls2DComponent *self)
{
return ls2d_object_unref(self);
}
void ls2d_component_set_parent_entity(Ls2DComponent *self, Ls2DEntity *entity)
{
if (ls_unlikely(!self)) {
return;
}
self->parent_entity = entity;
}
Ls2DEntity *ls2d_component_get_parent_entity(Ls2DComponent *self)
{
if (ls_unlikely(!self)) {
return NULL;
}
return self->parent_entity;
}
int ls2d_component_get_id(Ls2DComponent *self)
{
if (ls_unlikely(!self)) {
return 0;
}
return self->comp_id;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/scene.c
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <SDL.h>
#include <stdlib.h>
#include <string.h>
#include "ls2d.h"
static void ls2d_scene_init(Ls2DScene *self);
static void ls2d_scene_destroy(Ls2DScene *self);
/**
* Opaque Ls2DScene implementation
*/
struct Ls2DScene {
Ls2DObject object; /*< Parent */
const char *name;
LsPtrArray *entities; /**<Our list of entities to render. */
LsHashmap *cameras; /**<Our set of cameras */
Ls2DTextureCache *tex_cache; /**< Our private texture cache. */
Ls2DCamera *active_camera;
};
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable scene_vtable = {
.init = (ls2d_object_vfunc_init)ls2d_scene_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_scene_destroy,
.obj_name = "Ls2DScene",
};
Ls2DScene *ls2d_scene_new(void)
{
return LS2D_NEW(Ls2DScene, scene_vtable);
}
static void ls2d_scene_init(Ls2DScene *self)
{
self->entities = ls_ptr_array_new();
self->tex_cache = ls2d_texture_cache_new();
self->cameras = ls_hashmap_new_full(ls_hashmap_string_hash,
ls_hashmap_string_equal,
free,
(ls_hashmap_free_func)ls2d_camera_unref);
}
Ls2DScene *ls2d_scene_unref(Ls2DScene *self)
{
return ls2d_object_unref(self);
}
static inline void free_entity(void *v)
{
(void)ls2d_entity_unref(v);
}
static void ls2d_scene_destroy(Ls2DScene *self)
{
if (ls_likely(self->entities != NULL)) {
ls_array_free(self->entities, free_entity);
}
if (ls_likely(self->tex_cache != NULL)) {
ls2d_texture_cache_unref(self->tex_cache);
}
if (ls_likely(self->cameras != NULL)) {
ls_hashmap_free(self->cameras);
}
}
const char *ls2d_scene_get_name(Ls2DScene *self)
{
if (ls_unlikely(!self)) {
return NULL;
}
return self->name;
}
Ls2DTextureCache *ls2d_scene_get_texture_cache(Ls2DScene *self)
{
if (ls_unlikely(!self)) {
return NULL;
}
return self->tex_cache;
}
static bool ls2d_scene_should_render(Ls2DScene *self, Ls2DEntity *entity)
{
if (ls_unlikely(!entity)) {
return false;
}
if (ls_unlikely(!self->active_camera)) {
return true;
}
if (!ls2d_camera_entity_in_bounds(self->active_camera, entity)) {
return false;
}
return true;
}
void ls2d_scene_add_entity(Ls2DScene *self, Ls2DEntity *entity)
{
if (ls_unlikely(!self) || ls_unlikely(!entity)) {
SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Ls2DScene not yet initialised");
return;
}
/* Insert entity into our list */
ls_array_add(self->entities, ls2d_object_ref(entity));
}
void ls2d_scene_draw(Ls2DScene *self, Ls2DFrameInfo *frame)
{
for (uint16_t i = 0; i < self->entities->len; i++) {
Ls2DEntity *entity = self->entities->data[i];
if (!ls2d_scene_should_render(self, entity)) {
continue;
}
ls2d_entity_draw(entity, self->tex_cache, frame);
}
}
void ls2d_scene_update(Ls2DScene *self, Ls2DFrameInfo *frame)
{
if (ls_likely(self->active_camera != NULL)) {
ls2d_camera_update(self->active_camera, frame);
frame->camera = self->active_camera;
} else {
frame->camera = NULL;
}
for (uint16_t i = 0; i < self->entities->len; i++) {
Ls2DEntity *entity = self->entities->data[i];
ls2d_entity_update(entity, self->tex_cache, frame);
}
}
bool ls2d_scene_add_camera(Ls2DScene *self, const char *id, Ls2DCamera *camera)
{
if (ls_unlikely(!self) || ls_unlikely(!camera)) {
return false;
}
char *id_c = strdup(id);
if (ls_unlikely(!id_c)) {
return false;
}
if (ls_unlikely(!ls_hashmap_put(self->cameras, id_c, ls2d_object_ref(camera)))) {
ls2d_camera_unref(camera);
free(id_c);
return false;
}
if (ls_unlikely(!self->active_camera)) {
self->active_camera = camera;
}
return true;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/engine-update.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <SDL.h>
#include "engine-private.h"
#include "libls.h"
static void ls2d_engine_process_keyboard(Ls2DEngine *self, SDL_KeyboardEvent *event)
{
switch (event->keysym.sym) {
case SDLK_f:
if (event->type == SDL_KEYUP) {
ls2d_engine_set_fullscreen(self, !self->fullscreen);
}
break;
case SDLK_q:
self->running = false;
break;
case SDLK_RIGHT:
case SDLK_LEFT:
case SDLK_DOWN:
case SDLK_UP:
SDL_Log("Pressed an arrow :O");
break;
default:
break;
}
return;
}
void ls2d_engine_process_events(Ls2DEngine *self, Ls2DFrameInfo *frame)
{
SDL_Event event = { 0 };
if (ls_likely(self->active_scene != NULL)) {
ls2d_scene_update(self->active_scene, frame);
}
/* Event update */
while (SDL_PollEvent(&event) != 0) {
/* Process input if we can. */
if (ls2d_input_manager_process(self->input_manager, &event, frame)) {
continue;
}
switch (event.type) {
case SDL_KEYUP:
case SDL_KEYDOWN:
ls2d_engine_process_keyboard(self, &(event.key));
break;
case SDL_QUIT:
self->running = false;
break;
default:
break;
}
}
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/components/sprite.c
|
<reponame>lispysnake/lispysnake2d
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include "ls2d.h"
/**
* Opaque Ls2DSpriteComponent implementation
*/
struct Ls2DSpriteComponent {
Ls2DComponent parent; /*< Parent */
Ls2DTextureHandle handle;
SDL_RendererFlip flip;
double rotation;
};
static void ls2d_sprite_component_draw(Ls2DComponent *self, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame);
static void ls2d_sprite_component_init(Ls2DSpriteComponent *self);
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable sprite_vtable = {
.obj_name = "Ls2DSpriteComponent",
.init = (ls2d_object_vfunc_init)ls2d_sprite_component_init,
};
Ls2DComponent *ls2d_sprite_component_new()
{
return (Ls2DComponent *)LS2D_NEW(Ls2DSpriteComponent, sprite_vtable);
}
static void ls2d_sprite_component_init(Ls2DSpriteComponent *self)
{
self->flip = SDL_FLIP_NONE;
self->rotation = 0.0;
self->parent.draw = ls2d_sprite_component_draw;
self->parent.comp_id = LS2D_COMP_ID_SPRITE;
}
Ls2DSpriteComponent *ls2d_sprite_component_unref(Ls2DSpriteComponent *self)
{
return ls2d_object_unref(self);
}
void ls2d_sprite_component_set_texture(Ls2DSpriteComponent *self, Ls2DTextureHandle handle)
{
self->handle = handle;
}
/**
* Perform the actual sprite drawing. Long story short, we need to
* draw to our X, Y coordinates if within clip using our set
* texture.
*/
void ls2d_sprite_component_draw(Ls2DComponent *component, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame)
{
Ls2DSpriteComponent *self = (Ls2DSpriteComponent *)component;
Ls2DAnimationComponent *anim = NULL;
SDL_Rect area = { 0, 0, 0, 0 };
SDL_Point xy = { 0, 0 };
Ls2DTextureHandle handle = self->handle;
anim = (Ls2DAnimationComponent *)ls2d_entity_get_component(component->parent_entity,
LS2D_COMP_ID_ANIMATION);
if (anim) {
handle = ls2d_animation_component_get_texture(anim);
}
/* Grab a texture */
const Ls2DTextureNode *node = ls2d_texture_cache_lookup(cache, frame, handle);
if (!node) {
return;
}
area.w = node->area.w;
area.h = node->area.h;
/* Try setting up proper X, Y based on position component */
SDL_Rect dst = { area.x, area.y, node->area.w, node->area.h };
if (ls2d_camera_convert_entity_position(frame->camera,
component->parent_entity,
&xy.x,
&xy.y)) {
dst.x = xy.x;
dst.y = xy.y;
}
dst.w /= 3;
dst.h /= 3;
/* TODO: Add anchor support. */
SDL_RenderCopyEx(frame->renderer,
node->texture,
node->subregion ? &node->area : NULL,
&dst,
self->rotation,
NULL,
self->flip);
}
void ls2d_sprite_component_set_flip(Ls2DSpriteComponent *self, SDL_RendererFlip flip)
{
if (ls_unlikely(!self)) {
return;
}
self->flip = flip;
}
void ls2d_sprite_component_set_rotation(Ls2DSpriteComponent *self, double rotation)
{
if (ls_unlikely(!self)) {
return;
}
self->rotation = rotation;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/engine.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <stdbool.h>
#include "ls2d.h"
/**
* Return a new Ls2DEngine object
*/
Ls2DEngine *ls2d_engine_new(int width, int height);
/**
* Return a new Ls2DEngine object for the current display size
*/
Ls2DEngine *ls2d_engine_new_current_display(void);
/**
* Unref a previously allocated Ls2DEngine object
*/
Ls2DEngine *ls2d_engine_unref(Ls2DEngine *self);
/**
* Run an Ls2DEngine until termination.
* For convenience this will return standard EXIT_SUCCESS/EXIT_FAILURE
* codes.
*/
int ls2d_engine_run(Ls2DEngine *self, Ls2DGame *game);
/**
* Update the fullscreen state of the display
*/
void ls2d_engine_set_fullscreen(Ls2DEngine *self, bool fullscreen);
/**
* Set a framerate cap on the engine. If set to 0, there will be no cap.
*/
void ls2d_engine_set_fps_cap(Ls2DEngine *self, uint32_t fps);
/**
* Add a new scene to the Ls2DEngine.
*/
void ls2d_engine_add_scene(Ls2DEngine *self, Ls2DScene *scene);
/**
* Return the global input manager
*/
Ls2DInputManager *ls2d_engine_get_input_manager(Ls2DEngine *self);
DEF_AUTOFREE(Ls2DEngine, ls2d_engine_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/engine.c
|
<filename>src/core/engine.c<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <SDL.h>
#include <libxml/parser.h>
#include <libxml/xmlversion.h>
#include <stdlib.h>
#include "engine-private.h"
static bool did_init_xml = false;
static bool did_init_sdl = false;
static bool sdl_init(void);
static void sdl_deinit(void);
static bool xml_init(void);
static void xml_deinit(void);
static void ls2d_engine_destroy(Ls2DEngine *self);
/**
* Main vtable for our engine
*/
static Ls2DObjectTable engine_vtable = {
.destroy = (ls2d_object_vfunc_destroy)ls2d_engine_destroy,
.obj_name = "Ls2DEngine",
};
/**
* Helper to get a useful framerate limit.
*/
static inline uint32_t ls2d_get_framerate(void)
{
SDL_DisplayMode mode = { 0 };
if (SDL_GetCurrentDisplayMode(0, &mode) != 0) {
goto fail;
}
SDL_Log("Refresh rate discovered: %d", mode.refresh_rate);
if (mode.refresh_rate < 50) {
SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Slow limit framerate, enforcing 60fps");
return 60;
}
return (uint32_t)mode.refresh_rate;
fail:
SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Failed to get refresh rate: %s", SDL_GetError());
return 0;
}
Ls2DEngine *ls2d_engine_new(int width, int height)
{
Ls2DEngine *engine = NULL;
if (!sdl_init()) {
return NULL;
}
if (!xml_init()) {
return NULL;
}
engine = calloc(1, sizeof(struct Ls2DEngine));
if (!engine) {
return NULL;
}
engine->width = width;
engine->height = height;
engine->running = false;
engine->fullscreen = false;
/* autoset fps cap */
engine->fps_delay = ls2d_get_framerate();
/* Setup the window */
engine->window = SDL_CreateWindow("lispysnake2d",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
SDL_WINDOW_HIDDEN | SDL_WINDOW_ALLOW_HIGHDPI);
if (!engine->window) {
SDL_LogCritical(SDL_LOG_CATEGORY_VIDEO,
"Couldn't create window: %s",
SDL_GetError());
ls2d_engine_destroy(engine);
return NULL;
}
/* Setup our renderer, lock vsync for now. */
engine->render = SDL_CreateRenderer(engine->window,
-1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
SDL_RENDERER_TARGETTEXTURE);
if (!engine->render) {
SDL_LogCritical(SDL_LOG_CATEGORY_VIDEO,
"Couldn't create a renderer: %s",
SDL_GetError());
ls2d_engine_destroy(engine);
return NULL;
}
SDL_RenderSetLogicalSize(engine->render, width, height);
engine->buffer = SDL_CreateTexture(engine->render,
SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET,
width,
height);
if (ls_unlikely(!engine->buffer)) {
SDL_LogCritical(SDL_LOG_CATEGORY_VIDEO,
"Couldn't create double buffer: %s\n",
SDL_GetError());
ls2d_engine_destroy(engine);
return NULL;
}
engine->input_manager = ls2d_input_manager_new();
if (!engine->input_manager) {
SDL_LogCritical(SDL_LOG_CATEGORY_INPUT, "Couldn't create InputManager");
ls2d_engine_destroy(engine);
return NULL;
}
return ls2d_object_init((Ls2DObject *)engine, &engine_vtable);
}
Ls2DEngine *ls2d_engine_new_current_display()
{
SDL_DisplayMode mode = { 0 };
SDL_Rect area = { 0, 0, 320, 240 };
if (!sdl_init()) {
return NULL;
}
if (!xml_init()) {
return NULL;
}
/* Fetch current resolution, or fallback to busted default. */
if (SDL_GetCurrentDisplayMode(0, &mode) == 0) {
area.w = mode.w;
area.h = mode.h;
} else {
SDL_LogError(SDL_LOG_CATEGORY_VIDEO,
"Failed to fetch display mode: %s",
SDL_GetError());
}
return ls2d_engine_new(area.w, area.h);
}
Ls2DEngine *ls2d_engine_unref(Ls2DEngine *self)
{
return ls2d_object_unref(self);
}
static inline void free_scene(void *v)
{
(void)ls2d_scene_unref(v);
}
static void ls2d_engine_destroy(Ls2DEngine *self)
{
if (ls_unlikely(!self)) {
goto cleanup;
}
if (ls_likely(self->game != NULL) && ls_likely(self->game->funcs.destroy != NULL)) {
self->game->funcs.destroy(self->game);
}
if (ls_likely(self->render != NULL)) {
SDL_DestroyRenderer(self->render);
}
if (ls_likely(self->window != NULL)) {
SDL_DestroyWindow(self->window);
}
if (ls_likely(self->scenes != NULL)) {
ls_list_free_full(self->scenes, free_scene);
}
if (ls_likely(self->input_manager != NULL)) {
ls2d_input_manager_unref(self->input_manager);
}
free(self);
cleanup:
sdl_deinit();
xml_deinit();
}
/**
* Internally we're responsible for the primary event queue, so we'll
* manage it here and if necessary dispatch it.
*/
int ls2d_engine_run(Ls2DEngine *self, Ls2DGame *game)
{
Ls2DFrameInfo frame = { 0 };
if (ls_unlikely(!self)) {
return EXIT_FAILURE;
}
if (ls_unlikely(!game)) {
fprintf(stderr, "Missing game!\n");
return EXIT_FAILURE;
}
game->engine = self;
self->game = game;
/* Make sure to show the window */
SDL_ShowWindow(self->window);
/* Get the ball rolling */
self->running = true;
ls2d_frame_info_init(&frame);
frame.window = self->window;
frame.renderer = self->render;
if (game->funcs.init) {
if (!game->funcs.init(game)) {
fprintf(stderr, "Game init failed\n");
return EXIT_FAILURE;
}
}
/* Primary event loop */
while (self->running) {
/* Update frameinfo */
ls2d_frame_info_tick(&frame);
ls2d_engine_process_events(self, &frame);
ls2d_engine_draw(self, &frame);
/* Stash ticks */
ls2d_frame_info_stash(&frame);
double fps = ls2d_frame_info_get_fps(&frame);
char *s = NULL;
asprintf(&s, "demo: %.1f/fps", fps);
SDL_SetWindowTitle(frame.window, s);
free(s);
/* If framerate cap is set, use it.
ls2d_frame_info_delay(&frame, self->fps_delay, fps);*/
}
return EXIT_SUCCESS;
}
void ls2d_engine_set_fullscreen(Ls2DEngine *self, bool fullscreen)
{
if (!self || !self->window) {
SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Ls2DEngine not yet initialised");
return;
}
self->fullscreen = fullscreen;
SDL_SetWindowFullscreen(self->window, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
}
void ls2d_engine_set_fps_cap(Ls2DEngine *self, uint32_t fps)
{
if (ls_unlikely(!self)) {
return;
}
self->fps_delay = fps;
}
void ls2d_engine_add_scene(Ls2DEngine *self, Ls2DScene *scene)
{
if (ls_unlikely(!self) || ls_unlikely(!scene)) {
SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Ls2DEngine not yet initialised");
return;
}
self->scenes = ls_list_append(self->scenes, ls2d_object_ref(scene));
if (!self->active_scene) {
self->active_scene = scene;
}
}
Ls2DInputManager *ls2d_engine_get_input_manager(Ls2DEngine *self)
{
if (ls_unlikely(!self)) {
return NULL;
}
return self->input_manager;
}
/**
* Ensure we have initialisation of the correct subsystems
* Note this is kinda nasty but it saves calling it from our
* application.
*/
static bool sdl_init()
{
if (did_init_sdl) {
return true;
}
did_init_sdl = true;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) {
return false;
}
return true;
}
/**
* Ensure we unload SDL when the Engine is destroyed. Again this
* is kinda nasty, and not appropriate for most libraries, but it fits
* in with the single-engine-game approach we need.
*/
static void sdl_deinit()
{
SDL_Quit();
did_init_sdl = false;
}
static bool xml_init()
{
if (did_init_xml) {
return true;
}
did_init_xml = true;
LIBXML_TEST_VERSION
return true;
}
static void xml_deinit()
{
if (!did_init_xml) {
return;
}
xmlCleanupParser();
did_init_xml = false;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/ls2d.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
/**
* This is the main inclusion header for lispysnake2d and will take care
* of including any component headers.
*/
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
typedef struct Ls2DGame Ls2DGame;
typedef struct Ls2DGameVTable Ls2DGameVTable;
typedef struct Ls2DCamera Ls2DCamera;
typedef struct Ls2DInputManager Ls2DInputManager;
typedef struct Ls2DEngine Ls2DEngine;
typedef struct Ls2DEntity Ls2DEntity;
typedef struct Ls2DComponent Ls2DComponent;
typedef struct Ls2DBasicEntity Ls2DBasicEntity;
typedef struct Ls2DFrameInfo Ls2DFrameInfo;
typedef struct Ls2DObject Ls2DObject;
typedef struct Ls2DScene Ls2DScene;
typedef uint16_t Ls2DTextureHandle;
typedef struct Ls2DTextureCache Ls2DTextureCache;
typedef struct Ls2DTextureNode Ls2DTextureNode;
typedef struct Ls2DSpriteSheet Ls2DSpriteSheet;
typedef struct Ls2DTileSheet Ls2DTileSheet;
typedef struct Ls2DAnimation Ls2DAnimation;
typedef struct Ls2DTile Ls2DTile;
typedef struct Ls2DTileMap Ls2DTileMap;
typedef struct Ls2DImage Ls2DImage;
#include "libls.h"
#include "object.h"
#include "animation.h"
#include "camera.h"
#include "component.h"
#include "engine.h"
#include "entity.h"
#include "frame.h"
#include "game.h"
#include "input-manager.h"
#include "scene.h"
#include "spritesheet.h"
#include "texture-cache.h"
#include "tilesheet.h"
#include "entities/basic-entity.h"
#include "entities/image.h"
#include "entities/tilemap.h"
/* Our components */
enum Ls2DComponentID {
LS2D_COMP_ID_INVALID = 0,
LS2D_COMP_ID_POSITION,
LS2D_COMP_ID_SPRITE,
LS2D_COMP_ID_ANIMATION,
};
enum Ls2DTileOrientation {
LS2D_TILE_ORIENTATION_NONE = 0,
LS2D_TILE_ORIENTATION_ORTHOGONAL, /**<We actually only support orthogonal right now. */
LS2D_TILE_ORIENTATION_MAX,
};
#include "components/animation-component.h"
#include "components/position.h"
#include "components/sprite.h"
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/camera.h
|
<filename>src/core/camera.h
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <SDL.h>
#include "ls2d.h"
/**
* Construct a new Ls2DCamera. This allows manipulation of the view
* within a scene. Without a camera, all scenes are static.
*/
Ls2DCamera *ls2d_camera_new(Ls2DScene *scene);
/**
* Unref a previously allocated camera
*/
Ls2DCamera *ls2d_camera_unref(Ls2DCamera *self);
/**
* Set the bounds for the camera.
*/
void ls2d_camera_set_world_bounds(Ls2DCamera *self, SDL_Rect bounds);
/**
* Set the X,Y for the camera to look at.
* This function will automatically adjust to the world bounds.
*/
void ls2d_camera_set_xy(Ls2DCamera *self, SDL_Point lookat);
/**
* Returns true if the entity is within the bounds of the camera.
*/
bool ls2d_camera_entity_in_bounds(Ls2DCamera *self, Ls2DEntity *entity);
bool ls2d_camera_convert_entity_position(Ls2DCamera *self, Ls2DEntity *entity, int *x, int *y);
/**
* Get the current viewport (x/y/w/h)
*/
bool ls2d_camera_get_view(Ls2DCamera *self, SDL_Rect *view);
bool ls2d_camera_get_world_bounds(Ls2DCamera *self, SDL_Rect *view);
/**
* Update the camera
*/
void ls2d_camera_update(Ls2DCamera *self, Ls2DFrameInfo *frame);
DEF_AUTOFREE(Ls2DCamera, ls2d_camera_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/components/position.c
|
<filename>src/core/components/position.c
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include "ls2d.h"
static void ls2d_position_component_init(Ls2DPositionComponent *self);
/**
* Opaque Ls2DPositionComponent implementation
*/
struct Ls2DPositionComponent {
Ls2DComponent parent; /*< Parent */
SDL_Point pos;
int pos_z;
};
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable position_vtable = {
.obj_name = "Ls2DPositionComponent",
.init = (ls2d_object_vfunc_init)ls2d_position_component_init,
};
Ls2DComponent *ls2d_position_component_new()
{
return (Ls2DComponent *)LS2D_NEW(Ls2DPositionComponent, position_vtable);
}
static void ls2d_position_component_init(Ls2DPositionComponent *self)
{
self->parent.comp_id = LS2D_COMP_ID_POSITION;
}
Ls2DPositionComponent *ls2d_position_component_unref(Ls2DPositionComponent *self)
{
return ls2d_object_unref(self);
}
void ls2d_position_component_set_xy(Ls2DPositionComponent *self, SDL_Point pos)
{
if (ls_unlikely(!self)) {
return;
}
self->pos = pos;
}
void ls2d_position_component_set_z(Ls2DPositionComponent *self, int z)
{
if (ls_unlikely(!self)) {
return;
}
self->pos_z = z;
}
bool ls2d_position_component_get_z(Ls2DPositionComponent *self, int *z)
{
if (ls_unlikely(!self) || ls_unlikely(!z)) {
return false;
}
*z = self->pos_z;
return true;
}
bool ls2d_position_component_get_xy(Ls2DPositionComponent *self, SDL_Point *pos)
{
if (ls_unlikely(!self) || ls_unlikely(!pos)) {
return false;
}
*pos = self->pos;
return true;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/engine-draw.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <SDL.h>
#include "engine-private.h"
#include "libls.h"
void ls2d_engine_draw(Ls2DEngine *self, Ls2DFrameInfo *frame)
{
/* Clear the background */
SDL_SetRenderDrawColor(self->render, 52, 39, 89, 255);
SDL_RenderClear(self->render);
/* Clear old bfufer */
SDL_SetRenderTarget(self->render, self->buffer);
SDL_RenderClear(self->render);
/* Draw the active scene */
if (ls_likely(self->active_scene != NULL)) {
ls2d_scene_draw(self->active_scene, frame);
}
/* Copy the buffer in */
SDL_SetRenderTarget(self->render, NULL);
SDL_RenderCopy(self->render, self->buffer, NULL, NULL);
SDL_RenderPresent(self->render);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/frame.h
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include <SDL.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
/**
* The Ls2DFrameInfo object is passed to renderer and update cycles
* to give them information about the current frame pass.
*/
struct Ls2DFrameInfo {
uint32_t tick_start; /**<First tick */
uint32_t ticks; /**<Current tick count */
uint32_t prev_ticks; /**<Previous tick count */
uint32_t tick_increment; /**<Tick increment from last */
SDL_Renderer *renderer; /**<Current renderer */
SDL_Window *window; /**<Displayed window */
Ls2DCamera *camera; /**<Offset support. We need a sprite batcher. */
uint32_t frames[5];
uint32_t i_frame;
uint32_t tick_delay;
};
__attribute__((always_inline)) inline void ls2d_frame_info_init(Ls2DFrameInfo *frame)
{
frame->tick_start = SDL_GetTicks();
frame->prev_ticks = frame->tick_start - 1;
}
__attribute__((always_inline)) inline void ls2d_frame_info_tick(Ls2DFrameInfo *frame)
{
frame->ticks = SDL_GetTicks() - frame->tick_start;
frame->tick_increment = frame->ticks - frame->prev_ticks;
frame->frames[frame->i_frame % 5] = frame->ticks - frame->prev_ticks;
frame->i_frame++;
}
__attribute__((always_inline)) inline void ls2d_frame_info_stash(Ls2DFrameInfo *frame)
{
frame->tick_delay = frame->ticks - frame->prev_ticks;
frame->prev_ticks = frame->ticks;
}
/*
__attribute__((always_inline)) inline void ls2d_frame_info_delay(Ls2DFrameInfo *frame, uint32_t
fps_delay, double fps)
{
}
*/
__attribute__((always_inline)) inline double ls2d_frame_info_get_fps(Ls2DFrameInfo *frame)
{
uint32_t total = frame->i_frame >= 5 ? 5 : frame->i_frame;
double fps = 0;
for (unsigned int i = 0; i < total; i++) {
fps += frame->frames[i];
}
fps /= total;
return 1000.0 / fps;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/spritesheet/sheet.c
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
#include "spritesheet-private.h"
static void ls2d_sprite_sheet_init(Ls2DSpriteSheet *self);
static void ls2d_sprite_sheet_destroy(Ls2DSpriteSheet *self);
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable sprite_sheet_vtable = {
.init = (ls2d_object_vfunc_init)ls2d_sprite_sheet_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_sprite_sheet_destroy,
.obj_name = "Ls2DSpriteSheet",
};
static void ls2d_sprite_sheet_init(Ls2DSpriteSheet *self)
{
self->textures =
ls_hashmap_new_full(ls_hashmap_string_hash, ls_hashmap_string_equal, free, NULL);
}
Ls2DSpriteSheet *ls2d_sprite_sheet_new(Ls2DTextureCache *cache, const char *xml_file)
{
Ls2DSpriteSheet *self = LS2D_NEW(Ls2DSpriteSheet, sprite_sheet_vtable);
if (ls_unlikely(!self)) {
return NULL;
}
self->cache = cache;
if (!ls2d_sprite_sheet_parse_xml(self, xml_file)) {
ls2d_object_unref((Ls2DObject *)self);
return NULL;
}
return self;
}
Ls2DSpriteSheet *ls2d_sprite_sheet_unref(Ls2DSpriteSheet *self)
{
return ls2d_object_unref(self);
}
static void ls2d_sprite_sheet_destroy(Ls2DSpriteSheet *self)
{
ls_hashmap_free(self->textures);
free(self);
}
Ls2DTextureHandle ls2d_sprite_sheet_lookup(Ls2DSpriteSheet *self, char *key)
{
if (ls_unlikely(!self)) {
return 0;
}
return (Ls2DTextureHandle)LS_PTR_TO_INT(ls_hashmap_get(self->textures, key));
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/animation.c
|
<reponame>lispysnake/lispysnake2d
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
static void ls2d_animation_init(Ls2DAnimation *self);
static void ls2d_animation_destroy(Ls2DAnimation *self);
struct Ls2DAnimation {
Ls2DObject parent;
/* Dynamic storage of frames */
LsArray *frames;
uint16_t cur_frame;
Ls2DTextureHandle handle;
uint32_t ticks;
bool looping;
bool playing;
};
/**
* Animation frame is used internally so we can quickly cycle
* animation frames and retain a linear cache.
*/
typedef struct Ls2DAnimationFrame {
uint32_t duration;
Ls2DTextureHandle handle;
} Ls2DAnimationFrame;
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable animation_vtable = {
.init = (ls2d_object_vfunc_init)ls2d_animation_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_animation_destroy,
.obj_name = "Ls2DAnimation",
};
static void ls2d_animation_init(Ls2DAnimation *self)
{
self->cur_frame = 0;
self->looping = true;
self->playing = true;
self->frames = ls_array_new_size(sizeof(struct Ls2DAnimationFrame), 3);
}
Ls2DAnimation *ls2d_animation_new()
{
return LS2D_NEW(Ls2DAnimation, animation_vtable);
}
Ls2DAnimation *ls2d_animation_unref(Ls2DAnimation *self)
{
return ls2d_object_unref(self);
}
static void ls2d_animation_destroy(Ls2DAnimation *self)
{
ls_array_free(self->frames, NULL);
}
__attribute__((always_inline)) static inline Ls2DAnimationFrame *lookup_frame(void *cache,
uint16_t index)
{
Ls2DAnimationFrame *root = cache;
return &(root[index]);
}
bool ls2d_animation_add_frame(Ls2DAnimation *self, Ls2DTextureHandle handle, uint32_t duration)
{
Ls2DAnimationFrame *frame = NULL;
uint16_t index = 0;
if (ls_unlikely(!self)) {
return false;
}
if (ls_unlikely(!ls_array_add(self->frames, NULL))) {
return false;
}
index = (uint16_t)(self->frames->len - 1);
frame = lookup_frame(self->frames->data, index);
if (ls_unlikely(!frame)) {
return false;
}
frame->handle = handle;
frame->duration = duration;
return true;
}
void ls2d_animation_update(Ls2DAnimation *self, Ls2DFrameInfo *frame)
{
Ls2DAnimationFrame *cur_frame = NULL;
if (ls_unlikely(!self)) {
return;
}
if (ls_unlikely(!self->playing)) {
return;
}
if (ls_unlikely(self->frames->len < 1)) {
return;
}
self->ticks += frame->tick_increment;
cur_frame = lookup_frame(self->frames->data, self->cur_frame);
self->handle = cur_frame->handle;
/* If we don't need to update... don't */
if (self->ticks < cur_frame->duration) {
return;
}
self->cur_frame++;
if (self->cur_frame > self->frames->len - 1) {
if (!self->looping) {
ls2d_animation_stop(self);
return;
}
self->cur_frame = 0;
self->ticks = 0;
} else {
self->ticks = frame->tick_increment;
}
cur_frame = lookup_frame(self->frames->data, self->cur_frame);
self->handle = cur_frame->handle;
}
void ls2d_animation_stop(Ls2DAnimation *self)
{
if (ls_unlikely(!self)) {
return;
}
self->playing = false;
}
void ls2d_animation_set_looping(Ls2DAnimation *self, bool looping)
{
if (ls_unlikely(!self)) {
return;
}
self->looping = looping;
}
void ls2d_animation_reset(Ls2DAnimation *self)
{
if (ls_unlikely(!self)) {
return;
}
self->cur_frame = 0;
self->ticks = 0;
if (ls_unlikely(self->frames->len) < 1) {
return;
}
self->handle = lookup_frame(self->frames->data, 0)->handle;
}
Ls2DTextureHandle ls2d_animation_get_texture(Ls2DAnimation *self)
{
if (ls_unlikely(!self)) {
return 0;
}
return self->handle;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/scene.h
|
<filename>src/core/scene.h<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include "ls2d.h"
/**
* Construct a new scene object. Every scene contains a list of renderables
* and will process input accordingly.
* Notably, this optimises the event queue as we'll only dispatch the
* input handling to the visible renderables within the active scene.
*/
Ls2DScene *ls2d_scene_new(void);
/**
* Unref an allocated Scene. This will also deference any
* attached resources.
*/
Ls2DScene *ls2d_scene_unref(Ls2DScene *self);
/**
* Draw the scene using the current FrameInfo
*/
void ls2d_scene_draw(Ls2DScene *self, Ls2DFrameInfo *frame);
void ls2d_scene_update(Ls2DScene *self, Ls2DFrameInfo *frame);
/**
* Attach an entity to this scene.
*/
void ls2d_scene_add_entity(Ls2DScene *self, Ls2DEntity *entity);
bool ls2d_scene_add_camera(Ls2DScene *self, const char *id, Ls2DCamera *camera);
/**
* Return access to the texture cache
*/
Ls2DTextureCache *ls2d_scene_get_texture_cache(Ls2DScene *self);
DEF_AUTOFREE(Ls2DScene, ls2d_scene_unref)
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/core/entities/tilemap.c
|
<gh_stars>0
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "ls2d.h"
#include "tilemap-private.h"
static void ls2d_tilemap_destroy(Ls2DTileMap *self);
static void ls2d_tilemap_init(Ls2DTileMap *self);
static void ls2d_tilemap_draw(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame);
static void ls2d_tilemap_update(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame);
/**
* We don't yet do anything fancy.
*/
Ls2DObjectTable tilemap_vtable = {
.obj_name = "Ls2DTileMap",
.init = (ls2d_object_vfunc_init)ls2d_tilemap_init,
.destroy = (ls2d_object_vfunc_destroy)ls2d_tilemap_destroy,
};
static Ls2DTileMap *ls2d_tilemap_new_internal(void)
{
return LS2D_NEW(Ls2DTileMap, tilemap_vtable);
}
static void ls2d_tilemap_init(Ls2DTileMap *self)
{
self->layers = ls_array_new_size(sizeof(struct Ls2DTileMapLayer), 5);
self->tilesheets = ls_ptr_array_new_size(1);
self->parent.draw = ls2d_tilemap_draw;
self->parent.update = ls2d_tilemap_update;
}
Ls2DEntity *ls2d_tilemap_new(int tile_size, uint16_t width, uint16_t height)
{
Ls2DTileMap *self = NULL;
self = ls2d_tilemap_new_internal();
if (ls_unlikely(!self)) {
return NULL;
}
self->width = width;
self->height = height;
self->tile_size = tile_size;
self->size = self->width * self->height;
return (Ls2DEntity *)self;
}
Ls2DEntity *ls2d_tilemap_new_from_tmx(Ls2DTextureCache *cache, const char *filename)
{
Ls2DTileMap *self = NULL;
self = ls2d_tilemap_new_internal();
if (ls_unlikely(!self)) {
return NULL;
}
if (!ls2d_tilemap_load_tmx(self, cache, filename)) {
ls2d_tilemap_destroy(self);
free(self);
return NULL;
}
return (Ls2DEntity *)self;
}
Ls2DTileMap *ls2d_tilemap_unref(Ls2DTileMap *self)
{
return ls2d_object_unref(self);
}
__attribute__((always_inline)) static inline Ls2DTileMapLayer *lookup_layer(void *cache, int index)
{
Ls2DTileMapLayer *root = cache;
return &(root[index]);
}
static void ls2d_tilemap_free_layer(void *v)
{
Ls2DTileMapLayer *layer = v;
if (ls_likely(layer->tiles != NULL)) {
free(layer->tiles);
}
}
static void ls2d_tilemap_destroy(Ls2DTileMap *self)
{
if (ls_likely(self->layers != NULL)) {
for (uint16_t i = 0; i < self->layers->len; i++) {
Ls2DTileMapLayer *layer = lookup_layer(self->layers->data, i);
ls2d_tilemap_free_layer(layer);
}
ls_array_free(self->layers, NULL);
}
if (ls_likely(self->tilesheets != NULL)) {
ls_array_free(self->tilesheets, ls2d_tile_sheet_unref);
}
}
bool ls2d_tilemap_add_layer(Ls2DTileMap *self, int render_index)
{
Ls2DTileMapLayer *layer = NULL;
if (ls_unlikely(!self)) {
return false;
}
if (!ls_array_add(self->layers, NULL)) {
return false;
}
uint16_t index = (uint32_t)(self->layers->len - 1);
layer = lookup_layer(self->layers->data, index);
layer->render_index = render_index;
layer->tiles = calloc(sizeof(uint32_t), self->width * self->height);
if (ls_unlikely(!layer->tiles)) {
return false;
}
return true;
}
static inline uint32_t *ls2d_tilemap_get(Ls2DTileMap *self, int layer_index, int x, int y)
{
Ls2DTileMapLayer *layer = NULL;
if (ls_unlikely(!self)) {
return NULL;
}
layer = lookup_layer(self->layers->data, layer_index);
if (ls_unlikely(!layer)) {
return NULL;
}
const int index = x + self->width * y;
if (index > self->size) {
return NULL;
}
return &layer->tiles[index];
}
static bool ls2d_tilemap_get_tile(Ls2DTileMap *self, int layer_index, int x, int y, Ls2DTile *tile)
{
uint32_t *gid = ls2d_tilemap_get(self, layer_index, x, y);
if (ls_unlikely(!gid)) {
return false;
}
const uint32_t r_gid = *gid;
tile->flipped_horizontal = r_gid & LS2D_TILE_FLIPPED_HORIZONTALLY ? true : false;
tile->flipped_vertical = r_gid & LS2D_TILE_FLIPPED_VERTICALLY ? true : false;
tile->flipped_diagonal = r_gid & LS2D_TILE_FLIPPED_DIAGONALLY ? true : false;
tile->gid = r_gid & LS2D_TILE_MASK;
return true;
}
bool ls2d_tilemap_set_internal(Ls2DTileMap *self, int layer_index, int x, int y, uint32_t gid)
{
uint32_t *t = ls2d_tilemap_get(self, layer_index, x, y);
if (ls_unlikely(!t)) {
return false;
}
*t = gid;
return true;
}
bool ls2d_tilemap_set_tile(Ls2DTileMap *self, int layer_index, int x, int y, Ls2DTile tile)
{
uint32_t *t = ls2d_tilemap_get(self, layer_index, x, y);
if (ls_unlikely(!t)) {
return false;
}
uint32_t new_gid = tile.gid;
if (tile.flipped_horizontal) {
new_gid |= LS2D_TILE_FLIPPED_HORIZONTALLY;
}
if (tile.flipped_vertical) {
new_gid |= LS2D_TILE_FLIPPED_VERTICALLY;
}
if (tile.flipped_diagonal) {
new_gid |= LS2D_TILE_FLIPPED_DIAGONALLY;
}
*t = new_gid;
return true;
}
static Ls2DTextureNode *ls2d_tilemap_find_texture_node(Ls2DTileMap *self, Ls2DTextureCache *cache,
Ls2DFrameInfo *frame, uint32_t gid)
{
for (uint16_t i = 0; i < self->tilesheets->len; i++) {
Ls2DTextureHandle handle = 0;
Ls2DTileSheet *sheet = (Ls2DTileSheet *)self->tilesheets->data[i];
handle = ls2d_tile_sheet_lookup(sheet, gid);
if (handle < 1) {
continue;
}
return ls2d_texture_cache_lookup(cache, frame, handle);
}
return NULL;
}
static void ls2d_tilemap_draw(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame)
{
Ls2DTileMap *self = (Ls2DTileMap *)entity;
SDL_Rect draw_area = { 0 };
int x_draw, y_draw = 0;
for (uint16_t i = 0; i < self->layers->len; i++) {
Ls2DTileMapLayer *layer = lookup_layer(self->layers->data, i);
x_draw = self->render.x_start;
y_draw = self->render.y_start;
for (uint16_t y = self->render.first_row; y < self->render.max_row; y++) {
for (uint16_t x = self->render.first_column; x < self->render.max_column;
x++) {
Ls2DTextureNode *node = NULL;
Ls2DTextureHandle handle;
Ls2DTile tile = { 0 };
SDL_Rect area = { .w = self->tile_size,
.h = self->tile_size,
.x = x_draw,
.y = y_draw };
if (!ls2d_tilemap_get_tile(self, i, x, y, &tile)) {
fprintf(stderr, "Missing tile??!\n");
abort();
}
/* Draw outline texture for layer 0 */
if (tile.gid == 0) {
goto draw_next;
}
node = ls2d_tilemap_find_texture_node(self, cache, frame, tile.gid);
if (ls_unlikely(node == NULL)) {
goto draw_next;
}
/* Non-regular tiles, anchor to bottom of cell */
if (!node->subregion) {
area.w = node->area.w;
area.h = node->area.h;
if (node->area.w != self->tile_size ||
node->area.h != self->tile_size) {
area.y += self->tile_size;
area.y -= node->area.h;
}
}
SDL_RenderCopyEx(frame->renderer,
node->texture,
node->subregion ? &node->area : NULL,
&area,
0,
NULL,
0);
draw_next:
x_draw += self->tile_size;
}
/* Increment to next row */
y_draw += self->tile_size;
x_draw = self->render.x_start;
}
}
}
void ls2d_tilemap_add_tilesheet(Ls2DTileMap *self, Ls2DTileSheet *sheet)
{
if (ls_unlikely(!self)) {
return;
}
ls_array_add(self->tilesheets, ls2d_object_ref(sheet));
}
static void ls2d_tilemap_update(Ls2DEntity *entity, Ls2DTextureCache *cache, Ls2DFrameInfo *frame)
{
Ls2DTileMap *self = (Ls2DTileMap *)entity;
SDL_Rect draw_area = { 0 };
int visible_columns = 0;
int visible_rows = 0;
/* Basic Premise:
* Work out the visible rows and columns for the draw area
* Only draw those columns
* Draw at offset to camera and missing columns
* TODO: Optimise by only changing the camera when it needs changing.
*/
for (uint16_t i = 0; i < self->tilesheets->len; i++) {
Ls2DTileSheet *sheet = (Ls2DTileSheet *)self->tilesheets->data[i];
ls2d_tile_sheet_update(sheet, frame);
}
if (!ls2d_camera_get_view(frame->camera, &draw_area)) {
self->render.first_column = 0;
self->render.first_row = 0;
self->render.max_row = self->height;
self->render.max_column = self->width;
self->render.x_start = 0;
self->render.y_start = 0;
return;
}
visible_columns = ceil((float)draw_area.w / self->tile_size);
visible_rows = ceil((float)draw_area.h / self->tile_size);
self->render.first_row = floor((float)draw_area.y / self->tile_size);
self->render.first_column = floor((float)draw_area.x / self->tile_size);
/* TODO: Introduce MAX/MIN macros */
self->render.max_column = self->render.first_column + visible_columns + 1;
self->render.max_row = self->render.first_row + visible_rows + 1;
if (self->render.max_row > self->height) {
self->render.max_row = self->height;
}
if (self->render.max_column > self->width) {
self->render.max_column = self->width;
}
self->render.x_start = 0 - draw_area.x;
self->render.x_start += self->render.first_column * self->tile_size;
self->render.y_start = 0 - draw_area.y;
self->render.y_start += self->render.first_row * self->tile_size;
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=8 tabstop=8 expandtab:
* :indentSize=8:tabSize=8:noTabs=true:
*/
|
lispysnake/lispysnake2d
|
src/demo/level.c
|
/*
* This file is part of lispysnake2d.
*
* Copyright (c) 2019 <NAME>, Ltd.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "demo.h"
bool demo_game_load_tilemap(DemoGame *self)
{
Ls2DTextureCache *cache = ls2d_scene_get_texture_cache(self->scene);
Ls2DTileSheet *tsx = NULL;
self->tilemap = ls2d_tilemap_new_from_tmx(cache, "data/level1.tmx");
ls2d_scene_add_entity(self->scene, self->tilemap);
return true;
}
|
Il-Capitano/bozonlib
|
bz/vec.h
|
<filename>bz/vec.h
// MIT License
//
// Copyright (c) 2019 Il-Capitano
//
// 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 _bz_vec_h_
#define _bz_vec_h_
#include "common.h"
#if !bz_cxx14
#warning C++14 required for bz::vec
#else
#include <cmath>
#include <utility>
#include <type_traits>
namespace bz
{
namespace internal
{
template<size_t N, typename T>
struct vec_base
{
public:
T c[N];
vec_base(void) noexcept = default;
template<typename ...Ts, typename = std::enable_if_t<sizeof...(Ts) == N>>
constexpr vec_base(Ts ...components) noexcept
: c{ components... }
{}
constexpr T &operator [] (size_t n) noexcept
{ return this->c[n]; }
constexpr T const &operator [] (size_t n) const noexcept
{ return this->c[n]; }
};
template<typename T>
struct vec_base<2, T>
{
public:
T x;
T y;
vec_base(void) noexcept = default;
constexpr vec_base(T _x, T _y) noexcept
: x(_x), y(_y)
{}
constexpr T &operator [] (size_t n) noexcept
{
switch (n)
{
case 0: return this->x;
case 1: return this->y;
default: return reinterpret_cast<T *>(this)[n];
}
}
constexpr T const &operator [] (size_t n) const noexcept
{
switch (n)
{
case 0: return this->x;
case 1: return this->y;
default: return reinterpret_cast<T const *>(this)[n];
}
}
};
template<typename T>
struct vec_base<3, T>
{
public:
T x;
T y;
T z;
vec_base(void) noexcept = default;
constexpr vec_base(T _x, T _y, T _z) noexcept
: x(_x), y(_y), z(_z)
{}
constexpr T &operator [] (size_t n) noexcept
{
switch (n)
{
case 0: return this->x;
case 1: return this->y;
case 2: return this->z;
default: return reinterpret_cast<T *>(this)[n];
}
}
constexpr T const &operator [] (size_t n) const noexcept
{
switch (n)
{
case 0: return this->x;
case 1: return this->y;
case 2: return this->z;
default: return reinterpret_cast<T const *>(this)[n];
}
}
};
template<typename T>
struct vec_base<4, T>
{
public:
T x;
T y;
T z;
T w;
vec_base(void) noexcept = default;
constexpr vec_base(T _x, T _y, T _z, T _w) noexcept
: x(_x), y(_y), z(_z), w(_w)
{}
constexpr T &operator [] (size_t n) noexcept
{
switch (n)
{
case 0: return this->x;
case 1: return this->y;
case 2: return this->z;
case 3: return this->w;
default: return reinterpret_cast<T *>(this)[n];
}
}
constexpr T const &operator [] (size_t n) const noexcept
{
switch (n)
{
case 0: return this->x;
case 1: return this->y;
case 2: return this->z;
case 3: return this->w;
default: return reinterpret_cast<T const *>(this)[n];
}
}
};
} // namespace internal
template<size_t N, typename T>
struct vec : internal::vec_base<N, T>
{
static_assert(std::is_trivial<T>::value, "value_type for bz::vec must be trivial");
static_assert(N > 1, "dimension for bz::vec must be > 1");
private:
using self_t = vec<N, T>;
using base_t = internal::vec_base<N, T>;
public:
using value_type = T;
static constexpr auto dimension = N;
using base_t::vec_base;
using base_t::operator [];
private:
template<typename U, size_t ...self_Ns, size_t ...zero_Ns>
constexpr auto cast_helper(
std::index_sequence<self_Ns...>,
std::index_sequence<zero_Ns...>
) noexcept(
noexcept(static_cast<U>(std::declval<value_type>()))
) -> vec<sizeof... (self_Ns) + sizeof... (zero_Ns), U>
{ return { static_cast<U>((*this)[self_Ns])..., ((void)zero_Ns, U{})... }; }
template<typename U, size_t ...Ns>
constexpr auto cast_helper(
std::index_sequence<Ns...>
) noexcept(
noexcept(static_cast<U>(std::declval<value_type>()))
) -> vec<sizeof... (Ns), U>
{ return { static_cast<U>((*this)[Ns])... }; }
template<typename U, size_t ...Ns>
constexpr self_t &op_plus_eq_helper(
vec<N, U> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(std::declval<value_type &>() += rhs[0])
)
#if bz_cxx17
{ (((*this)[Ns] += rhs[Ns]), ...); return *this; }
#else
{
using arr = int[N];
arr{ (((*this)[Ns] += rhs[Ns]), 0)... };
return *this;
}
#endif
template<typename U, size_t ...Ns>
constexpr self_t &op_minus_eq_helper(
vec<N, U> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(std::declval<value_type &>() -= rhs[0])
)
#if bz_cxx17
{ (((*this)[Ns] -= rhs[Ns]), ...); return *this; }
#else
{
using arr = int[N];
arr{ (((*this)[Ns] -= rhs[Ns]), 0)... };
return *this;
}
#endif
template<typename U, size_t ...Ns>
constexpr self_t &op_multiply_eq_helper(
U const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(std::declval<value_type &>() *= rhs)
)
#if bz_cxx17
{ (((*this)[Ns] *= rhs), ...); return *this; }
#else
{
using arr = int[N];
arr{ (((*this)[Ns] *= rhs), 0)... };
return *this;
}
#endif
template<typename U, size_t ...Ns>
constexpr self_t &op_divide_eq_helper(
U const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(std::declval<value_type &>() /= rhs)
)
#if bz_cxx17
{ (((*this)[Ns] /= rhs), ...); return *this; }
#else
{
using arr = int[N];
arr{ (((*this)[Ns] /= rhs), 0)... };
return *this;
}
#endif
public:
template<size_t M, typename U, typename = std::enable_if_t<M <= N>>
constexpr explicit operator vec<M, U> (void) noexcept
{
return this->cast_helper<U>(
std::make_index_sequence<M>{}
);
}
template<size_t M, typename U>
constexpr explicit operator vec<M, U> (void) noexcept
{
return this->cast_helper<U>(
std::make_index_sequence<N>{},
std::make_index_sequence<M - N>{}
);
}
template<typename U>
constexpr self_t &operator += (vec<N, U> const &rhs) noexcept(
noexcept(std::declval<value_type &>() += rhs[0])
)
{ return this->op_plus_eq_helper(rhs, std::make_index_sequence<N>{}); }
template<typename U>
constexpr self_t &operator -= (vec<N, U> const &rhs) noexcept(
noexcept(std::declval<value_type &>() -= rhs[0])
)
{ return this->op_minus_eq_helper(rhs, std::make_index_sequence<N>{}); }
template<typename U>
constexpr self_t &operator *= (U const &rhs) noexcept(
noexcept(std::declval<value_type &>() *= rhs)
)
{ return this->op_multiply_eq_helper(rhs, std::make_index_sequence<N>{}); }
template<typename U>
constexpr self_t &operator /= (U const &rhs) noexcept(
noexcept(std::declval<value_type &>() /= rhs)
)
{ return this->op_divide_eq_helper(rhs, std::make_index_sequence<N>{}); }
};
namespace internal
{
template<size_t N, typename T, size_t ...Ns>
constexpr auto op_plus_helper(
vec<N, T> const &v,
std::index_sequence<Ns...>
) noexcept(
noexcept(+v[0])
) -> vec<N, decltype(+v[0])>
{ return { (+v[Ns])... }; }
template<size_t N, typename T, size_t ...Ns>
constexpr auto op_minus_helper(
vec<N, T> const &v,
std::index_sequence<Ns...>
) noexcept(
noexcept(-v[0])
) -> vec<N, decltype(-v[0])>
{ return { (-v[Ns])... }; }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr auto op_plus_helper(
vec<N, T1> const &lhs,
vec<N, T2> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] + rhs[0])
) -> vec<N, decltype(lhs[0] + rhs[0])>
{ return { (lhs[Ns] + rhs[Ns])... }; }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr auto op_minus_helper(
vec<N, T1> const &lhs,
vec<N, T2> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] - rhs[0])
) -> vec<N, decltype(lhs[0] - rhs[0])>
{ return { (lhs[Ns] - rhs[Ns])... }; }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr auto op_multiply_helper(
vec<N, T1> const &lhs,
T2 const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] * rhs)
) -> vec<N, decltype(lhs[0] * rhs)>
{ return { (lhs[Ns] * rhs)... }; }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr auto op_multiply_helper(
T1 const &lhs,
vec<N, T2> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs * rhs[0])
) -> vec<N, decltype(lhs * rhs[0])>
{ return { (lhs * rhs[Ns])... }; }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr auto op_divide_helper(
vec<N, T1> const &lhs,
T2 const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] / rhs)
) -> vec<N, decltype(lhs[0] / rhs)>
{ return { (lhs[Ns] / rhs)... }; }
#if bz_cxx17
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr bool op_eq_helper(
vec<N, T1> const &lhs,
vec<N, T2> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] == rhs[0])
)
{ return ((lhs[Ns] == rhs[Ns]) && ...); }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr bool op_not_eq_helper(
vec<N, T1> const &lhs,
vec<N, T2> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] != rhs[0])
)
{ return ((lhs[Ns] != rhs[Ns]) || ...); }
#else
constexpr bool bool_and(bool val) noexcept
{ return val; }
template<typename ...Ts>
constexpr bool bool_and(bool val, Ts ...vals) noexcept
{ return val && bool_and(vals...); }
constexpr bool bool_or(bool val) noexcept
{ return val; }
template<typename ...Ts>
constexpr bool bool_or(bool val, Ts ...vals) noexcept
{ return val || bool_or(vals...); }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr bool op_eq_helper(
vec<N, T1> const &lhs,
vec<N, T2> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] == rhs[0])
)
{ return bool_and((lhs[Ns] == rhs[Ns])...); }
template<size_t N, typename T1, typename T2, size_t ...Ns>
constexpr bool op_not_eq_helper(
vec<N, T1> const &lhs,
vec<N, T2> const &rhs,
std::index_sequence<Ns...>
) noexcept(
noexcept(lhs[0] != rhs[0])
)
{ return bool_or((lhs[Ns] != rhs[Ns])...); }
#endif // c++17
} // namespace internal
template<size_t N, typename T>
constexpr auto operator + (
vec<N, T> const &v
) noexcept(
noexcept(internal::op_plus_helper(v, std::make_index_sequence<N>{}))
) -> decltype(internal::op_plus_helper(v, std::make_index_sequence<N>{}))
{ return internal::op_plus_helper(v, std::make_index_sequence<N>{}); }
template<size_t N, typename T>
constexpr auto operator - (
vec<N, T> const &v
) noexcept(
noexcept(internal::op_minus_helper(v, std::make_index_sequence<N>{}))
) -> decltype(internal::op_minus_helper(v, std::make_index_sequence<N>{}))
{ return internal::op_minus_helper(v, std::make_index_sequence<N>{}); }
template<size_t N, typename T1, typename T2>
constexpr auto operator + (
vec<N, T1> const &lhs,
vec<N, T2> const &rhs
) noexcept(
noexcept(internal::op_plus_helper(lhs, rhs, std::make_index_sequence<N>{}))
) -> decltype(internal::op_plus_helper(lhs, rhs, std::make_index_sequence<N>{}))
{ return internal::op_plus_helper(lhs, rhs, std::make_index_sequence<N>{}); }
template<size_t N, typename T1, typename T2>
constexpr auto operator - (
vec<N, T1> const &lhs,
vec<N, T2> const &rhs
) noexcept(
noexcept(internal::op_minus_helper(lhs, rhs, std::make_index_sequence<N>{}))
) -> decltype(internal::op_minus_helper(lhs, rhs, std::make_index_sequence<N>{}))
{ return internal::op_minus_helper(lhs, rhs, std::make_index_sequence<N>{}); }
template<size_t N, typename T1, typename T2>
constexpr auto operator * (
vec<N, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(internal::op_multiply_helper(lhs, rhs, std::make_index_sequence<N>{}))
) -> decltype(internal::op_multiply_helper(lhs, rhs, std::make_index_sequence<N>{}))
{ return internal::op_multiply_helper(lhs, rhs, std::make_index_sequence<N>{}); }
template<size_t N, typename T1, typename T2>
constexpr auto operator * (
T1 const &lhs,
vec<N, T2> const &rhs
) noexcept(
noexcept(internal::op_multiply_helper(lhs, rhs, std::make_index_sequence<N>{}))
) -> decltype(internal::op_multiply_helper(lhs, rhs, std::make_index_sequence<N>{}))
{ return internal::op_multiply_helper(lhs, rhs, std::make_index_sequence<N>{}); }
template<size_t N, typename T1, typename T2>
constexpr auto operator / (
vec<N, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(internal::op_divide_helper(lhs, rhs, std::make_index_sequence<N>{}))
) -> decltype(internal::op_divide_helper(lhs, rhs, std::make_index_sequence<N>{}))
{ return internal::op_divide_helper(lhs, rhs, std::make_index_sequence<N>{}); }
template<size_t N, typename T1, typename T2>
constexpr bool operator == (
vec<N, T1> const &lhs,
vec<N, T2> const &rhs
) noexcept(
noexcept(internal::op_eq_helper(lhs, rhs, std::make_index_sequence<N>{}))
)
{ return internal::op_eq_helper(lhs, rhs, std::make_index_sequence<N>{}); }
template<size_t N, typename T1, typename T2>
constexpr bool operator != (
vec<N, T1> const &lhs,
vec<N, T2> const &rhs
) noexcept(
noexcept(internal::op_not_eq_helper(lhs, rhs, std::make_index_sequence<N>{}))
)
{ return internal::op_not_eq_helper(lhs, rhs, std::make_index_sequence<N>{}); }
// specialized operators for N = 2, 3, 4, so we don't rely as much on the inliner to optimize
// ==== N == 2 ====
template<typename T>
constexpr auto operator + (
vec<2, T> const v
) noexcept(
noexcept(+v.x)
) -> vec<2, decltype(+v.x)>
{ return { +v.x, +v.y }; }
template<typename T>
constexpr auto operator - (
vec<2, T> const v
) noexcept(
noexcept(-v.x)
) -> vec<2, decltype(-v.x)>
{ return { -v.x, -v.y }; }
template<typename T1, typename T2>
constexpr auto operator + (
vec<2, T1> const &lhs,
vec<2, T2> const &rhs
) noexcept(
noexcept(lhs.x + rhs.x)
) -> vec<2, decltype(lhs.x + rhs.x)>
{ return { lhs.x + rhs.x, lhs.y + rhs.y }; }
template<typename T1, typename T2>
constexpr auto operator - (
vec<2, T1> const &lhs,
vec<2, T2> const &rhs
) noexcept(
noexcept(lhs.x - rhs.x)
) -> vec<2, decltype(lhs.x - rhs.x)>
{ return { lhs.x - rhs.x, lhs.y - rhs.y }; }
template<typename T1, typename T2>
constexpr auto operator * (
vec<2, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(lhs.x * rhs)
) -> vec<2, decltype(lhs.x * rhs)>
{ return { lhs.x * rhs, lhs.y * rhs }; }
template<typename T1, typename T2>
constexpr auto operator * (
T1 const &lhs,
vec<2, T2> const &rhs
) noexcept(
noexcept(lhs * rhs.x)
) -> vec<2, decltype(lhs * rhs.x)>
{ return { lhs * rhs.x, lhs * rhs.y }; }
template<typename T1, typename T2>
constexpr auto operator / (
vec<2, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(lhs.x / rhs)
) -> vec<2, decltype(lhs.x / rhs)>
{ return { lhs.x / rhs, lhs.y / rhs }; }
template<typename T1, typename T2>
constexpr bool operator == (
vec<2, T1> const &lhs,
vec<2, T2> const &rhs
) noexcept(
noexcept(lhs.x == rhs.x)
)
{ return lhs.x == rhs.x && lhs.y == rhs.y; }
template<typename T1, typename T2>
constexpr bool operator != (
vec<2, T1> const &lhs,
vec<2, T2> const &rhs
) noexcept(
noexcept(lhs.x != rhs.x)
)
{ return lhs.x != rhs.x || lhs.y != rhs.y; }
// ==== N == 3 ====
template<typename T>
constexpr auto operator + (
vec<3, T> const v
) noexcept(
noexcept(+v.x)
) -> vec<3, decltype(+v.x)>
{ return { +v.x, +v.y, +v.z }; }
template<typename T>
constexpr auto operator - (
vec<3, T> const v
) noexcept(
noexcept(-v.x)
) -> vec<3, decltype(-v.x)>
{ return { -v.x, -v.y, -v.z }; }
template<typename T1, typename T2>
constexpr auto operator + (
vec<3, T1> const &lhs,
vec<3, T2> const &rhs
) noexcept(
noexcept(lhs.x + rhs.x)
) -> vec<3, decltype(lhs.x + rhs.x)>
{ return { lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z }; }
template<typename T1, typename T2>
constexpr auto operator - (
vec<3, T1> const &lhs,
vec<3, T2> const &rhs
) noexcept(
noexcept(lhs.x - rhs.x)
) -> vec<3, decltype(lhs.x - rhs.x)>
{ return { lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z }; }
template<typename T1, typename T2>
constexpr auto operator * (
vec<3, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(lhs.x * rhs)
) -> vec<3, decltype(lhs.x * rhs)>
{ return { lhs.x * rhs, lhs.y * rhs, lhs.z * rhs }; }
template<typename T1, typename T2>
constexpr auto operator * (
T1 const &lhs,
vec<3, T2> const &rhs
) noexcept(
noexcept(lhs * rhs.x)
) -> vec<3, decltype(lhs * rhs.x)>
{ return { lhs * rhs.x, lhs * rhs.y, lhs * rhs.z }; }
template<typename T1, typename T2>
constexpr auto operator / (
vec<3, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(lhs.x / rhs)
) -> vec<3, decltype(lhs.x / rhs)>
{ return { lhs.x / rhs, lhs.y / rhs, lhs.z / rhs }; }
template<typename T1, typename T2>
constexpr bool operator == (
vec<3, T1> const &lhs,
vec<3, T2> const &rhs
) noexcept(
noexcept(lhs.x == rhs.x)
)
{ return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; }
template<typename T1, typename T2>
constexpr bool operator != (
vec<3, T1> const &lhs,
vec<3, T2> const &rhs
) noexcept(
noexcept(lhs.x != rhs.x)
)
{ return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z; }
// ==== N == 4 ====
template<typename T>
constexpr auto operator + (
vec<4, T> const v
) noexcept(
noexcept(+v.x)
) -> vec<4, decltype(+v.x)>
{ return { +v.x, +v.y, +v.z, +v.w }; }
template<typename T>
constexpr auto operator - (
vec<4, T> const v
) noexcept(
noexcept(-v.x)
) -> vec<4, decltype(-v.x)>
{ return { -v.x, -v.y, -v.z, -v.w }; }
template<typename T1, typename T2>
constexpr auto operator + (
vec<4, T1> const &lhs,
vec<4, T2> const &rhs
) noexcept(
noexcept(lhs.x + rhs.x)
) -> vec<4, decltype(lhs.x + rhs.x)>
{ return { lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w }; }
template<typename T1, typename T2>
constexpr auto operator - (
vec<4, T1> const &lhs,
vec<4, T2> const &rhs
) noexcept(
noexcept(lhs.x - rhs.x)
) -> vec<4, decltype(lhs.x - rhs.x)>
{ return { lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w }; }
template<typename T1, typename T2>
constexpr auto operator * (
vec<4, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(lhs.x * rhs)
) -> vec<4, decltype(lhs.x * rhs)>
{ return { lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs }; }
template<typename T1, typename T2>
constexpr auto operator * (
T1 const &lhs,
vec<4, T2> const &rhs
) noexcept(
noexcept(lhs * rhs.x)
) -> vec<4, decltype(lhs * rhs.x)>
{ return { lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w }; }
template<typename T1, typename T2>
constexpr auto operator / (
vec<4, T1> const &lhs,
T2 const &rhs
) noexcept(
noexcept(lhs.x / rhs)
) -> vec<4, decltype(lhs.x / rhs)>
{ return { lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs }; }
template<typename T1, typename T2>
constexpr bool operator == (
vec<4, T1> const &lhs,
vec<4, T2> const &rhs
) noexcept(
noexcept(lhs.x == rhs.x)
)
{ return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; }
template<typename T1, typename T2>
constexpr bool operator != (
vec<4, T1> const &lhs,
vec<4, T2> const &rhs
) noexcept(
noexcept(lhs.x != rhs.x)
)
{ return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; }
template<typename T>
using vec2 = vec<2, T>;
template<typename T>
using vec3 = vec<3, T>;
template<typename T>
using vec4 = vec<4, T>;
using vec2i = vec2<int>;
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec3i = vec3<int>;
using vec3f = vec3<float>;
using vec3d = vec3<double>;
using vec4i = vec4<int>;
using vec4f = vec4<float>;
using vec4d = vec4<double>;
} // namespace bz
#endif // c++14
#endif // _bz_vec_h_
|
Il-Capitano/bozonlib
|
bz/units.h
|
// MIT License
//
// Copyright (c) 2019 Il-Capitano
//
// 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 _bz_units_h_
#define _bz_units_h_
#include "common.h"
#if !bz_cxx14
#warning C++14 required for bz::units
#else
#include <cmath>
#include <cstdlib>
#include <cstdint>
#include <utility>
#include <type_traits>
namespace bz
{
namespace units
{
namespace standards
{
struct si
{};
struct imperial
{};
} // namespace standards
template<std::intmax_t NUM, std::intmax_t DEN>
struct static_rational
{
static_assert(DEN != 0, "denominator in static_rational can't be 0");
static_assert(DEN > 0, "denominator in static_rational must be positive");
static constexpr auto num = NUM;
static constexpr auto den = DEN;
template<typename T>
static constexpr T value = static_cast<T>(num) / static_cast<T>(den);
};
namespace internal
{
constexpr std::intmax_t calculate_gcd(std::intmax_t a, std::intmax_t b)
{
while (a % b != 0)
{
auto tmp = b;
b = a % b;
a = tmp;
}
return b;
}
} // namespace internal
template<std::intmax_t NUM, std::intmax_t DEN = 1>
using make_static_rational = static_rational<
(DEN < 0 ? -NUM : NUM) / internal::calculate_gcd(NUM < 0 ? -NUM : NUM, DEN < 0 ? -DEN : DEN),
(DEN < 0 ? -DEN : DEN) / internal::calculate_gcd(NUM < 0 ? -NUM : NUM, DEN < 0 ? -DEN : DEN)
>;
namespace internal
{
template<typename, typename>
struct static_rational_add_impl;
template<typename, typename>
struct static_rational_subtract_impl;
template<typename, typename>
struct static_rational_multiply_impl;
template<typename, typename>
struct static_rational_divide_impl;
template<
std::intmax_t NUM1, std::intmax_t DEN1,
std::intmax_t NUM2, std::intmax_t DEN2
>
struct static_rational_add_impl<
static_rational<NUM1, DEN1>,
static_rational<NUM2, DEN2>
>
{ using type = make_static_rational<NUM1 * DEN2 + NUM2 * DEN1, DEN1 * DEN2>; };
template<
std::intmax_t NUM1, std::intmax_t DEN1,
std::intmax_t NUM2, std::intmax_t DEN2
>
struct static_rational_subtract_impl<
static_rational<NUM1, DEN1>,
static_rational<NUM2, DEN2>
>
{ using type = make_static_rational<NUM1 * DEN2 - NUM2 * DEN1, DEN1 * DEN2>; };
template<
std::intmax_t NUM1, std::intmax_t DEN1,
std::intmax_t NUM2, std::intmax_t DEN2
>
struct static_rational_multiply_impl<
static_rational<NUM1, DEN1>,
static_rational<NUM2, DEN2>
>
{ using type = make_static_rational<NUM1 * NUM2, DEN1 * DEN2>; };
template<
std::intmax_t NUM1, std::intmax_t DEN1,
std::intmax_t NUM2, std::intmax_t DEN2
>
struct static_rational_divide_impl<
static_rational<NUM1, DEN1>,
static_rational<NUM2, DEN2>
>
{ using type = make_static_rational<NUM1 * NUM2, DEN1 * DEN2>; };
} // namespace internal
template<typename Rat1, typename Rat2>
using static_rational_add = typename internal::static_rational_add_impl<Rat1, Rat2>::type;
template<typename Rat1, typename Rat2>
using static_rational_subtract = typename internal::static_rational_subtract_impl<Rat1, Rat2>::type;
template<typename Rat1, typename Rat2>
using static_rational_multiply = typename internal::static_rational_multiply_impl<Rat1, Rat2>::type;
template<typename Rat1, typename Rat2>
using static_rational_divide = typename internal::static_rational_divide_impl<Rat1, Rat2>::type;
// reference: https://www.nist.gov/pml/weights-and-measures/metric-si/si-units
template<
typename Std,
typename LengthRatio,
typename TimeRatio,
typename AmountOfSubstanceRatio,
typename CurrentRatio,
typename TemperatureRatio,
typename LuminousIntensityRatio,
typename MassRatio
>
struct dimension;
template<typename>
constexpr bool is_dimension = false;
template<typename ...Ts>
constexpr bool is_dimension<dimension<Ts...>> = true;
template<
typename Std,
std::intmax_t LENGTH_NUM, std::intmax_t LENGTH_DEN,
std::intmax_t TIME_NUM, std::intmax_t TIME_DEN,
std::intmax_t AMOUNT_OF_SUBSTANCE_NUM, std::intmax_t AMOUNT_OF_SUBSTANCE_DEN,
std::intmax_t CURRENT_NUM, std::intmax_t CURRENT_DEN,
std::intmax_t TEMPERATURE_NUM, std::intmax_t TEMPERATURE_DEN,
std::intmax_t LUMINOUS_INTENSITY_NUM, std::intmax_t LUMINOUS_INTENSITY_DEN,
std::intmax_t MASS_NUM, std::intmax_t MASS_DEN
>
struct dimension<
Std,
static_rational<LENGTH_NUM, LENGTH_DEN>,
static_rational<TIME_NUM, TIME_DEN>,
static_rational<AMOUNT_OF_SUBSTANCE_NUM, AMOUNT_OF_SUBSTANCE_DEN>,
static_rational<CURRENT_NUM, CURRENT_DEN>,
static_rational<TEMPERATURE_NUM, TEMPERATURE_DEN>,
static_rational<LUMINOUS_INTENSITY_NUM, LUMINOUS_INTENSITY_DEN>,
static_rational<MASS_NUM, MASS_DEN>
>
{
using standard_type = Std;
using length = static_rational<LENGTH_NUM, LENGTH_DEN>;
using time = static_rational<TIME_NUM, TIME_DEN>;
using amount_of_substance = static_rational<AMOUNT_OF_SUBSTANCE_NUM, AMOUNT_OF_SUBSTANCE_DEN>;
using electric_current = static_rational<CURRENT_NUM, CURRENT_DEN>;
using temperature = static_rational<TEMPERATURE_NUM, TEMPERATURE_DEN>;
using luminous_intensity = static_rational<LUMINOUS_INTENSITY_NUM, LUMINOUS_INTENSITY_DEN>;
using mass = static_rational<MASS_NUM, MASS_DEN>;
};
namespace internal
{
template<typename, typename>
struct dimension_multiply_impl;
template<typename, typename>
struct dimension_divide_impl;
template<
typename Std,
typename ...Bases1,
typename ...Bases2
>
struct dimension_multiply_impl<
dimension<Std, Bases1...>,
dimension<Std, Bases2...>
>
{ using type = dimension<Std, static_rational_add<Bases1, Bases2>...>; };
template<
typename Std,
typename ...Bases1,
typename ...Bases2
>
struct dimension_divide_impl<
dimension<Std, Bases1...>,
dimension<Std, Bases2...>
>
{ using type = dimension<Std, static_rational_subtract<Bases1, Bases2>...>; };
} // namespace internal
template<typename Dim1, typename Dim2>
using dimension_multiply = typename internal::dimension_multiply_impl<Dim1, Dim2>::type;
template<typename Dim1, typename Dim2>
using dimension_divide = typename internal::dimension_divide_impl<Dim1, Dim2>::type;
#define dim_def(dim_type, index) \
template<typename Std> \
using dim_type = dimension< \
Std, \
make_static_rational<index == 0 ? 1 : 0>, \
make_static_rational<index == 1 ? 1 : 0>, \
make_static_rational<index == 2 ? 1 : 0>, \
make_static_rational<index == 3 ? 1 : 0>, \
make_static_rational<index == 4 ? 1 : 0>, \
make_static_rational<index == 5 ? 1 : 0>, \
make_static_rational<index == 6 ? 1 : 0> \
>; \
namespace si { using dim_type = ::bz::units::dim_type<standards::si>; } \
namespace imperial { using dim_type = ::bz::units::dim_type<standards::imperial>; }
dim_def(dimension_none, -1)
dim_def(length, 0)
dim_def(time, 1)
dim_def(amount_of_substance, 2)
dim_def(electric_current, 3)
dim_def(temperature, 4)
dim_def(luminous_intensity, 5)
dim_def(mass, 6)
#undef dim_def
#define dim_def_alias(dim_type, alias_type) \
template<typename Std> \
using dim_type = alias_type<Std>; \
namespace si { using dim_type = ::bz::units::dim_type<standards::si>; } \
namespace imperial { using dim_type = ::bz::units::dim_type<standards::imperial>; }
#define dim_def_mul(dim_type, lhs, rhs) \
template<typename Std> \
using dim_type = dimension_multiply<lhs<Std>, rhs<Std>>; \
namespace si { using dim_type = ::bz::units::dim_type<standards::si>; } \
namespace imperial { using dim_type = ::bz::units::dim_type<standards::imperial>; }
#define dim_def_div(dim_type, lhs, rhs) \
template<typename Std> \
using dim_type = dimension_divide<lhs<Std>, rhs<Std>>; \
namespace si { using dim_type = ::bz::units::dim_type<standards::si>; } \
namespace imperial { using dim_type = ::bz::units::dim_type<standards::imperial>; }
// reference: https://physics.nist.gov/cuu/Units/units.html
// no special units
dim_def_mul(area, length, length)
dim_def_mul(volume, area, length)
dim_def_div(velocity, length, time)
dim_def_div(acceleration, velocity, time)
dim_def_mul(impulse, velocity, mass)
// special units in SI
dim_def_div(frequency, dimension_none, time)
dim_def_div(force, impulse, time)
dim_def_div(pressure, force, area)
dim_def_mul(work, force, length)
dim_def_mul(energy, force, length)
dim_def_mul(heat, force, length)
dim_def_div(power, energy, time)
dim_def_mul(electric_charge, electric_current, time)
dim_def_div(electric_potential, power, electric_current)
dim_def_div(electromotive_force, power, electric_current)
dim_def_div(capacitance, electric_charge, electric_potential)
dim_def_div(electric_resistance, electric_potential, electric_current)
dim_def_div(electric_conductance, electric_current, electric_potential)
dim_def_mul(magnetic_flux, electric_potential, time)
dim_def_div(magnetic_flux_density, magnetic_flux, area)
dim_def_div(inductance, magnetic_flux, electric_current)
dim_def_alias(luminous_flux, luminous_intensity)
dim_def_div(illuminance, luminous_flux, area)
dim_def_div(activity, dimension_none, time)
#undef dim_def_alias
#undef dim_def_mul
#undef dim_def_div
namespace internal
{
template<typename T>
constexpr T power_of_ten(std::intmax_t exp)
{
T result = 1;
if (exp < 0)
{
return 1 / power_of_ten<T>(-exp);
}
else
{
for (std::intmax_t i = 0; i < exp; ++i)
{
result *= 10;
}
}
return result;
}
} // namespace internal
template<std::intmax_t NUM, std::intmax_t DEN, std::intmax_t EXP>
struct ratio
{
static_assert(NUM >= 0, "numerator in bz::units::ratio must be >= 0");
static_assert(DEN > 0, "denominator in bz::units::ratio must be > 0");
static constexpr auto num = NUM;
static constexpr auto den = DEN;
static constexpr auto exp = EXP;
template<typename T>
static constexpr T value =
(static_cast<T>(NUM) / static_cast<T>(DEN)) * internal::power_of_ten<T>(EXP);
};
template<typename>
constexpr bool is_ratio = false;
template<std::intmax_t NUM, std::intmax_t DEN, std::intmax_t EXP>
constexpr bool is_ratio<ratio<NUM, DEN, EXP>> = true;
namespace internal
{
constexpr std::intmax_t calculate_num(std::intmax_t num, std::intmax_t den)
{
while (den % 10 == 0)
{
den /= 10;
}
while (num % 10 == 0)
{
num /= 10;
}
while (den % 2 == 0)
{
num *= 5;
den /= 2;
}
while (den % 5 == 0)
{
num *= 2;
den /= 5;
}
return num;
}
constexpr std::intmax_t calculate_den(std::intmax_t, std::intmax_t den)
{
while (den % 10 == 0)
{
den /= 10;
}
while (den % 2 == 0)
{
den /= 2;
}
while (den % 5 == 0)
{
den /= 5;
}
return den;
}
constexpr std::intmax_t calculate_exp(std::intmax_t num, std::intmax_t den, std::intmax_t exp)
{
while (den % 10 == 0)
{
den /= 10;
exp -= 1;
}
while (num % 10 == 0)
{
num /= 10;
exp += 1;
}
while (den % 2 == 0)
{
num *= 5;
den /= 2;
exp -= 1;
}
while (den % 5 == 0)
{
num *= 2;
den /= 5;
exp -= 1;
}
return exp;
}
template<std::intmax_t NUM, std::intmax_t DEN, std::intmax_t EXP>
struct make_ratio_impl
{
static_assert(NUM >= 0, "numerator in bz::units::make_ratio must be >= 0");
static_assert(DEN > 0, "denominator in bz::units::make_ratio must be > 0");
private:
static constexpr std::intmax_t _gcd = calculate_gcd(NUM, DEN);
static constexpr std::intmax_t _num = calculate_num(NUM / _gcd, DEN / _gcd);
static constexpr std::intmax_t _den = calculate_den(NUM / _gcd, DEN / _gcd);
static constexpr std::intmax_t _exp = calculate_exp(NUM / _gcd, DEN / _gcd, EXP);
public:
using type = ratio<_num, _den, _exp>;
};
} // namespace internal
template<std::intmax_t NUM, std::intmax_t DEN = 1, std::intmax_t EXP = 0>
using make_ratio = typename internal::make_ratio_impl<NUM, DEN, EXP>::type;
using atto = make_ratio<1, 1, -18>;
using femto = make_ratio<1, 1, -15>;
using pico = make_ratio<1, 1, -12>;
using nano = make_ratio<1, 1, -9>;
using micro = make_ratio<1, 1, -6>;
using milli = make_ratio<1, 1, -3>;
using centi = make_ratio<1, 1, -2>;
using deci = make_ratio<1, 1, -1>;
using deca = make_ratio<1, 1, 1>;
using hecto = make_ratio<1, 1, 2>;
using kilo = make_ratio<1, 1, 3>;
using mega = make_ratio<1, 1, 6>;
using giga = make_ratio<1, 1, 9>;
using tera = make_ratio<1, 1, 12>;
using peta = make_ratio<1, 1, 15>;
using exa = make_ratio<1, 1, 18>;
namespace internal
{
template<typename, typename>
struct ratio_multiply_impl;
template<typename, typename>
struct ratio_divide_impl;
template<
std::intmax_t Num1, std::intmax_t Den1, std::intmax_t Exp1,
std::intmax_t Num2, std::intmax_t Den2, std::intmax_t Exp2
>
struct ratio_multiply_impl<
ratio<Num1, Den1, Exp1>,
ratio<Num2, Den2, Exp2>
>
{
using type = make_ratio<Num1 * Num2, Den1 * Den2, Exp1 + Exp2>;
};
template<
std::intmax_t Num1, std::intmax_t Den1, std::intmax_t Exp1,
std::intmax_t Num2, std::intmax_t Den2, std::intmax_t Exp2
>
struct ratio_divide_impl<
ratio<Num1, Den1, Exp1>,
ratio<Num2, Den2, Exp2>
>
{
using type = make_ratio<Num1 * Den2, Den1 * Num2, Exp1 - Exp2>;
};
} // namespace internal
template<typename Ratio1, typename Ratio2>
using ratio_multiply = typename internal::ratio_multiply_impl<Ratio1, Ratio2>::type;
template<typename Ratio1, typename Ratio2>
using ratio_divide = typename internal::ratio_divide_impl<Ratio1, Ratio2>::type;
template<typename Dim, typename Ratio = make_ratio<1>>
struct unit
{
static_assert(is_dimension<Dim>, "invalid dimension_type for bz::units::unit");
static_assert(is_ratio<Ratio>, "invalid ratio_type for bz::units::unit");
using dimension_type = Dim;
using ratio_type = Ratio;
using base_unit_type = unit<dimension_type, make_ratio<1>>;
};
namespace internal
{
template<typename T>
struct is_unit_impl
{
using no = char;
using yes = int;
template<typename U>
static auto test(U) -> decltype(
std::declval<typename U::dimension_type>(),
std::declval<typename U::ratio_type>(),
std::declval<typename U::base_unit_type>(),
yes{}
);
static no test(...);
static constexpr bool value = std::is_same<decltype(test(std::declval<T>())), yes>::value;
};
} // namespace internal
template<typename T>
constexpr bool is_unit = internal::is_unit_impl<T>::value;
template<typename Unit1, typename Unit2>
constexpr bool is_same_unit =
std::is_same<typename Unit1::dimension_type, typename Unit2::dimension_type>::value
&& std::is_same<typename Unit1::ratio_type, typename Unit2::ratio_type>::value;
namespace internal
{
template<typename Unit1, typename Unit2>
struct unit_multiply_impl
{
static_assert(is_unit<Unit1>, "first type provided to unit_multiply is invalid");
static_assert(is_unit<Unit2>, "second type provided to unit_multiply is invalid");
using Dim1 = typename Unit1::dimension_type;
using Dim2 = typename Unit2::dimension_type;
using Ratio1 = typename Unit1::ratio_type;
using Ratio2 = typename Unit2::ratio_type;
using type = unit<
dimension_multiply<Dim1, Dim2>,
ratio_multiply<Ratio1, Ratio2>
>;
};
template<typename Unit1, typename Unit2>
struct unit_divide_impl
{
static_assert(is_unit<Unit1>, "first type provided to unit_divide is invalid");
static_assert(is_unit<Unit2>, "second type provided to unit_divide is invalid");
using Dim1 = typename Unit1::dimension_type;
using Dim2 = typename Unit2::dimension_type;
using Ratio1 = typename Unit1::ratio_type;
using Ratio2 = typename Unit2::ratio_type;
using type = unit<
dimension_divide<Dim1, Dim2>,
ratio_divide<Ratio1, Ratio2>
>;
};
} // namespace internal
template<typename Unit1, typename Unit2>
using unit_multiply = typename internal::unit_multiply_impl<Unit1, Unit2>::type;
template<typename Unit1, typename Unit2>
using unit_divide = typename internal::unit_divide_impl<Unit1, Unit2>::type;
namespace si
{
#define def_base_unit(unit_name, dim) \
struct unit_name : unit<dim> \
{ using base_unit_type = unit_name; }
#define def_unit_prefix(unit_name, rat) \
struct rat##unit_name : unit< \
unit_name::dimension_type, ratio_multiply<unit_name::ratio_type, rat> \
> \
{ using base_unit_type = unit_name::base_unit_type; }
// length
def_base_unit(meter, length);
def_unit_prefix(meter, nano);
def_unit_prefix(meter, micro);
def_unit_prefix(meter, milli);
def_unit_prefix(meter, centi);
def_unit_prefix(meter, deci);
def_unit_prefix(meter, kilo);
// time
def_base_unit(second, time);
def_unit_prefix(second, atto);
def_unit_prefix(second, femto);
def_unit_prefix(second, pico);
def_unit_prefix(second, nano);
def_unit_prefix(second, micro);
def_unit_prefix(second, milli);
struct minute : unit<time, make_ratio<60>> { using base_unit_type = second; };
struct hour : unit<time, make_ratio<60 * 60>> { using base_unit_type = second; };
// amount of substance
def_base_unit(mole, amount_of_substance);
// electric current
def_base_unit(amper, electric_current);
// temperature
def_base_unit(kelvin, temperature);
// luminous intensity
def_base_unit(candela, luminous_intensity);
// mass
// kilograms are the base unit, so this needs to be done manually
struct kilogram : unit<mass> { using base_unit_type = kilogram; };
struct gram : unit<mass, milli> { using base_unit_type = kilogram; };
struct milligram : unit<mass, micro> { using base_unit_type = kilogram; };
struct tonn : unit<mass, kilo> { using base_unit_type = kilogram; };
// area
def_base_unit(square_meter, area);
// volume
def_base_unit(cubic_meter, volume);
// velocity
def_base_unit(meter_per_second, velocity);
struct kilometer_per_hour : unit<
velocity,
ratio_divide<kilometer::ratio_type, hour::ratio_type>
> { using base_unit_type = meter_per_second; };
// acceleration
def_base_unit(meter_per_second_squared, acceleration);
using meter_per_second_per_second = meter_per_second_squared;
// impulse
// frequency
def_base_unit(hertz, frequency);
def_unit_prefix(hertz, kilo);
def_unit_prefix(hertz, mega);
// force
def_base_unit(newton, force);
def_unit_prefix(newton, kilo);
def_unit_prefix(newton, mega);
// pressure
def_base_unit(pascal, pressure);
def_unit_prefix(pascal, kilo);
def_unit_prefix(pascal, mega);
// work, energy, heat
def_base_unit(joule, energy);
def_unit_prefix(joule, kilo);
def_unit_prefix(joule, mega);
struct electronvolt : unit<energy, make_ratio<1602176634, 1000000000, -19>>
{ using base_unit_type = joule; };
def_unit_prefix(electronvolt, kilo);
def_unit_prefix(electronvolt, mega);
struct watthour : unit<energy, hour::ratio_type>
{ using base_unit_type = joule; };
def_unit_prefix(watthour, kilo);
// power
def_base_unit(watt, power);
def_unit_prefix(watt, kilo);
// electric charge
def_base_unit(coulomb, electric_charge);
// electric potential, electromotive force
def_base_unit(volt, electric_potential);
def_unit_prefix(volt, kilo);
// capacitance
def_base_unit(farad, capacitance);
def_unit_prefix(farad, nano);
def_unit_prefix(farad, micro);
def_unit_prefix(farad, milli);
// electric resistance
def_base_unit(ohm, electric_resistance);
def_unit_prefix(ohm, kilo);
def_unit_prefix(ohm, mega);
// electric conductance
def_base_unit(siemens, electric_conductance);
def_unit_prefix(siemens, micro);
def_unit_prefix(siemens, milli);
// magnetic flux
def_base_unit(weber, magnetic_flux);
// magnetic flux density
def_base_unit(tesla, magnetic_flux_density);
// inductance
def_base_unit(henry, inductance);
// luminous flux
def_base_unit(lumen, luminous_flux);
// illuminance
def_base_unit(lux, illuminance);
// activity
def_base_unit(becquerel, activity);
#undef def_base_unit
#undef def_unit_prefix
} // namespace si
} // namespace units
template<typename Unit, typename ValT = double>
struct quantity
{
static_assert(units::is_unit<Unit>, "unit_type is invalid for bz::quantity");
private:
using self_t = quantity<Unit, ValT>;
public:
using unit_type = Unit;
using dimension_type = typename unit_type::dimension_type;
using ratio_type = typename unit_type::ratio_type;
using base_unit_type = typename unit_type::base_unit_type;
using value_type = ValT;
private:
value_type _value;
public:
quantity(void) = default;
constexpr explicit quantity(value_type value)
: _value(value)
{}
template<
typename RhsUnit,
typename RhsValT,
typename = std::enable_if_t<units::is_same_unit<unit_type, RhsUnit>>
>
constexpr self_t &operator += (
quantity<RhsUnit, RhsValT> const &rhs
) noexcept(
noexcept(std::declval<value_type &>() += rhs._value)
)
{ this->_value += rhs._value; return *this; }
template<
typename RhsUnit,
typename RhsValT,
typename = std::enable_if_t<units::is_same_unit<unit_type, RhsUnit>>
>
constexpr self_t &operator -= (
quantity<RhsUnit, RhsValT> const &rhs
) noexcept(
noexcept(std::declval<value_type &>() -= rhs._value)
)
{ this->_value -= rhs._value; return *this; }
template<typename T>
constexpr self_t &operator *= (T const &rhs) noexcept(
noexcept(std::declval<value_type &>() *= rhs)
)
{ this->_value *= rhs; return *this; }
template<typename T>
constexpr self_t &operator /= (T const &rhs) noexcept(
noexcept(std::declval<value_type &>() /= rhs)
)
{ this->_value /= rhs; return *this; }
constexpr auto value(void) noexcept -> value_type &
{ return this->_value; }
constexpr auto value(void) const noexcept -> value_type const &
{ return this->_value; }
constexpr auto to_base_unit(void) const noexcept
-> quantity<base_unit_type, value_type>
{
using ret_t = quantity<base_unit_type, value_type>;
return ret_t{ this->_value * ratio_type::template value<ValT> };
}
};
template<typename T>
constexpr bool is_quantity = false;
template<typename Unit, typename ValT>
constexpr bool is_quantity<quantity<Unit, ValT>> = true;
template<typename UnitTo, typename Unit, typename ValT>
auto quantity_cast(quantity<Unit, ValT> q) noexcept -> quantity<UnitTo, ValT>
{
static_assert(
units::is_unit<UnitTo>,
"Invalid type for 'quantity_cast'! Type must be a unit."
);
static_assert(
std::is_same<
typename UnitTo::dimension_type,
typename Unit ::dimension_type
>::value,
"Invalid unit for 'quantity_cast'! New unit must be of the same dimension."
);
static_assert(
std::is_same<
typename UnitTo::dimension_type::standard_type,
typename Unit ::dimension_type::standard_type
>::value,
"Invalid unit for 'quantity_cast'! New unit must be of the same standard."
);
using RatioTo = typename UnitTo::ratio_type;
using Ratio = typename Unit ::ratio_type;
return q.value() * (Ratio::template value<ValT> / RatioTo::template value<ValT>);
}
template<
typename LhsUnit,
typename RhsUnit,
typename LhsValT,
typename RhsValT,
typename = std::enable_if_t<units::is_same_unit<LhsUnit, RhsUnit>>
>
constexpr auto operator + (
quantity<LhsUnit, LhsValT> lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
LhsUnit,
decltype(std::declval<LhsValT>() + std::declval<RhsValT>())
>
{
using ret_t = quantity<
LhsUnit,
decltype(std::declval<LhsValT>() + std::declval<RhsValT>())
>;
return ret_t{ lhs.value() + rhs.value() };
}
template<
typename LhsUnit,
typename LhsValT,
typename RhsValT,
typename = std::enable_if_t<
units::is_unit<LhsUnit>
&& !is_quantity<RhsValT>
&& std::is_same<
typename LhsUnit::dimension_type,
units::dimension_none<typename LhsUnit::dimension_type::standard_type>
>::value
>
>
constexpr auto operator + (
quantity<LhsUnit, LhsValT> lhs,
RhsValT rhs
) noexcept -> quantity<
LhsUnit,
decltype(std::declval<LhsValT>() + std::declval<RhsValT>())
>
{
using ret_t = quantity<
LhsUnit,
decltype(std::declval<LhsValT>() + std::declval<RhsValT>())
>;
return ret_t{ lhs.value() + rhs };
}
template<
typename RhsUnit,
typename LhsValT,
typename RhsValT,
typename = std::enable_if_t<
units::is_unit<RhsUnit>
&& !is_quantity<RhsValT>
&& std::is_same<
typename RhsUnit::dimension_type,
units::dimension_none<typename RhsUnit::dimension_type::standard_type>
>::value
>
>
constexpr auto operator + (
LhsValT lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
RhsUnit,
decltype(std::declval<LhsValT>() + std::declval<RhsValT>())
>
{
using ret_t = quantity<
RhsUnit,
decltype(std::declval<LhsValT>() + std::declval<RhsValT>())
>;
return ret_t{ lhs + rhs.value() };
}
template<
typename LhsUnit,
typename RhsUnit,
typename LhsValT,
typename RhsValT,
typename = std::enable_if_t<units::is_same_unit<LhsUnit, RhsUnit>>
>
constexpr auto operator - (
quantity<LhsUnit, LhsValT> lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
LhsUnit,
decltype(std::declval<LhsValT>() - std::declval<RhsValT>())
>
{
using ret_t = quantity<
LhsUnit,
decltype(std::declval<LhsValT>() * std::declval<RhsValT>())
>;
return ret_t{ lhs.value() - rhs.value() };
}
template<
typename LhsUnit,
typename LhsValT,
typename RhsValT,
typename = std::enable_if_t<
units::is_unit<LhsUnit>
&& !is_quantity<RhsValT>
&& std::is_same<
typename LhsUnit::dimension_type,
units::dimension_none<typename LhsUnit::dimension_type::standard_type>
>::value
>
>
constexpr auto operator - (
quantity<LhsUnit, LhsValT> lhs,
RhsValT rhs
) noexcept -> quantity<
LhsUnit,
decltype(std::declval<LhsValT>() - std::declval<RhsValT>())
>
{
using ret_t = quantity<
LhsUnit,
decltype(std::declval<LhsValT>() - std::declval<RhsValT>())
>;
return ret_t{ lhs.value() - rhs };
}
template<
typename RhsUnit,
typename LhsValT,
typename RhsValT,
typename = std::enable_if_t<
units::is_unit<RhsUnit>
&& !is_quantity<RhsValT>
&& std::is_same<
typename RhsUnit::dimension_type,
units::dimension_none<typename RhsUnit::dimension_type::standard_type>
>::value
>
>
constexpr auto operator - (
LhsValT lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
RhsUnit,
decltype(std::declval<LhsValT>() - std::declval<RhsValT>())
>
{
using ret_t = quantity<
RhsUnit,
decltype(std::declval<LhsValT>() - std::declval<RhsValT>())
>;
return ret_t{ lhs - rhs.value() };
}
template<
typename LhsUnit,
typename RhsUnit,
typename LhsValT,
typename RhsValT
>
constexpr auto operator * (
quantity<LhsUnit, LhsValT> lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
units::unit_multiply<LhsUnit, RhsUnit>,
decltype(std::declval<LhsValT>() * std::declval<RhsValT>())
>
{
using ret_t = quantity<
units::unit_multiply<LhsUnit, RhsUnit>,
decltype(std::declval<LhsValT>() * std::declval<RhsValT>())
>;
return ret_t{ lhs.value() * rhs.value() };
}
template<
typename LhsUnit,
typename LhsValT,
typename RhsValT
>
constexpr auto operator * (
quantity<LhsUnit, LhsValT> lhs,
RhsValT rhs
) noexcept -> quantity<
LhsUnit,
decltype(std::declval<LhsValT>() * std::declval<RhsValT>())
>
{
using ret_t = quantity<
LhsUnit,
decltype(std::declval<LhsValT>() * std::declval<RhsValT>())
>;
return ret_t{ lhs.value() * rhs };
}
template<
typename RhsUnit,
typename LhsValT,
typename RhsValT
>
constexpr auto operator * (
LhsValT lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
RhsUnit,
decltype(std::declval<LhsValT>() * std::declval<RhsValT>())
>
{
using ret_t = quantity<
RhsUnit,
decltype(std::declval<LhsValT>() * std::declval<RhsValT>())
>;
return ret_t{ lhs * rhs.value() };
}
template<
typename LhsUnit,
typename RhsUnit,
typename LhsValT,
typename RhsValT
>
constexpr auto operator / (
quantity<LhsUnit, LhsValT> lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
units::unit_divide<LhsUnit, RhsUnit>,
decltype(std::declval<LhsValT>() / std::declval<RhsValT>())
>
{
using ret_t = quantity<
units::unit_divide<LhsUnit, RhsUnit>,
decltype(std::declval<LhsValT>() / std::declval<RhsValT>())
>;
return ret_t{ lhs.value() / rhs.value() };
}
template<
typename LhsUnit,
typename LhsValT,
typename RhsValT
>
constexpr auto operator / (
quantity<LhsUnit, LhsValT> lhs,
RhsValT rhs
) noexcept -> quantity<
LhsUnit,
decltype(std::declval<LhsValT>() / std::declval<RhsValT>())
>
{
using ret_t = quantity<
LhsUnit,
decltype(std::declval<LhsValT>() / std::declval<RhsValT>())
>;
return ret_t{ lhs.value() / rhs };
}
template<
typename RhsUnit,
typename LhsValT,
typename RhsValT
>
constexpr auto operator / (
LhsValT lhs,
quantity<RhsUnit, RhsValT> rhs
) noexcept -> quantity<
units::unit_divide<
units::unit<units::dimension_none<typename RhsUnit::dimension_type::standard_type>>,
RhsUnit
>,
decltype(std::declval<LhsValT>() / std::declval<RhsValT>())
>
{
using ret_t = quantity<
units::unit_divide<
units::unit<units::dimension_none<typename RhsUnit::dimension_type::standard_type>>,
RhsUnit
>,
decltype(std::declval<LhsValT>() / std::declval<RhsValT>())
>;
return ret_t{ lhs / rhs.value() };
}
#define def_cmp_op(op) \
template< \
typename LhsUnit, \
typename RhsUnit, \
typename LhsValT, \
typename RhsValT, \
typename = std::enable_if_t< \
std::is_same< \
typename LhsUnit::dimension_type, \
typename RhsUnit::dimension_type \
>::value \
> \
> \
constexpr bool operator op ( \
quantity<LhsUnit, LhsValT> lhs, \
quantity<RhsUnit, RhsValT> rhs \
) noexcept \
{ \
using LhsDim = typename LhsUnit::dimension_type; \
using RhsDim = typename RhsUnit::dimension_type; \
static_assert( \
std::is_same<LhsDim, RhsDim>::value, \
"Cannot compare quantities of differring dimensions" \
); \
return (LhsUnit::ratio_type::template value<LhsValT> * lhs.value()) \
op (RhsUnit::ratio_type::template value<RhsValT> * rhs.value()); \
}
def_cmp_op(==)
def_cmp_op(!=)
def_cmp_op(<)
def_cmp_op(<=)
def_cmp_op(>)
def_cmp_op(>=)
#undef def_cmp_op
namespace units
{
namespace si
{
namespace unit_literals
{
#define def_unit_literal(postfix, unit) \
constexpr auto operator ""_##postfix (long double val) -> quantity<unit> \
{ return quantity<unit>{ static_cast<quantity<unit>::value_type>(val) }; } \
\
constexpr auto operator ""_##postfix (unsigned long long int val) -> quantity<unit> \
{ return quantity<unit>{ static_cast<quantity<unit>::value_type>(val) }; }
// length
def_unit_literal(nm, nanometer)
def_unit_literal(um, micrometer)
def_unit_literal(mm, millimeter)
def_unit_literal(cm, centimeter)
def_unit_literal(dm, decimeter)
def_unit_literal( m, meter)
def_unit_literal(km, kilometer)
// time
def_unit_literal(as, attosecond)
def_unit_literal(fs, femtosecond)
def_unit_literal(ps, picosecond)
def_unit_literal(ns, nanosecond)
def_unit_literal(us, microsecond)
def_unit_literal(ms, millisecond)
def_unit_literal( s, second)
def_unit_literal(min, minute)
def_unit_literal(h, hour)
// amount of substance
def_unit_literal(mol, mole)
// electric current
def_unit_literal(A, amper)
// temperature
def_unit_literal(K, kelvin)
// luminous intensity
def_unit_literal(cd, candela)
// mass
def_unit_literal(mg, milligram)
def_unit_literal( g, gram)
def_unit_literal(kg, kilogram)
def_unit_literal(t, tonn)
// area
def_unit_literal(m2, square_meter)
// volume
def_unit_literal(m3, cubic_meter)
// velocity
def_unit_literal(mps, meter_per_second)
def_unit_literal(kmph, kilometer_per_hour)
// acceleration
def_unit_literal(mps2, meter_per_second_squared)
// frequency
def_unit_literal( Hz, hertz)
def_unit_literal(kHz, kilohertz)
def_unit_literal(MHz, megahertz)
// force
def_unit_literal( N, newton)
def_unit_literal(kN, kilonewton)
def_unit_literal(MN, meganewton)
// pressure
def_unit_literal( Pa, pascal)
def_unit_literal(kPa, kilopascal)
def_unit_literal(MPa, megapascal)
// work, energy, heat
def_unit_literal( J, joule)
def_unit_literal(kJ, kilojoule)
def_unit_literal(MJ, megajoule)
def_unit_literal( eV, electronvolt)
def_unit_literal(keV, kiloelectronvolt)
def_unit_literal(MeV, megaelectronvolt)
def_unit_literal( Wh, watthour)
def_unit_literal(kWh, kilowatthour)
// power
def_unit_literal( W, watt)
def_unit_literal(kW, kilowatt)
// electric charge
def_unit_literal(C, coulomb)
// electric potential, electromotive force
def_unit_literal( V, volt)
def_unit_literal(kV, kilovolt)
// capacitance
def_unit_literal(nF, nanofarad)
def_unit_literal(uF, microfarad)
def_unit_literal(mF, millifarad)
def_unit_literal( F, farad)
// electric resistance
def_unit_literal( Ohm, ohm)
def_unit_literal(kOhm, kiloohm)
def_unit_literal(MOhm, megaohm)
// electric conductance
def_unit_literal(uS, microsiemens)
def_unit_literal(mS, millisiemens)
def_unit_literal( S, siemens)
// magnetic flux
def_unit_literal(Wb, weber)
// magnetic flux density
def_unit_literal(T, tesla)
// inductance
def_unit_literal(H, henry)
// luminous flux
def_unit_literal(lm, lumen)
// illuminance
def_unit_literal(lx, lux)
// activity
def_unit_literal(Bq, becquerel)
#undef def_unit_literal
} // namespace unit_literals
namespace constants
{
// defined constants in the SI system
// reference: https://www.nist.gov/si-redefinition/meet-constants
constexpr quantity<hertz, double>
hyperfine_transition_frequency_of_cesium{ 9192631770 };
constexpr quantity<meter_per_second, double>
speed_of_light{ 299792458 };
constexpr quantity<unit_multiply<joule, second>, double>
Planck_constant{ 6.62607015e-34 };
constexpr quantity<coulomb, double>
elementary_charge{ 1.602176634e-19 };
constexpr quantity<unit_divide<joule, kelvin>, double>
Boltzmann_constant{ 1.380649e-23 };
constexpr quantity<unit_divide<unit<dimension_none>, mole>, double>
Avogadro_constant{ 6.02214076e23 };
constexpr quantity<unit_divide<lumen, watt>, double>
luminous_efficacy{ 683 };
} // namespace constants
} // namespace si
} // namespace units
} // namespace bz
#endif // c++14
#endif // _bz_units_h__
|
Il-Capitano/bozonlib
|
bz/common.h
|
// MIT License
//
// Copyright (c) 2019 Il-Capitano
//
// 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 _bz_common_h_
#define _bz_common_h_
#if __cplusplus < 201103L
#define bz_cxx20 0
#define bz_cxx17 0
#define bz_cxx14 0
#define bz_cxx11 0
#elif __cplusplus < 201402L
#define bz_cxx20 0
#define bz_cxx17 0
#define bz_cxx14 0
#define bz_cxx11 1
#elif __cplusplus < 201703L
#define bz_cxx20 0
#define bz_cxx17 0
#define bz_cxx14 1
#define bz_cxx11 1
#else
#define bz_cxx20 0
#define bz_cxx17 1
#define bz_cxx14 1
#define bz_cxx11 1
#endif
namespace bz
{
#if bz_cxx14
template<typename T>
constexpr T pi{ 3.141592653589793238462643383279502884197169399375L };
#endif // c++14
}
#endif // _bz_common_h_
|
Il-Capitano/bozonlib
|
bz/math_helper.h
|
<gh_stars>0
#ifndef _bz_math_helper_h_
#define _bz_math_helper_h_
#include "common.h"
#if bz_cxx14
#include <cmath>
#include <utility>
namespace bz
{
namespace internal
{
#define def_op_helpers_unary(op) \
template<typename T> \
struct op##_type_impl \
{ \
template<typename U> \
static auto tester(U) -> decltype(op(std::declval<U>())); \
template<typename U> \
static auto tester(...) -> decltype(std::op(std::declval<U>())); \
using type = decltype(tester<T>(std::declval<T>())); \
}; \
template<typename T> \
struct op##_noexcept_impl \
{ \
template<typename U> \
static auto tester(U) noexcept( \
noexcept(op(std::declval<U>())) \
) -> decltype(op(std::declval<U>())); \
template<typename U> \
static auto tester(...) noexcept( \
noexcept(std::op(std::declval<U>())) \
) -> decltype(std::op(std::declval<U>())); \
static constexpr bool value = noexcept(tester<T>(std::declval<T>())); \
}; \
template<typename T> \
using op##_type = typename internal::op##_type_impl<T>::type; \
template<typename T> \
constexpr bool op##_noexcept = internal::op##_noexcept_impl<T>::value; \
template<typename T> \
constexpr auto op##_helper(T &&x) noexcept(op##_noexcept<T>) -> op##_type<T> \
{ \
using std::op; \
return op(std::forward<T>(x)); \
}
#define def_op_helpers_binary(op) \
template<typename T, typename U> \
struct op##_type_impl \
{ \
template<typename T_, typename U_> \
static auto tester(T_, U_) -> decltype(op(std::declval<T_>(), std::declval<U_>())); \
template<typename T_, typename U_> \
static auto tester(...) -> decltype(std::op(std::declval<T_>(), std::declval<U_>())); \
using type = decltype(tester<T, U>(std::declval<T>(), std::declval<U>())); \
}; \
template<typename T, typename U> \
struct op##_noexcept_impl \
{ \
template<typename T_, typename U_> \
static auto tester(T_, U_) noexcept( \
noexcept(op(std::declval<T_>(), std::declval<U_>())) \
) -> decltype(op(std::declval<T_>(), std::declval<U_>())); \
template<typename T_, typename U_> \
static auto tester(...) noexcept( \
noexcept(std::op(std::declval<T_>(), std::declval<U_>())) \
) -> decltype(std::op(std::declval<T_>(), std::declval<U_>())); \
static constexpr bool value = noexcept( \
tester<T, U>(std::declval<T>(), std::declval<U>()) \
); \
}; \
template<typename T, typename U> \
using op##_type = typename op##_type_impl<T, U>::type; \
template<typename T, typename U> \
constexpr bool op##_noexcept = op##_noexcept_impl<T, U>::value; \
template<typename T, typename U> \
constexpr auto op##_helper(T &&x, U &&y) noexcept(op##_noexcept<T, U>) -> op##_type<T, U> \
{ \
using std::op; \
return op(std::forward<T>(x), std::forward<U>(y)); \
}
def_op_helpers_unary(abs)
def_op_helpers_unary(exp)
def_op_helpers_unary(exp2)
def_op_helpers_unary(expm1)
def_op_helpers_unary(log)
def_op_helpers_unary(log10)
def_op_helpers_unary(log2)
def_op_helpers_unary(log1p)
def_op_helpers_binary(pow)
def_op_helpers_unary(sqrt)
def_op_helpers_unary(cbrt)
template<typename ...Ts>
struct hypot_type_impl
{
template<typename ...Us>
auto tester() -> decltype(hypot(std::declval<Us>()...));
template<typename ...Us>
auto tester(...) -> decltype(std::hypot(std::declval<Us>()...));
using type = decltype(
std::declval<hypot_type_impl<Ts...>>().template tester<Ts...>(std::declval<Ts>()...)
);
};
template<typename ...Ts>
struct hypot_noexcept_impl
{
template<typename ...Us>
static auto tester(Us ...) noexcept(
noexcept(hypot(std::declval<Us>()...))
) -> decltype(hypot(std::declval<Us>()...));
template<typename ...Us>
static auto tester(...) noexcept(
noexcept(std::hypot(std::declval<Us>()...))
) -> decltype(std::hypot(std::declval<Us>()...));
static constexpr bool value = noexcept(
std::declval<hypot_noexcept_impl<Ts...>>().template tester<Ts...>(std::declval<Ts>()...)
);
};
template<typename ...Ts>
using hypot_type = typename hypot_type_impl<Ts...>::type;
template<typename ...Ts>
constexpr bool hypot_noexcept = hypot_noexcept_impl<Ts...>::value;
template<typename ...Ts>
constexpr auto hypot_helper(Ts &&...xs) noexcept(hypot_noexcept<Ts...>) -> hypot_type<Ts...>
{
using std::hypot;
return hypot(std::forward<Ts>(xs)...);
}
def_op_helpers_unary(sin)
def_op_helpers_unary(cos)
def_op_helpers_unary(tan)
def_op_helpers_unary(asin)
def_op_helpers_unary(acos)
def_op_helpers_unary(atan)
def_op_helpers_binary(atan2)
def_op_helpers_unary(sinh)
def_op_helpers_unary(cosh)
def_op_helpers_unary(tanh)
def_op_helpers_unary(asinh)
def_op_helpers_unary(acosh)
def_op_helpers_unary(atanh)
def_op_helpers_unary(erf)
def_op_helpers_unary(erfc)
def_op_helpers_unary(tgamma)
def_op_helpers_unary(lgamma)
def_op_helpers_unary(ceil)
def_op_helpers_unary(floor)
def_op_helpers_unary(trunc)
def_op_helpers_unary(round)
def_op_helpers_unary(lround)
def_op_helpers_unary(llround)
def_op_helpers_unary(nearbyint)
def_op_helpers_unary(rint)
def_op_helpers_unary(lrint)
def_op_helpers_unary(llrint)
} // namespace internal
} // namespace bz
#endif // c++14
#endif // _bz_math_helper_h_
|
BiRDLab-UMinho/vrviz
|
vrviz/include/vrviz/openvr_vk.h
|
<reponame>BiRDLab-UMinho/vrviz
//========= Copyright Valve Corporation ============//
#ifndef OPENVR_VK_H
#define OPENVR_VK_H
#if defined( _WIN32 )
#define VK_USE_PLATFORM_WIN32_KHR
#else
#define SDL_VIDEO_DRIVER_X11
#define VK_USE_PLATFORM_XLIB_KHR
#endif
#include <vulkan/vulkan.h>
#include <SDL.h>
#include <SDL_syswm.h>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <inttypes.h>
#include <openvr.h>
#include <deque>
#include "shared/lodepng.h"
#include "shared/Matrices.h"
#include "shared/pathtools.h"
#if defined(POSIX)
#include "unistd.h"
#endif
#ifndef _countof
#define _countof(x) (sizeof(x)/sizeof((x)[0]))
#endif
void inline ThreadSleep( unsigned long nMilliseconds )
{
#if defined(_WIN32)
::Sleep( nMilliseconds );
#elif defined(POSIX)
usleep( nMilliseconds * 1000 );
#endif
}
// Pipeline state objects
enum PipelineStateObjectEnum_t
{
PSO_SCENE = 0,
PSO_AXES,
PSO_RENDERMODEL,
PSO_COMPANION,
PSO_COUNT
};
// Indices of descriptor sets for rendering
enum DescriptorSetIndex_t
{
DESCRIPTOR_SET_LEFT_EYE_SCENE = 0,
DESCRIPTOR_SET_RIGHT_EYE_SCENE,
DESCRIPTOR_SET_COMPANION_LEFT_TEXTURE,
DESCRIPTOR_SET_COMPANION_RIGHT_TEXTURE,
DESCRIPTOR_SET_LEFT_EYE_RENDER_MODEL0,
DESCRIPTOR_SET_LEFT_EYE_RENDER_MODEL_MAX = DESCRIPTOR_SET_LEFT_EYE_RENDER_MODEL0 + vr::k_unMaxTrackedDeviceCount,
DESCRIPTOR_SET_RIGHT_EYE_RENDER_MODEL0,
DESCRIPTOR_SET_RIGHT_EYE_RENDER_MODEL_MAX = DESCRIPTOR_SET_RIGHT_EYE_RENDER_MODEL0 + vr::k_unMaxTrackedDeviceCount,
NUM_DESCRIPTOR_SETS
};
class VulkanRenderModel
{
public:
VulkanRenderModel( const std::string & sRenderModelName );
~VulkanRenderModel();
bool BInit( VkDevice pDevice, const VkPhysicalDeviceMemoryProperties &memoryProperties, VkCommandBuffer pCommandBuffer, vr::TrackedDeviceIndex_t unTrackedDeviceIndex, VkDescriptorSet pDescriptorSets[ 2 ], const vr::RenderModel_t & vrModel, const vr::RenderModel_TextureMap_t & vrDiffuseTexture );
void Cleanup();
void Draw( vr::EVREye nEye, VkCommandBuffer pCommandBuffer, VkPipelineLayout pPipelineLayout, const Matrix4 &matMVP );
const std::string & GetName() const { return m_sModelName; }
private:
VkDevice m_pDevice;
VkPhysicalDeviceMemoryProperties m_physicalDeviceMemoryProperties;
VkBuffer m_pVertexBuffer;
VkDeviceMemory m_pVertexBufferMemory;
VkBuffer m_pIndexBuffer;
VkDeviceMemory m_pIndexBufferMemory;
VkImage m_pImage;
VkDeviceMemory m_pImageMemory;
VkImageView m_pImageView;
VkBuffer m_pImageStagingBuffer;
VkDeviceMemory m_pImageStagingBufferMemory;
VkBuffer m_pConstantBuffer[ 2 ];
VkDeviceMemory m_pConstantBufferMemory[ 2 ];
void *m_pConstantBufferData[ 2 ];
VkDescriptorSet m_pDescriptorSets[ 2 ];
VkSampler m_pSampler;
size_t m_unVertexCount;
vr::TrackedDeviceIndex_t m_unTrackedDeviceIndex;
std::string m_sModelName;
};
static bool g_bPrintf = true;
// Vulkan extension entrypoints
static PFN_vkCreateDebugReportCallbackEXT g_pVkCreateDebugReportCallbackEXT = nullptr;
static PFN_vkDestroyDebugReportCallbackEXT g_pVkDestroyDebugReportCallbackEXT = nullptr;
//-----------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
class CMainApplication
{
public:
CMainApplication( int argc, char *argv[] );
virtual ~CMainApplication();
bool BInit();
virtual bool BInitVulkan();
bool BInitVulkanInstance();
bool BInitVulkanDevice();
bool BInitVulkanSwapchain();
bool BInitCompositor();
bool GetVulkanInstanceExtensionsRequired( std::vector< std::string > &outInstanceExtensionList );
bool GetVulkanDeviceExtensionsRequired( VkPhysicalDevice pPhysicalDevice, std::vector< std::string > &outDeviceExtensionList );
void SetupRenderModels();
void Shutdown();
void RunMainLoop();
bool HandleInput();
void ProcessVREvent( const vr::VREvent_t & event );
void RenderFrame();
virtual bool SetupTexturemaps();
static void GenMipMapRGBA( const uint8_t *pSrc, uint8_t *ppDst, int nSrcWidth, int nSrcHeight, int *pDstWidthOut, int *pDstHeightOut );
void SetupScene();
void AddCubeToScene( Matrix4 mat, std::vector<float> &vertdata );
void AddCubeVertex( float fl0, float fl1, float fl2, float fl3, float fl4, std::vector<float> &vertdata );
virtual void RenderControllerAxes();
bool SetupStereoRenderTargets();
void SetupCompanionWindow();
void SetupCameras();
void RenderStereoTargets();
void RenderCompanionWindow();
void RenderScene( vr::Hmd_Eye nEye );
Matrix4 GetHMDMatrixProjectionEye( vr::Hmd_Eye nEye );
Matrix4 GetHMDMatrixPoseEye( vr::Hmd_Eye nEye );
Matrix4 GetCurrentViewProjectionMatrix( vr::Hmd_Eye nEye );
virtual void UpdateHMDMatrixPose();
Matrix4 ConvertSteamVRMatrixToMatrix4( const vr::HmdMatrix34_t &matPose );
bool CreateAllShaders();
void CreateAllDescriptorSets();
void SetupRenderModelForTrackedDevice( vr::TrackedDeviceIndex_t unTrackedDeviceIndex );
VulkanRenderModel *FindOrLoadRenderModel( vr::TrackedDeviceIndex_t unTrackedDeviceIndex, const char *pchRenderModelName );
unsigned int m_unPointSize;
std::string m_strTextPath;
std::string m_strActionManifestPath;
protected:
bool m_bDebugVulkan;
bool m_bVerbose;
bool m_bPerf;
bool m_bVblank;
int m_nMSAASampleCount;
// Optional scaling factor to render with supersampling (defaults off, use -scale)
float m_flSuperSampleScale;
vr::IVRSystem *m_pHMD;
vr::IVRRenderModels *m_pRenderModels;
std::string m_strDriver;
std::string m_strDisplay;
vr::TrackedDevicePose_t m_rTrackedDevicePose[ vr::k_unMaxTrackedDeviceCount ];
Matrix4 m_rmat4DevicePose[ vr::k_unMaxTrackedDeviceCount ];
bool m_rbShowTrackedDevice[ vr::k_unMaxTrackedDeviceCount ];
// SDL bookkeeping
SDL_Window *m_pCompanionWindow;
uint32_t m_nCompanionWindowWidth;
uint32_t m_nCompanionWindowHeight;
// Vulkan bookkeeping
int m_iTrackedControllerCount;
int m_iTrackedControllerCount_Last;
int m_iValidPoseCount;
int m_iValidPoseCount_Last;
bool m_bShowCubes;
std::string m_strPoseClasses; // what classes we saw poses for this frame
char m_rDevClassChar[ vr::k_unMaxTrackedDeviceCount ]; // for each device, a character representing its class
int m_iSceneVolumeWidth;
int m_iSceneVolumeHeight;
int m_iSceneVolumeDepth;
float m_fScaleSpacing;
float m_fScale;
int m_iSceneVolumeInit; // if you want something other than the default 20x20x20
float m_fNearClip;
float m_fFarClip;
unsigned int m_uiVertcount;
unsigned int m_uiCompanionWindowIndexSize;
VkInstance m_pInstance;
VkDevice m_pDevice;
VkPhysicalDevice m_pPhysicalDevice;
VkQueue m_pQueue;
VkSurfaceKHR m_pSurface;
VkSwapchainKHR m_pSwapchain;
VkPhysicalDeviceProperties m_physicalDeviceProperties;
VkPhysicalDeviceMemoryProperties m_physicalDeviceMemoryProperties;
VkPhysicalDeviceFeatures m_physicalDeviceFeatures;
uint32_t m_nQueueFamilyIndex;
VkDebugReportCallbackEXT m_pDebugReportCallback;
uint32_t m_nSwapQueueImageCount;
uint32_t m_nFrameIndex;
uint32_t m_nCurrentSwapchainImage;
std::vector< VkImage > m_swapchainImages;
std::vector< VkImageView > m_pSwapchainImageViews;
std::vector< VkFramebuffer > m_pSwapchainFramebuffers;
std::vector< VkSemaphore > m_pSwapchainSemaphores;
VkRenderPass m_pSwapchainRenderPass;
VkCommandPool m_pCommandPool;
VkDescriptorPool m_pDescriptorPool;
VkDescriptorSet m_pDescriptorSets[ NUM_DESCRIPTOR_SETS ];
struct VulkanCommandBuffer_t
{
VkCommandBuffer m_pCommandBuffer;
VkFence m_pFence;
};
std::deque< VulkanCommandBuffer_t > m_commandBuffers;
VulkanCommandBuffer_t m_currentCommandBuffer;
VulkanCommandBuffer_t GetCommandBuffer();
// Scene resources
VkBuffer m_pSceneVertexBuffer;
VkDeviceMemory m_pSceneVertexBufferMemory;
VkBufferView m_pSceneVertexBufferView;
VkBuffer m_pSceneConstantBuffer[ 2 ];
VkDeviceMemory m_pSceneConstantBufferMemory[ 2 ];
void *m_pSceneConstantBufferData[ 2 ];
VkImage m_pSceneImage;
VkDeviceMemory m_pSceneImageMemory;
VkImageView m_pSceneImageView;
VkBuffer m_pSceneStagingBuffer;
VkDeviceMemory m_pSceneStagingBufferMemory;
VkSampler m_pSceneSampler;
// Storage for VS and PS for each PSO
VkShaderModule m_pShaderModules[ PSO_COUNT * 2 ];
VkPipeline m_pPipelines[ PSO_COUNT ];
VkDescriptorSetLayout m_pDescriptorSetLayout;
VkPipelineLayout m_pPipelineLayout;
VkPipelineCache m_pPipelineCache;
// Companion window resources
VkBuffer m_pCompanionWindowVertexBuffer;
VkDeviceMemory m_pCompanionWindowVertexBufferMemory;
VkBuffer m_pCompanionWindowIndexBuffer;
VkDeviceMemory m_pCompanionWindowIndexBufferMemory;
// Controller axes resources
VkBuffer m_pControllerAxesVertexBuffer;
VkDeviceMemory m_pControllerAxesVertexBufferMemory;
unsigned int m_uiControllerVertcount;
Matrix4 m_mat4HMDPose;
Matrix4 m_mat4eyePosLeft;
Matrix4 m_mat4eyePosRight;
Matrix4 m_mat4ProjectionCenter;
Matrix4 m_mat4ProjectionLeft;
Matrix4 m_mat4ProjectionRight;
struct VertexDataScene
{
Vector3 position;
Vector2 texCoord;
};
struct VertexDataWindow
{
Vector2 position;
Vector2 texCoord;
VertexDataWindow( const Vector2 & pos, const Vector2 tex ) : position(pos), texCoord(tex) { }
};
struct FramebufferDesc
{
VkImage m_pImage;
VkImageLayout m_nImageLayout;
VkDeviceMemory m_pDeviceMemory;
VkImageView m_pImageView;
VkImage m_pDepthStencilImage;
VkImageLayout m_nDepthStencilImageLayout;
VkDeviceMemory m_pDepthStencilDeviceMemory;
VkImageView m_pDepthStencilImageView;
VkRenderPass m_pRenderPass;
VkFramebuffer m_pFramebuffer;
};
FramebufferDesc m_leftEyeDesc;
FramebufferDesc m_rightEyeDesc;
bool CreateFrameBuffer( int nWidth, int nHeight, FramebufferDesc &framebufferDesc );
uint32_t m_nRenderWidth;
uint32_t m_nRenderHeight;
std::vector< VulkanRenderModel * > m_vecRenderModels;
VulkanRenderModel *m_rTrackedDeviceToRenderModel[ vr::k_unMaxTrackedDeviceCount ];
};
//-----------------------------------------------------------------------------
// Purpose: Outputs a set of optional arguments to debugging output, using
// the printf format setting specified in fmt*.
//-----------------------------------------------------------------------------
void inline dprintf( const char *fmt, ... )
{
va_list args;
char buffer[ 2048 ];
va_start( args, fmt );
vsprintf_s( buffer, fmt, args );
va_end( args );
if ( g_bPrintf )
printf( "%s", buffer );
OutputDebugStringA( buffer );
}
//-----------------------------------------------------------------------------
// Purpose: VK_EXT_debug_report callback
//-----------------------------------------------------------------------------
static VkBool32 VKAPI_PTR inline VKDebugMessageCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object,
size_t location, int32_t messageCode, const char* pLayerPrefix, const char *pMessage, void *pUserData )
{
char buf[4096] = { 0 };
switch ( flags )
{
case VK_DEBUG_REPORT_ERROR_BIT_EXT:
sprintf( buf, "VK ERROR %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_WARNING_BIT_EXT:
sprintf( buf, "VK WARNING %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT:
sprintf( buf, "VK PERF %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_INFORMATION_BIT_EXT:
sprintf( buf, "VK INFO %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
case VK_DEBUG_REPORT_DEBUG_BIT_EXT:
sprintf( buf, "VK DEBUG %s %" PRIu64 ":%d: %s\n", pLayerPrefix, uint64_t( location ), messageCode, pMessage );
break;
default:
break;
}
dprintf( "%s\n", buf );
return VK_FALSE;
}
//-----------------------------------------------------------------------------
// Purpose: Determine the memory type index from the memory requirements
// and type bits
//-----------------------------------------------------------------------------
static bool inline MemoryTypeFromProperties( const VkPhysicalDeviceMemoryProperties &memoryProperties, uint32_t nMemoryTypeBits, VkMemoryPropertyFlags nMemoryProperties, uint32_t *pTypeIndexOut )
{
for ( uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++ )
{
if ( ( nMemoryTypeBits & 1 ) == 1)
{
// Type is available, does it match user properties?
if ( ( memoryProperties.memoryTypes[i].propertyFlags & nMemoryProperties ) == nMemoryProperties )
{
*pTypeIndexOut = i;
return true;
}
}
nMemoryTypeBits >>= 1;
}
// No memory types matched, return failure
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Helper function to create Vulkan static VB/IBs
//-----------------------------------------------------------------------------
static bool inline CreateVulkanBuffer( VkDevice pDevice, const VkPhysicalDeviceMemoryProperties &memoryProperties, const void *pBufferData, VkDeviceSize nSize, VkBufferUsageFlags nUsage, VkBuffer *ppBufferOut, VkDeviceMemory *ppDeviceMemoryOut )
{
// Create the vertex buffer and fill with data
VkBufferCreateInfo bufferCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferCreateInfo.size = nSize;
bufferCreateInfo.usage = nUsage;
VkResult nResult = vkCreateBuffer( pDevice, &bufferCreateInfo, nullptr, ppBufferOut );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s - vkCreateBuffer failed with error %d\n", __FUNCTION__, nResult );
return false;
}
VkMemoryRequirements memoryRequirements = {};
vkGetBufferMemoryRequirements( pDevice, *ppBufferOut, &memoryRequirements );
VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
if ( !MemoryTypeFromProperties( memoryProperties, memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &allocInfo.memoryTypeIndex ) )
{
dprintf( "%s - failed to find matching memoryTypeIndex for buffer\n", __FUNCTION__ );
return false;
}
allocInfo.allocationSize = memoryRequirements.size;
nResult = vkAllocateMemory( pDevice, &allocInfo, nullptr, ppDeviceMemoryOut );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s - vkCreateBuffer failed with error %d\n", __FUNCTION__, nResult );
return false;
}
nResult = vkBindBufferMemory( pDevice, *ppBufferOut, *ppDeviceMemoryOut, 0 );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s vkBindBufferMemory failed with error %d\n", __FUNCTION__, nResult );
return false;
}
if ( pBufferData != nullptr )
{
void *pData;
nResult = vkMapMemory( pDevice, *ppDeviceMemoryOut, 0, VK_WHOLE_SIZE, 0, &pData );
if ( nResult != VK_SUCCESS )
{
dprintf( "%s - vkMapMemory returned error %d\n", __FUNCTION__, nResult );
return false;
}
memcpy( pData, pBufferData, nSize );
vkUnmapMemory( pDevice, *ppDeviceMemoryOut );
VkMappedMemoryRange memoryRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE };
memoryRange.memory = *ppDeviceMemoryOut;
memoryRange.size = VK_WHOLE_SIZE;
vkFlushMappedMemoryRanges( pDevice, 1, &memoryRange );
}
return true;
}
#endif //OPENVR_VK_H
|
BiRDLab-UMinho/vrviz
|
vrviz/src/mesh.h
|
<filename>vrviz/src/mesh.h
/*
Copyright 2011 <NAME>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MESH_H
#define MESH_H
#include <map>
#include <vector>
#include <GL/glew.h>
#include <assimp/Importer.hpp> // C++ importer interface
#include <assimp/scene.h> // Output data structure
#include <assimp/postprocess.h> // Post processing flags
#include "shared/Matrices.h"
#include "texture.h"
#include "openvr.h"
#include "visualization_msgs/Marker.h"
#define SAFE_DELETE(p) if (p) { delete p; p = NULL; }
#define ASSIMP_LOAD_FLAGS (aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_JoinIdenticalVertices | aiProcess_PreTransformVertices)
#define INVALID_OGL_VALUE 0xffffffff
namespace vr
{
/** A single vertex in a render model */
struct RenderModel_Vertex_t_rgb
{
HmdVector3_t vPosition; // position in meters in device space
HmdVector3_t vNormal;
HmdVector3_t vColor;
};
}
struct Vertex
{
Vector3 m_pos;
Vector2 m_tex;
Vector3 m_normal;
Vertex() {}
Vertex(const Vector3& pos, const Vector2& tex, const Vector3& normal)
{
m_pos = pos;
m_tex = tex;
m_normal = normal;
}
};
class Mesh
{
public:
Mesh();
~Mesh();
bool LoadMesh(const std::string& Filename);
void InitMarker(float scaling_factor=1.0);
Matrix4 quat2mat(geometry_msgs::Quaternion quat);
void Render();
std::string name;
int id;
std::string frame_id;
bool has_texture;
bool initialized;
bool needs_update;
bool load_mesh;
std::string filename;
visualization_msgs::Marker marker;
std::string fallback_texture_filename;
Vector3 scale;
Matrix4 trans;
bool Z_UP;
private:
geometry_msgs::Quaternion quatPoint2Point(Vector4 p1, Vector4 p2, float distance);
bool InitFromScene(const aiScene* pScene, const std::string& Filename);
Vector4 sphere2cart(float azimuth, float elevation, float radius);
void AddColorVertex(Vector4 pt,Vector4 normal,Vector3 color, std::vector<vr::RenderModel_Vertex_t_rgb> &Vertices, std::vector<u_int32_t> &Indices);
void AddColorTri(Vector4 pt1, Vector4 pt2, Vector4 pt3, Vector3 color, std::vector<vr::RenderModel_Vertex_t_rgb> &Vertices, std::vector<u_int32_t> &Indices);
void InitCube(std::vector<vr::RenderModel_Vertex_t_rgb> &Vertices, std::vector<u_int32_t> &Indices, Vector3 radius, Vector3 color, Matrix4 mat );
void InitSphere(std::vector<vr::RenderModel_Vertex_t_rgb> &Vertices, std::vector<u_int32_t> &Indices, float radius, Vector3 color, Vector4 center, int num_lat=8, int num_lon=0 );
void InitArrow( std::vector<vr::RenderModel_Vertex_t_rgb> &Vertices, std::vector<u_int32_t> &Indices, Matrix4 mat, float radius_y,float radius_z, float length, Vector3 color, int num_facets=16 );
void InitCylinder( std::vector<vr::RenderModel_Vertex_t_rgb> &Vertices, std::vector<u_int32_t> &Indices, Matrix4 mat, float radius, float length, Vector3 color, int num_facets=16 );
void InitTriangles(std::vector<vr::RenderModel_Vertex_t_rgb> &Vertices, std::vector<u_int32_t> &Indices,Matrix4 mat,Vector3 radius, std::vector<geometry_msgs::Point> &points,std::vector<std_msgs::ColorRGBA> &colors, Vector3 default_color);
void InitMesh(unsigned int Index, const aiMesh* paiMesh, const aiNode* node);
bool InitMaterials(const aiScene* pScene, const std::string& Filename);
void Clear();
#define INVALID_MATERIAL 0xFFFFFFFF
#define NO_TEXTURE 0xFFFFFFFE
public:
struct MeshEntry {
MeshEntry();
~MeshEntry();
void Init(const std::vector<vr::RenderModel_Vertex_t>& Vertices,
const std::vector<u_int32_t>& Indices);
void Init(const std::vector<vr::RenderModel_Vertex_t_rgb>& Vertices,
const std::vector<u_int32_t>& Indices);
GLuint VB;
GLuint VA;
GLuint IB;
unsigned int NumIndices;
unsigned int MaterialIndex;
};
std::vector<MeshEntry> m_Entries;
std::vector<Texture*> m_Textures;
std::vector<aiColor4D> m_Colors;
};
#endif /* MESH_H */
|
BiRDLab-UMinho/vrviz
|
vrviz/include/vrviz/openvr_gl.h
|
//========= Copyright Valve Corporation ============//
#ifndef OPENVR_GL_H
#define OPENVR_GL_H
#include <SDL.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
#if defined( OSX )
#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>
#include <OpenGL/glu.h>
// Apple's version of glut.h #undef's APIENTRY, redefine it
#define APIENTRY
#else
#include <GL/glu.h>
#endif
#include <stdio.h>
#include <string>
#include <cstdlib>
#include "mesh.h"
#include <openvr.h>
#include "shared/lodepng.h"
#include "shared/Matrices.h"
#include "shared/pathtools.h"
#if defined(POSIX)
#include "unistd.h"
#endif
#ifndef _WIN32
#define APIENTRY
#endif
#ifndef _countof
#define _countof(x) (sizeof(x)/sizeof((x)[0]))
#endif
void inline ThreadSleep( unsigned long nMilliseconds )
{
#if defined(_WIN32)
::Sleep( nMilliseconds );
#elif defined(POSIX)
usleep( nMilliseconds * 1000 );
#endif
}
class CGLRenderModel
{
public:
CGLRenderModel( const std::string & sRenderModelName );
~CGLRenderModel();
bool BInit( const vr::RenderModel_t & vrModel, const vr::RenderModel_TextureMap_t & vrDiffuseTexture );
void Cleanup();
void Draw();
const std::string & GetName() const { return m_sModelName; }
private:
GLuint m_glVertBuffer;
GLuint m_glIndexBuffer;
GLuint m_glVertArray;
GLuint m_glTexture;
GLsizei m_unVertexCount;
std::string m_sModelName;
};
static bool g_bPrintf = true;
//-----------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
class CMainApplication
{
public:
CMainApplication( int argc, char *argv[] );
virtual ~CMainApplication();
bool BInit();
virtual bool BInitGL();
bool BInitCompositor();
void SetupRenderModels();
void Shutdown();
void RunMainLoop();
bool HandleInput();
void ProcessVREvent( const vr::VREvent_t & event );
void RenderFrame();
virtual bool SetupTexturemaps();
void SetupScene();
void AddCubeToScene( Matrix4 mat, std::vector<float> &vertdata );
void AddCubeVertex( float fl0, float fl1, float fl2, float fl3, float fl4, std::vector<float> &vertdata );
virtual void RenderControllerAxes();
bool SetupStereoRenderTargets();
void SetupCompanionWindow();
void SetupCameras();
void RenderStereoTargets();
void RenderCompanionWindow();
void RenderScene( vr::Hmd_Eye nEye );
Matrix4 GetHMDMatrixProjectionEye( vr::Hmd_Eye nEye );
Matrix4 GetHMDMatrixPoseEye( vr::Hmd_Eye nEye );
virtual Matrix4 GetRobotMatrixPose( std::string frame_name );
Matrix4 GetCurrentViewProjectionMatrix( vr::Hmd_Eye nEye );
virtual void UpdateHMDMatrixPose();
Matrix4 ConvertSteamVRMatrixToMatrix4( const vr::HmdMatrix34_t &matPose );
GLuint CompileGLShader( const char *pchShaderName, const char *pchVertexShader, const char *pchFragmentShader );
bool CreateAllShaders();
void SetupRenderModelForTrackedDevice( vr::TrackedDeviceIndex_t unTrackedDeviceIndex );
CGLRenderModel *FindOrLoadRenderModel( const char *pchRenderModelName );
unsigned int m_unPointSize;
std::string m_strTextPath;
std::string m_strActionManifestPath;
std::vector<Mesh*> robot_meshes;
std::string m_strPointCloudFrame;
protected:
bool m_bDebugOpenGL;
bool m_bVerbose;
bool m_bPerf;
bool m_bVblank;
bool m_bGlFinishHack;
vr::IVRSystem *m_pHMD;
std::string m_strDriver;
std::string m_strDisplay;
vr::TrackedDevicePose_t m_rTrackedDevicePose[ vr::k_unMaxTrackedDeviceCount ];
Matrix4 m_rmat4DevicePose[ vr::k_unMaxTrackedDeviceCount ];
struct ControllerInfo_t
{
vr::VRInputValueHandle_t m_source = vr::k_ulInvalidInputValueHandle;
vr::VRActionHandle_t m_actionPose = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t m_actionHaptic = vr::k_ulInvalidActionHandle;
Matrix4 m_rmat4Pose;
CGLRenderModel *m_pRenderModel = nullptr;
std::string m_sRenderModelName;
bool m_bShowController;
};
enum EHand
{
Left = 0,
Right = 1,
};
ControllerInfo_t m_rHand[2];
// SDL bookkeeping
SDL_Window *m_pCompanionWindow;
uint32_t m_nCompanionWindowWidth;
uint32_t m_nCompanionWindowHeight;
SDL_GLContext m_pContext;
// OpenGL bookkeeping
int m_iTrackedControllerCount;
int m_iTrackedControllerCount_Last;
int m_iValidPoseCount;
int m_iValidPoseCount_Last;
bool m_bShowCubes;
bool m_bShowControllers;
Vector2 m_vAnalogValue;
std::string m_strPoseClasses; // what classes we saw poses for this frame
char m_rDevClassChar[ vr::k_unMaxTrackedDeviceCount ]; // for each device, a character representing its class
int m_iSceneVolumeWidth;
int m_iSceneVolumeHeight;
int m_iSceneVolumeDepth;
float m_fScaleSpacing;
float m_fScale;
int m_iSceneVolumeInit; // if you want something other than the default 20x20x20
float m_fNearClip;
float m_fFarClip;
GLuint m_iTexture;
unsigned int m_uiVertcount;
GLuint m_glSceneVertBuffer;
GLuint m_unSceneVAO;
GLuint m_unCompanionWindowVAO;
GLuint m_glCompanionWindowIDVertBuffer;
GLuint m_glCompanionWindowIDIndexBuffer;
unsigned int m_uiCompanionWindowIndexSize;
GLuint m_glControllerVertBuffer;
GLuint m_unControllerVAO;
unsigned int m_uiControllerVertcount;
GLuint m_glPointCloudVertBuffer;
GLuint m_unPointCloudVAO;
unsigned int m_uiPointCloudVertcount;
GLuint m_glColorTrisVertBuffer;
GLuint m_unColorTrisVAO;
unsigned int m_uiColorTrisVertcount;
Matrix4 m_mat4HMDPose;
Matrix4 m_mat4eyePosLeft;
Matrix4 m_mat4eyePosRight;
vr::HmdMatrix34_t OverlayTransform;
Matrix4 m_mat4ProjectionCenter;
Matrix4 m_mat4ProjectionLeft;
Matrix4 m_mat4ProjectionRight;
struct VertexDataScene
{
Vector3 position;
Vector2 texCoord;
};
struct VertexDataWindow
{
Vector2 position;
Vector2 texCoord;
VertexDataWindow( const Vector2 & pos, const Vector2 tex ) : position(pos), texCoord(tex) { }
};
GLuint m_unSceneProgramID;
GLuint m_unCompanionWindowProgramID;
GLuint m_unControllerTransformProgramID;
GLuint m_unRenderModelProgramID;
GLuint m_unLitRGBModelProgramID;
GLuint m_unLitModelProgramID;
GLint m_nSceneMatrixLocation;
GLint m_nControllerMatrixLocation;
GLint m_nRenderModelMatrixLocation;
GLint m_nLitRGBModelMatrixLocation;
GLint m_nLitModelMatrixLocation;
GLuint m_WVPRGBLocation;
GLuint m_WorldMatrixRGBLocation;
GLuint m_colorTextureRGBLocation;
GLuint m_eyeWorldPosRGBLocation;
GLuint m_matSpecularIntensityRGBLocation;
GLuint m_matSpecularPowerRGBLocation;
GLuint m_numPointLightsRGBLocation;
GLuint m_numSpotLightsRGBLocation;
GLuint m_WVPLocation;
GLuint m_WorldMatrixLocation;
GLuint m_colorTextureLocation;
GLuint m_eyeWorldPosLocation;
GLuint m_matSpecularIntensityLocation;
GLuint m_matSpecularPowerLocation;
GLuint m_numPointLightsLocation;
GLuint m_numSpotLightsLocation;
struct {
GLuint Color;
GLuint AmbientIntensity;
GLuint DiffuseIntensity;
GLuint Direction;
} m_dirLightLocation,m_dirLightRGBLocation;
struct {
GLuint Color;
GLuint AmbientIntensity;
GLuint DiffuseIntensity;
GLuint Position;
struct {
GLuint Constant;
GLuint Linear;
GLuint Exp;
} Atten;
} m_pointLightsLocation[2];
struct {
GLuint Color;
GLuint AmbientIntensity;
GLuint DiffuseIntensity;
GLuint Position;
GLuint Direction;
GLuint Cutoff;
struct {
GLuint Constant;
GLuint Linear;
GLuint Exp;
} Atten;
} m_spotLightsLocation[2];
struct FramebufferDesc
{
GLuint m_nDepthBufferId;
GLuint m_nRenderTextureId;
GLuint m_nRenderFramebufferId;
GLuint m_nResolveTextureId;
GLuint m_nResolveFramebufferId;
};
FramebufferDesc leftEyeDesc;
FramebufferDesc rightEyeDesc;
vr::VROverlayHandle_t m_ulOverlayHandle;
bool CreateFrameBuffer( int nWidth, int nHeight, FramebufferDesc &framebufferDesc );
uint32_t m_nRenderWidth;
uint32_t m_nRenderHeight;
std::vector< CGLRenderModel * > m_vecRenderModels;
vr::VRActionHandle_t m_actionMoveWorld = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t m_actionTwistCommand = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t m_actionResetGame = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t m_actionTriggerHaptic = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t m_actionAnalongInput = vr::k_ulInvalidActionHandle;
vr::VRActionSetHandle_t m_actionsetVrviz = vr::k_ulInvalidActionSetHandle;
};
//---------------------------------------------------------------------------------------------------------------------
// Purpose: Returns true if the action is active and had a rising edge
//---------------------------------------------------------------------------------------------------------------------
bool inline GetDigitalActionRisingEdge(vr::VRActionHandle_t action, vr::VRInputValueHandle_t *pDevicePath = nullptr )
{
vr::InputDigitalActionData_t actionData;
vr::VRInput()->GetDigitalActionData(action, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle );
if (pDevicePath)
{
*pDevicePath = vr::k_ulInvalidInputValueHandle;
if (actionData.bActive)
{
vr::InputOriginInfo_t originInfo;
if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo(actionData.activeOrigin, &originInfo, sizeof(originInfo)))
{
*pDevicePath = originInfo.devicePath;
}
}
}
return actionData.bActive && actionData.bChanged && actionData.bState;
}
//---------------------------------------------------------------------------------------------------------------------
// Purpose: Returns true if the action is active and had a falling edge
//---------------------------------------------------------------------------------------------------------------------
bool inline GetDigitalActionFallingEdge(vr::VRActionHandle_t action, vr::VRInputValueHandle_t *pDevicePath = nullptr )
{
vr::InputDigitalActionData_t actionData;
vr::VRInput()->GetDigitalActionData(action, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle );
if (pDevicePath)
{
*pDevicePath = vr::k_ulInvalidInputValueHandle;
if (actionData.bActive)
{
vr::InputOriginInfo_t originInfo;
if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo(actionData.activeOrigin, &originInfo, sizeof(originInfo)))
{
*pDevicePath = originInfo.devicePath;
}
}
}
return actionData.bActive && actionData.bChanged && !actionData.bState;
}
//---------------------------------------------------------------------------------------------------------------------
// Purpose: Returns true if the action is active and its state is true
//---------------------------------------------------------------------------------------------------------------------
bool inline GetDigitalActionState(vr::VRActionHandle_t action, vr::VRInputValueHandle_t *pDevicePath = nullptr )
{
vr::InputDigitalActionData_t actionData;
vr::VRInput()->GetDigitalActionData(action, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle );
if (pDevicePath)
{
*pDevicePath = vr::k_ulInvalidInputValueHandle;
if (actionData.bActive)
{
vr::InputOriginInfo_t originInfo;
if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo(actionData.activeOrigin, &originInfo, sizeof(originInfo)))
{
*pDevicePath = originInfo.devicePath;
}
}
}
return actionData.bActive && actionData.bState;
}
//-----------------------------------------------------------------------------
// Purpose: Outputs a set of optional arguments to debugging output, using
// the printf format setting specified in fmt*.
//-----------------------------------------------------------------------------
void inline dprintf( const char *fmt, ... )
{
va_list args;
char buffer[ 2048 ];
va_start( args, fmt );
vsprintf_s( buffer, fmt, args );
va_end( args );
if ( g_bPrintf )
printf( "%s", buffer );
OutputDebugStringA( buffer );
}
#endif // OPENVR_GL_H
|
task123/AutoTTApp
|
autoTT/raspberryCar/ModesInfoViewController.h
|
<gh_stars>0
//
// ModesInfoViewController.h
// raspberryCar
//
// Created by <NAME> on 29.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
@interface ModesInfoViewController : UIViewController
@property TCPConnection* tcpConnection;
@property (strong, nonatomic) IBOutlet UITextView *info;
@property NSInteger chosenInfo;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/StatusTableViewController.h
|
<gh_stars>0
//
// StatusTableViewController.h
// raspberryCar
//
// Created by <NAME> on 18.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
@interface StatusTableViewController : UITableViewController
@property TCPConnection* tcpConnection;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/TCPConnection.h
|
<reponame>task123/AutoTTApp<gh_stars>0
//
// TCPConnection.h
// raspberryCar
//
// Created by <NAME> on 18.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
// Class for making a tcp connection and sending and receiving messages
@interface TCPConnection : NSObject <NSStreamDelegate>
// TCPConnection sends out NSNotifications with the following names:
// @"tcpConnected", @"tcpError", @"tcpEnded" and @"tcpReceived'X'"
// where 'X' is the type of message specified in the received message as @"'X'#$#theActualMessage"
// if the received message does not contain '#$#' then 'X' is empty
// anything after '%^%' in a message is removed
//
// '%^%' is added to all sendt messages
@property (strong, nonatomic) NSString* errorMessage;
@property (strong, nonatomic) NSAttributedString* messageLog;
@property (strong, nonatomic) NSString* messageReceived;
-(void)connectToIPAddress:(NSString*)ipAddress andPort:(NSString*)
port;
- (void)sendMessage:(NSString*)message;
- (void)closeConnection;
// restrict the messages in messageLog to only be of type 'X' (@"'X'#$#theActualMessage")
- (void)setMessageLogTypeRestriction:(NSString*)X;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/SetStreamSourceViewController.h
|
//
// SetStreamSourceViewController.h
// raspberryCar
//
// Created by <NAME> on 28.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MainViewController.h"
@interface SetStreamSourceViewController : UIViewController <UITextFieldDelegate>
@property MainViewController* mainViewController;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/AppDelegate.h
|
<reponame>task123/AutoTTApp
//
// AppDelegate.h
// raspberryCar
//
// Created by <NAME> on 15.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/ConnectionViewController.h
|
//
// ViewController.h
// raspberryCar
//
// Created by <NAME> on 15.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
@interface ConnectionViewController : UIViewController <UITextFieldDelegate>
@property (strong, nonatomic) TCPConnection* tcpConnection;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/GyroscopeData.h
|
<reponame>task123/AutoTTApp
//
// GyroscopeData.h
// raspberryCar
//
// Created by <NAME> on 26.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreMotion/CoreMotion.h>
@protocol gyroscopeDataDelegate
- (void)updateOfGyroscopeDataWithRoll:(double)roll Pitch: (double)pitch Yaw: (double)yaw;
@optional
@end
@interface GyroscopeData : NSObject
@property id <gyroscopeDataDelegate> delegate;
@property double sensitivity;
@property BOOL offset;
@property (strong, nonatomic) CMAttitude* offsetAttitude;
- (void)startGyroscopeDataWithIntervall:(double)seconds;
- (void)stopGyroscopteData;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/SendMessageViewController.h
|
<reponame>task123/AutoTTApp<gh_stars>0
//
// SendMessageViewController.h
// raspberryCar
//
// Created by <NAME> on 19.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
@interface SendMessageViewController : UIViewController <UITextFieldDelegate>
@property (weak, nonatomic) TCPConnection* tcpConnection;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/ModesTableViewController.h
|
<reponame>task123/AutoTTApp<gh_stars>0
//
// ModesTableViewController.h
// raspberryCar
//
// Created by <NAME> on 17.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
#import "MainViewController.h"
@interface ModesTableViewController : UITableViewController
@property TCPConnection* tcpConnection;
@property MainViewController* mainViewController;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/VoiceRecognition.h
|
//
// VoiceRecognition.h
// AutoTT
//
// Created by <NAME> on 17.04.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "TCPConnection.h"
#import </Users/hakonaustlidtasken/Documents/6. Semester/Instrumentering/tt/paulOpenEars/OpenEarsDistribution/OpenEars/Classes/include/OEEventsObserver.h>
@interface VoiceRecognition : NSObject <OEEventsObserverDelegate>
@property (strong, nonatomic) OEEventsObserver *openEarsEventsObserver;
@property TCPConnection* tcpConnection;
- (void) startVoiceRecognition:(TCPConnection*)tcpConnection;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/MainViewController.h
|
//
// MainViewController.h
// raspberryCar
//
// Created by <NAME> on 17.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
#import "GyroscopeData.h"
@interface MainViewController : UIViewController <gyroscopeDataDelegate>
@property (weak, nonatomic) TCPConnection* tcpConnection;
@property (strong, nonatomic) GyroscopeData* gyroscopeData;
@property (strong, nonatomic) NSTimer* connectionTestTimer;
@property (strong, nonatomic) NSString* streamSourceURL;
@property BOOL videoStreamOn;
@property (strong, nonatomic) IBOutlet UINavigationItem *mode;
@property (strong, nonatomic) NSArray* modesArray;
@property (strong, nonatomic) NSArray* modesInfoArray;
- (void)startVideoStream;
- (void)stopVideoStream;
- (void)stopGyroAndRemoveObservers;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/MenuTableViewController.h
|
//
// MenuTableViewController.h
// raspberryCar
//
// Created by <NAME> on 17.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
#import "MainViewController.h"
@interface MenuTableViewController : UITableViewController
@property (weak, nonatomic) TCPConnection* tcpConnection;
@property (weak, nonatomic) MainViewController* mainViewController;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/PopUpMessageViewController.h
|
<reponame>task123/AutoTTApp
//
// PopUpMessageViewController.h
// raspberryCar
//
// Created by <NAME> on 24.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
@interface PopUpMessageViewController : UIViewController
@property TCPConnection* tcpConnection;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/CouldNotConnectViewController.h
|
//
// CouldNotConnectViewController.h
// raspberryCar
//
// Created by <NAME> on 22.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TCPConnection.h"
@interface CouldNotConnectViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *errorMessage;
@property (weak, nonatomic) TCPConnection* tcpConnection;
@end
|
task123/AutoTTApp
|
autoTT/raspberryCar/SendMessage.h
|
<reponame>task123/AutoTTApp<filename>autoTT/raspberryCar/SendMessage.h
//
// SendMessage.h
// raspberryCar
//
// Created by <NAME> on 18.02.2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SendMessage : UITableViewController
@end
|
clickteam-plugin/ASCII
|
src/Common.h
|
/*
* Copyright 2009-2013 <NAME>
* http://www.magicspark.org/ or http://oulydev.free.fr/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __MMF2EXT_ASCII_COMMON_H__
#define __MMF2EXT_ASCII_COMMON_H__
#if defined(_DEBUG) && defined(WIN32)
#define _CRTDBG_MAP_ALLOC 1
#endif
#define IN_EXT_VERSION2
#define COXSDK
// ----------------------------------------------
// VERSION AND BUILD YOUR EXTENSION CAN WORK WITH
// ----------------------------------------------
//#define TGFEXT // TGF, MMF Standard and MMF Pro
#define MMFEXT // MMF Standard and MMF Pro
//#define PROEXT // MMF Pro only
// Build number of the minimum required version of MMF
#define MINBUILD 246
// General includes
#include "ccxhdr.h"
#include "Surface.h"
// Specific to this cox
#include "resource.h"
#include "main.h"
// Globals and Prototypes
extern HINSTANCE hInstLib;
extern short conditionsInfos[];
#define actionsInfos conditionsInfos
/*extern short actionsInfos[];*/
extern short expressionsInfos[];
long (WINAPI * ConditionJumps[])(LPRDATA rdPtr, long param1, long param2);
short (WINAPI * ActionJumps[])(LPRDATA rdPtr, long param1, long param2);
long (WINAPI * ExpressionJumps[])(LPRDATA rdPtr, long param);
// Used to ensure the MMF version is 1.5, you can safely ignore this
#if defined(MMFEXT)
#define IS_COMPATIBLE(v) (v->mvGetVersion != NULL && (v->mvGetVersion() & MMFBUILD_MASK) >= MINBUILD && (v->mvGetVersion() & MMFVERSION_MASK) >= MMFVERSION_20 && ((v->mvGetVersion() & MMFVERFLAG_MASK) & MMFVERFLAG_HOME) == 0)
#elif defined(PROEXT)
#define IS_COMPATIBLE(v) (v->mvGetVersion != NULL && (v->mvGetVersion() & MMFBUILD_MASK) >= MINBUILD && (v->mvGetVersion() & MMFVERSION_MASK) >= MMFVERSION_20 && ((v->mvGetVersion() & MMFVERFLAG_MASK) & MMFVERFLAG_PRO) != 0)
#else
#define IS_COMPATIBLE(v) (v->mvGetVersion != NULL && (v->mvGetVersion() & MMFBUILD_MASK) >= MINBUILD && (v->mvGetVersion() & MMFVERSION_MASK) >= MMFVERSION_20)
#endif
#endif /* __MMF2EXT_ASCII_COMMON_H__ */
/* END OF FILE */
|
clickteam-plugin/ASCII
|
src/Main.h
|
<reponame>clickteam-plugin/ASCII<filename>src/Main.h
/*
* Copyright 2009-2013 <NAME>
* http://www.magicspark.org/ or http://oulydev.free.fr/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __MMF2EXT_ASCII_MAIN_H__
#define __MMF2EXT_ASCII_MAIN_H__
// Object identifier "MKE1"
#define IDENTIFIER 0x4D4B4531
// Object versions
#define KCX_CURRENT_VERSION 1
// ---------------------------
// DEFINITION OF ACTIONS CODES
// ---------------------------
#define ACT_LAST 0
// ------------------------------
// DEFINITION OF CONDITIONS CODES
// ------------------------------
#define CND_LAST 0
// -------------------------------
// DEFINITION OF EXPRESSIONS CODES
// -------------------------------
#define EXP_INT2CHAR 0
#define EXP_CHAR2INT 1
#define EXP_LAST 2
// ---------------------
// OBJECT DATA STRUCTURE
// ---------------------
// Used at edit time and saved in the MFA/CCN/EXE files
typedef struct tagEDATA_V1
{
// Header - required
extHeader eHeader;
// Object's data
} EDITDATA;
typedef EDITDATA * LPEDATA;
// --------------------------------
// RUNNING OBJECT DATA STRUCTURE
// --------------------------------
// Used at runtime. Initialize it in the CreateRunObject function.
// Free any allocated memory or object in the DestroyRunObject function.
//
// Note: if you store C++ objects in this structure and do not store
// them as pointers, you must call yourself their constructor in the
// CreateRunObject function and their destructor in the DestroyRunObject
// function. As the RUNDATA structure is a simple C structure and not a C++ object.
typedef struct tagRDATA
{
// Main header - required
headerObject rHo;
// Optional headers - depend on the OEFLAGS value, see documentation and examples for more info
// rCom rc; // Common structure for movements & animations
// rMvt rm; // Movements
// rSpr rs; // Sprite (displayable objects)
// rVal rv; // Alterable values
// Object's runtime data
} RUNDATA;
typedef RUNDATA * LPRDATA;
// Size when editing the object under level editor
// -----------------------------------------------
#define MAX_EDITSIZE sizeof(EDITDATA)
// Default flags - see documentation for more info
// -------------
#define OEFLAGS OEFLAG_DISPLAYINFRONT
#define OEPREFS 0
// If to handle message, specify the priority of the handling procedure
// 0= low, 255= very high. You should use 100 as normal.
// --------------------------------------------------------------------
#define WINDOWPROC_PRIORITY 100
#endif /* __MMF2EXT_ASCII_MAIN_H__ */
/* END OF FILE */
|
clickteam-plugin/ASCII
|
src/Resource.h
|
<reponame>clickteam-plugin/ASCII<filename>src/Resource.h
/*
* Copyright 2009-2013 <NAME>
* http://www.magicspark.org/ or http://oulydev.free.fr/
*
* 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.
*/
// Used by Ext.rc
#ifndef __MMF2EXT_ASCII_RESOURCE_H__
#define __MMF2EXT_ASCII_RESOURCE_H__
#define _APS_NO_MFC 1
// About box information
#define IDST_OBJNAME 128
#define IDST_AUTHOR 129
#define IDST_COPYRIGHT 130
#define IDST_COMMENT 131
#define IDST_HTTP 132
// Dialog Box ID
#define DB_SETUP 20003
// Help ID
#define ID_HELP 20004
// Actions
//-------------------
// Identifier of actions menu
#define MN_ACTIONS 20000
// Commands of action menu
// Action strings
// Titles of action parameters
// Conditions
//--------------------
// Identifier of conditions menu
#define MN_CONDITIONS 20001
// Commands of condition menu
// Condition strings
// Titles of condition parameters
// EXPRESSIONS
//---------------------
// Identifier of expressions menu
#define MN_EXPRESSIONS 20002
// Commands of expressions menu
#define EXP_IDMN_INT2CHAR 27000
#define EXP_IDMN_CHAR2INT 27001
// Expression strings
#define EXP_IDS_INT2CHAR 7000
#define EXP_IDS_CHAR2INT 7001
// Names of expression parameters
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
#endif /* __MMF2EXT_ASCII_RESOURCE_H__ */
/* END OF FILE */
|
sivanbil/c-course
|
Calculator/main.c
|
<filename>Calculator/main.c
//
// Created by sivan on 2021/5/29.
//
#include "main.h"
int main() {
int left = 0;
int right = 0;
char operator;
int times = 0;
while(times <= 10) {
puts("please enter expression like '1 + 2':");
scanf("%d %c %d", &left, &operator, &right);
printf("The result is: %d\n", Calculator(left, right, operator));
}
}
|
sivanbil/c-course
|
Pointer/main.c
|
//
// Created by sivan on 2021/6/1.
//
#include "main.h"
int main() {
int value_int = 2;
int other_value_int = 4;
int *p = &value_int;
// Read from back to front
// Read-only pointer points to a variable
int *const pp = &value_int;
// The pointer points to a read-only variable
int const *ppp = &value_int;
// The pointer can point to another address
ppp = &other_value_int;
PRINT_INT(*ppp);
PRINT_INT(*pp);
PRINT_INT(*p);
PRINT_HEX(p);
{
int array[] = {0, 2, 4, 6, 8, 10};
int *p = array;
// 指针做加减运算,相当于是移位
PRINT_INT(*(p + 3));
PRINT_INT(*(array + 3));
PRINT_INT(p[3]);
PRINT_INT(array[3]);
}
return 0;
}
|
sivanbil/c-course
|
CompileCondition/main.c
|
//
// Created by sivan on 2021/5/30.
// #ifndef
// #ifdef
// #if
//
#include <stdio.h>
#define DEBUG
void dump(char *message) {
#ifdef DEBUG
puts(message);
#endif
}
int main() {
dump("main start\n");
printf("Hello world\n");
printf("__STDC_VERSION:%ld\n", __STDC_VERSION__);
#if __STDC_VERSION__ == 201112
puts("C11");
#elif __STDC_VERSION__ >= 19901
puts("C99");
#else
puts("maybe C90?");
#endif
dump("main end\n");
return 0;
}
|
sivanbil/c-course
|
FileStream/main.h
|
//
// Created by sivan on 2021/6/2.
//
#include <io_utils.h>
#ifndef C_COURSE_MAIN_H
#define C_COURSE_MAIN_H
#endif //C_COURSE_MAIN_H
|
sivanbil/c-course
|
FileStream/main.c
|
<filename>FileStream/main.c<gh_stars>1-10
//
// Created by sivan on 2021/6/2.
//
#include "main.h"
int main() {
FILE *file = fopen("main.h", "r");
return 0;
}
|
sivanbil/c-course
|
HanoiTower/tower_main.h
|
//
// Created by sivan on 2021/5/30.
//
#include <stdio.h>
#ifndef C_COURSE_MAIN_H
#define C_COURSE_MAIN_H
#endif //C_COURSE_MAIN_H
/**
*
* @param n
* @param src
* @param dest
* @param tmp
*/
void Move(int n, char src, char dest, char tmp);
void Move(int n, char src, char dest, char tmp) {
if (n == 0) {
return;
}
else if (n == 1) printf("%c --> %c\n", src, dest);
else {
Move(n - 1, src, tmp, dest);
Move(1, src, dest, tmp);
Move(n - 1, tmp, dest, src);
}
}
|
sivanbil/c-course
|
Struct/main.c
|
//
// Created by sivan on 2021/6/1.
//
#include "main.h"
typedef struct Job {
char *name;
int id;
char *location;
} Job;
typedef struct Person {
char *name;
int age;
Job *job;
} Person;
int main() {
Job job = {.name="intern", .id=1, .location="shanghai"};
Person person = {.age=10, .name="xiaoli", .job=&job};
PRINT_INT(person.age);
struct Person *person_ptr = &person;
PRINT_INT(person_ptr->age);
PRINT_INT(person_ptr->job);
PRINT_INT(sizeof(person));
PRINT_HEX(person);
return 0;
}
|
sivanbil/c-course
|
Pointer/left_right_value.c
|
//
// Created by sivan on 2021/6/1.
//
#include "main.h"
int main() {
int a;
a = 2;
int *p = &a;
*p = 3;
// 右值 就是个值,而不是storage
int b = *p;
int array[4] = {0};
int *pa = array;
*pa = 2;
*(pa++) = 3;
// left is storage, right is value
return 0;
}
|
sivanbil/c-course
|
include/io_utils.h
|
<gh_stars>1-10
//
// Created by sivan on 2021/5/30.
//
#ifndef C_COURSE_IO_UTILS_H
#define C_COURSE_IO_UTILS_H
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#define PRINT_METADATA
#ifdef PRINT_METADATA
# define PRINTLNF(format, ...) printf("("__FILE__":%d) %s:"format"\n", __LINE__, __FUNCTION__, ##__VA_ARGS__)
#else
# define PRINTLNF(format, ...) printf(format"\n", ##__VA_ARGS__)
#endif
#define PRINT_CHAR(char_value) PRINTLNF(#char_value": %c", char_value)
#define PRINT_WCHAR(char_value) PRINTLNF(#char_value": %lc", char_value)
#define PRINT_INT(int_value) PRINTLNF(#int_value": %d", int_value)
#define PRINT_HEX(int_value) PRINTLNF(#int_value": %#x", int_value)
#define PRINT_DOUBLE(double_value) PRINTLNF(#double_value": %lf", double_value)
#endif //C_COURSE_IO_UTILS_H
|
sivanbil/c-course
|
ArrayBoundary/main.h
|
<filename>ArrayBoundary/main.h
//
// Created by sivan on 2021/5/30.
//
#ifndef C_COURSE_MAIN_H
#define C_COURSE_MAIN_H
#include <io_utils.h>
#endif //C_COURSE_MAIN_H
|
sivanbil/c-course
|
Calculator/main.h
|
//
// Created by sivan on 2021/5/29.
//
#include "stdio.h"
#ifndef C_COURSE_MAIN_H
#define C_COURSE_MAIN_H
#endif //C_COURSE_MAIN_H
#ifndef MATH_OPERATOR
#define MATH_OPERATOR 1
#define MATH_OPERATOR_ADD '+'
#define MATH_OPERATOR_MINUS '-'
#define MATH_OPERATOR_MULTIPLE '*'
#define MATH_OPERATOR_DIVIDE '/'
#define MATH_OPERATOR_MOD '%'
#endif
__BEGIN_DECLS
/**
* OPERATOR
* @param left
* @param right
* @param operator
* @return
*/
int Calculator(int left, int right, char operator);
/**
* plus two numbers
* @param a
* @param b
* @return
*/
int Add(int a, int b);
/**
*
* @param a
* @param b
* @return
*/
int Minus(int a, int b);
/**
*
* @param a
* @param b
* @return
*/
int Multiple(int a, int b);
/**
* divide
* @param a
* @param b
* @return
*/
int Divide(int a, int b);
/**
* mod
* @param a
* @param b
* @return
*/
int Mod(int a, int b);
__END_DECLS
int Calculator(int left, int right, char operator) {
int result = 0;
switch (operator) {
case MATH_OPERATOR_MINUS:
result = Minus(left, right);
break;
case MATH_OPERATOR_MULTIPLE:
result = Multiple(left, right);
break;
case MATH_OPERATOR_DIVIDE:
result = Divide(left, right);
break;
case MATH_OPERATOR_MOD:
result = Mod(left, right);
break;
case MATH_OPERATOR_ADD:
default:
result = Add(left, right);
break;
}
return result;
}
int Multiple(int a, int b) {
return a * b;
}
int Mod(int a, int b) {
return a % b;
}
int Minus(int a, int b) {
return a - b;
}
int Divide(int a, int b) {
return a / b;
}
int Add(int a, int b) {
return a + b;
}
|
sivanbil/c-course
|
HanoiTower/tower_main.c
|
<gh_stars>1-10
//
// Created by sivan on 2021/5/30.
//
#include "tower_main.h"
int main(void) {
Move(5, 'A', 'C', 'B');
return 0;
}
|
sivanbil/c-course
|
Printlnf/main.h
|
<reponame>sivanbil/c-course<gh_stars>1-10
//
// Created by sivan on 2021/5/30.
//
#include <stdio.h>
#include <stdarg.h>
#ifndef C_COURSE_MAIN_H
#define C_COURSE_MAIN_H
#endif //C_COURSE_MAIN_H
|
sivanbil/c-course
|
CompileCondition/main.h
|
//
// Created by sivan on 2021/5/30.
//
#ifndef C_COURSE_MAIN_H
#define C_COURSE_MAIN_H
#endif //C_COURSE_MAIN_H
|
sivanbil/c-course
|
Printlnf/main.c
|
<gh_stars>1-10
//
// Created by sivan on 2021/5/30.
//
#include "main.h"
#include "../include/io_utils.h"
void Printlnf(const char* format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
printf("\n");
va_end(args);
}
// use macro function
//#define PRINTLNF(format, ...) printf(format"\n", ##__VA_ARGS__)
//#define PRINTLNF(format, ...) printf(format"\n", ##__VA_ARGS__)
//
//#define PRINT_INT(value)
int main(void) {
char array_char[5] = {[2] = 'a', 'b', 'c'};
for (int i = 0; i < 5; ++i) {
PRINT_CHAR(array_char[i]);
}
int value = 2;
Printlnf("hello world %d", value);
PRINTLNF("hello world %d", value);
PRINT_INT(2);
PRINT_DOUBLE(2.0);
return 0;
}
|
sivanbil/c-course
|
MacroFunc/macro_function.c
|
<reponame>sivanbil/c-course
//
// Created by sivan on 2021/5/30.
//
#include <stdio.h>
#define MAX(a, b) (a) > (b) ? (a) : (b)
/**
* define macro function with multi lines.
*/
#define IS_HEX_CHARACTER(ch) \
((ch) >= '0' && (ch) <= '9') || \
((ch) >= 'A' && (ch) <= 'F') || \
((ch) >= 'a' && (ch) <= 'f')
int main(void) {
// int max = MAX(1, 3);
int max2 = MAX(1, MAX(4, 5));
printf("max2: %d\n", max2);
int a = IS_HEX_CHARACTER('A');
printf("%d\n", a);
return 0;
}
|
sivanbil/c-course
|
ArrayBoundary/main.c
|
//
// Created by sivan on 2021/5/30.
//
#include "main.h"
#define MAX_SIZE 5
int main() {
int array[MAX_SIZE];
PRINT_INT(array[0]);
PRINT_INT(array[5]);
// array[5] => array + 5
// VAL The length of an array can be declared as a variable. c99+ or gcc support
int value = 2;
int array_size_of_value[value];
const int kSize = 5;
int array_size_of_kSize[kSize];
return 0;
}
|
sivanbil/c-course
|
Struct/link_node.c
|
<filename>Struct/link_node.c
//
// Created by sivan on 2021/6/2.
//
#include "main.h"
typedef struct LinkNode {
int value;
struct LinkNode *next;
} LinkNode;
LinkNode *CreateLinkNode(int value) {
LinkNode *node = malloc(sizeof(LinkNode));
if (!node) {
//
exit(0);
}
node->value = value;
node->next = NULL;
return node;
}
void DestroyNode(LinkNode **node_ptr) {
(*node_ptr)->next = NULL;
free(*node_ptr);
*node_ptr = NULL;
}
LinkNode *CreateList(int array[], int length) {
if (length <=0) return NULL;
LinkNode *head = CreateLinkNode(array[0]);
LinkNode *current = head;
for (int i = 1; i < length; ++i) {
current->next = CreateLinkNode(array[i]);
current = current->next;
}
return head;
}
void DestroyList(LinkNode **head) {
if (!head || (*head)) return;
LinkNode *current = *head;
while (current) {
LinkNode *to_be_destroy = current;
current = current->next;
DestroyNode(&to_be_destroy);
}
*head = NULL;
}
void InsertNodeK(LinkNode **head, int value, int index) {
if (!head || index < 0) return;
LinkNode *new_node = CreateLinkNode(value);
if (index == 0) {
new_node->next = *head;
*head = new_node;
} else {
if (!(*head)) {
*head = CreateLinkNode(0);
}
LinkNode *current = *head;
// find index node
while (index > 1) {
if (!current->next) {
current->next = CreateLinkNode(0);
}
current = current->next;
index--;
}
// 1-> 2-> 3
// 1-> 2->4-> 3 // current = 2
new_node->next = current->next;
current->next = current;
}
}
void InsertNode(LinkNode **head, int value, int index) {
if (!head || index < 0) return;
LinkNode *new_node = CreateLinkNode(value);
if (index == 0) {
new_node->next = *head;
*head = new_node;
} else {
if (!(*head)) {
*head = CreateLinkNode(0);
}
LinkNode *current = *head;
while (index > 1) {
if (!current->next) {
current->next = CreateLinkNode(0);
}
current = current->next;
index--;
}
new_node->next = current->next;
current->next = new_node;
}
}
void PrintLinkList(LinkNode *head) {
while (head) {
PRINT_INT(head->value);
head = head->next;
}
}
// array resize cost too much
// 1 -> 2 -> 3 -> 4 -> 5
int main() {
// LinkNode *node = CreateLinkNode(0);
// DestroyNode(&node);
int array[] = {0, 1, 2, 3, 4};
LinkNode *head = CreateList(array, 5);
// PrintLinkList(head);
InsertNode(&head, 100, 10);
PrintLinkList(head);
DestroyList(&head);
PRINT_HEX(head);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.