示例#1
0
static
void
start_rabbit_game(CORE_DATA *cd, PLAYER *p, int bty, int special)
{
	/* store rabbit's pid in user data */
	ud(cd)->rabbit_pid = p->pid;

	/* announce the game to the arena */
	ArenaMessageFmt("%s is now the rabbit!", p->name);
	ArenaMessageFmt("%s is now the rabbit!", p->name);
	ArenaMessageFmt("%s is now the rabbit!", p->name);

	/* announce the game to the player */
	PrivMessageFmt(p, "You are now the rabbit! The game will end if you enter safe!");

	/* prize the bounty/special */
	PrivMessageFmt(p, "*prize %d", bty);
	if (special)
		PrivMessageFmt(p, "*prize #%d", special);

	/*
	 * send *where to get rabbits location and set the bot to parse messages looking
	 * for the response
	 */
	PrivMessage(p, "*where");
	ud(cd)->expecting_where = 1;

	/* set the timer for the next *where to be sent */
	ud(cd)->where_timer = SetTimer(SPAM_INTERVAL_MS, 0, 0);

	/* set the timer that signifies the game's end */
	ud(cd)->gameover_timer = SetTimer(GAME_LENGTH_MS, 0, 0);
}
示例#2
0
int genRandom(int min, int max)
{
    std::random_device rd;
    std::default_random_engine e1(rd());
    std::uniform_int_distribution<int> ud(min, max);
    int mean = ud(e1);
    
    return mean;
}
/*
 * select random sample of k elements from vector of int
 * with equal probability
 *
 * O(n) time O(1) space
 *
 * select random 1 and add 1 to it randomly
 *
 */
void Arrays::randomSampling(int k, std::vector<int> &vect) {
	// select random index between 0 to n-1
	// swap it with a[i] from 0 to k
	int size = vect.size();
	std::random_device rd;
	std::default_random_engine ran_gen(rd());

	for (int i = 0; i < k; i++) {
		std::uniform_int_distribution<int> ud(i,size-1);
		std::swap(vect[i],vect[static_cast<int>(ud(ran_gen))]);
	}
}
示例#4
0
文件: 3381.cpp 项目: slgu/zoj_code
void ud(int l,int r,int pos,int i,int x)
{
	if(l==r&&l==pos)
	{
		seg[i]=x;
		return;
	}
	int mid=(l+r)>>1;
	if(mid>=pos)
		ud(l,mid,pos,2*i,x);
	else
		ud(mid+1,r,pos,2*i+1,x);
	up(i);
}
void MkOrthogonalCamera::UpdateViewProjectionMatrix(void)
{
	// view matrix
	D3DXVECTOR3 ep(m_Position.x + 0.5f, m_Position.y - 0.5f, -(MKDEF_CAMERA_DEPTH_OFFSET)); // magic number
	D3DXVECTOR3 lp(ep.x, ep.y, 0.f);
	D3DXVECTOR3 ud(0.f, 1.f, 0.f);
	D3DXMatrixLookAtLH(&m_ViewMatrix, &ep, &lp, &ud);

	// projection matrix
	D3DXMatrixOrthoLH(&m_ProjectionMatrix, m_Size.x, m_Size.y, m_NearClip, m_FarClip);
}
示例#6
0
void ezQtCurve1DEditorWidget::SetCurves(ezCurveGroupData& curves, double fMinCurveLength, bool bCurveLengthIsFixed)
{
  ezQtScopedUpdatesDisabled ud(this);
  ezQtScopedBlockSignals bs(this);

  m_Curves.CloneFrom(curves);

  CurveEdit->SetCurves(&curves, fMinCurveLength, bCurveLengthIsFixed);
  m_fCurveDuration = CurveEdit->GetMaxCurveExtent();

  UpdateSpinBoxes();
}
示例#7
0
文件: main.cpp 项目: keitee/kb
int main()
{
   const size_t count = 10000000;
   std::vector<int> data(count);
   
   std::random_device rd;
   std::mt19937 mt;
   auto seed_data = std::array<int, std::mt19937::state_size> {};
   std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
   std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
   mt.seed(seq);
   std::uniform_int_distribution<> ud(1, 100);

   std::generate_n(std::begin(data), count, [&mt, &ud]() {return ud(mt); });
   
   auto start = std::chrono::system_clock::now();
   auto r1 = alter(data, [](int const e) {return e * e; });
   auto end = std::chrono::system_clock::now();
   auto t1 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
   std::cout << "time: " << t1.count() << "ms" << std::endl;
   
   start = std::chrono::system_clock::now();
   auto r2 = palter(data, [](int const e) {return e * e; });
   end = std::chrono::system_clock::now();
   auto t2 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
   std::cout << "time: " << t2.count() << "ms" << std::endl;

   start = std::chrono::system_clock::now();
   auto r3 = palter2(data, [](int const e) {return e * e; });
   end = std::chrono::system_clock::now();
   auto t3 = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
   std::cout << "time: " << t3.count() << "ms" << std::endl;

   assert(r1 == r2);
   assert(r1 == r3);
}
示例#8
0
PropertyHelper<UDim>::return_type
PropertyHelper<UDim>::fromString(const String& str)
{
    UDim ud(0.0f, 0.0f);

    if (str.empty())
        return ud;

    std::stringstream& sstream = SharedStringstream::GetPreparedStream(str);
    sstream >> ud;
    if (sstream.fail())
        throwParsingException(getDataTypeName(), str);

    return ud;
}
示例#9
0
文件: 3018.cpp 项目: slgu/zoj_code
void ud(int x,int y,int i,int n)
{
	if(seg[i].l==seg[i].r&&seg[i].a==seg[i].b)
	{
		seg[i].sum+=n;
		return;
	}
	int xm=(seg[i].l+seg[i].r)>>1;
	int ym=(seg[i].a+seg[i].b)>>1;
	if(xm>=x&&ym>=y)
	{
		if(!seg[i].ch[0])
			seg[i].ch[0]=get(seg[i].l,xm,seg[i].a,ym);
		ud(x,y,seg[i].ch[0],n);
	}
	if(xm>=x&&ym<y)
	{
		if(!seg[i].ch[1])
			seg[i].ch[1]=get(seg[i].l,xm,ym+1,seg[i].b);
		ud(x,y,seg[i].ch[1],n);
	
	}
	if(xm<x&&ym>=y)
	{
		if(!seg[i].ch[2])
			seg[i].ch[2]=get(xm+1,seg[i].r,seg[i].a,ym);
		ud(x,y,seg[i].ch[2],n);
	}
	if(xm<x&&ym<y)
	{
		if(!seg[i].ch[3])
			seg[i].ch[3]=get(xm+1,seg[i].r,ym+1,seg[i].b);
		ud(x,y,seg[i].ch[3],n);
	}
	up(i);
}
示例#10
0
 void
 AACEncode::pushBuffer(const uint8_t* const data, size_t size, IMetadata& metadata)
 {
     const size_t sampleCount = size / m_bytesPerSample;
     const size_t aac_packet_count = sampleCount / kSamplesPerFrame;
     const size_t required_bytes = aac_packet_count * m_outputPacketMaxSize;
     
     if(m_outputBuffer.total() < (required_bytes)) {
         m_outputBuffer.resize(required_bytes);
     }
     uint8_t* p = m_outputBuffer();
     uint8_t* p_out = (uint8_t*)data;
     
     for ( size_t i = 0 ; i < aac_packet_count ; ++i ) {
         UInt32 num_packets = 1;
         
         AudioBufferList l;
         l.mNumberBuffers=1;
         l.mBuffers[0].mDataByteSize = m_outputPacketMaxSize * num_packets;
         l.mBuffers[0].mData = p;
         
         std::unique_ptr<UserData> ud(new UserData());
         ud->size = static_cast<int>(kSamplesPerFrame * m_bytesPerSample);
         ud->data = const_cast<uint8_t*>(p_out);
         ud->packetSize = static_cast<int>(m_bytesPerSample);
         
         AudioStreamPacketDescription output_packet_desc[num_packets];
         m_converterMutex.lock();
         AudioConverterFillComplexBuffer(m_audioConverter, AACEncode::ioProc, ud.get(), &num_packets, &l, output_packet_desc);
         m_converterMutex.unlock();
         
         p += output_packet_desc[0].mDataByteSize;
         p_out += kSamplesPerFrame * m_bytesPerSample;
     }
     const size_t totalBytes = p - m_outputBuffer();
     
     
     auto output = m_output.lock();
     if(output && totalBytes) {
         if(!m_sentConfig) {
             output->pushBuffer((const uint8_t*)m_asc, sizeof(m_asc), metadata);
             m_sentConfig = true;
         }
         
         output->pushBuffer(m_outputBuffer(), totalBytes, metadata);
     }
 }
示例#11
0
std::string Detect(agi::fs::path const& file) {
	agi::read_file_mapping fp(file);

	// If it's over 100 MB it's either binary or big enough that we won't
	// be able to do anything useful with it anyway
	if (fp.size() > 100 * 1024 * 1024)
		return "binary";

	uint64_t binaryish = 0;

#ifdef WITH_UCHARDET
	agi::scoped_holder<uchardet_t> ud(uchardet_new(), uchardet_delete);
	for (uint64_t offset = 0; offset < fp.size(); ) {
		auto read = std::min<uint64_t>(4096, fp.size() - offset);
		auto buf = fp.read(offset, read);
		uchardet_handle_data(ud, buf, read);
		uchardet_data_end(ud);
		if (*uchardet_get_charset(ud))
			return uchardet_get_charset(ud);

		offset += read;

		// A dumb heuristic to detect binary files
		for (size_t i = 0; i < read; ++i) {
			if ((unsigned char)buf[i] < 32 && (buf[i] != '\r' && buf[i] != '\n' && buf[i] != '\t'))
				++binaryish;
		}

		if (binaryish > offset / 8)
			return "binary";
	}
	return uchardet_get_charset(ud);
#else
	auto read = std::min<uint64_t>(4096, fp.size());
	auto buf = fp.read(0, read);
	for (size_t i = 0; i < read; ++i) {
		if ((unsigned char)buf[i] < 32 && (buf[i] != '\r' && buf[i] != '\n' && buf[i] != '\t'))
			++binaryish;
	}

	if (binaryish > read / 8)
		return "binary";
	return "utf-8";
#endif
}
示例#12
0
         bool passwordAuth::addUser(std::string const& _username, std::string const& _password,
                                    std::string const& _temp_dir, std::string const& _work_dir,
                                    std::string const& _seed_dir, std::string const& _dest_dir,
                                    bool const _controlFlag, std::string const& _callback
                                    )
         {
            bool status = false;

            if (GetUser(_username) == users.end())
               {
                  userData ud(_password, _temp_dir, _work_dir, _seed_dir, _dest_dir, _controlFlag, _callback);
                  std::pair<std::string, userData> p(_username, ud);
                  users.insert(p);
                  status = true;
               }

            return status;
         }
示例#13
0
文件: 3018.cpp 项目: slgu/zoj_code
int main()
{
	while(gets(str)!=NULL)
	{
		cnt=0;
		ff=1;
		get(1,MAXN,1,MAXN);
		while(1)
		{
			if(str[0]=='E')
				break;
			if(str[0]=='I')
			{
				ff=1;
				gets(str);
				continue;
			}
			else
				if(str[0]=='Q')
				{
					ff=0;
					gets(str);
					continue;
				}
				else
				{
					int a,b,c,d;
					if(ff)
					{
						sscanf(str,"%d%d%d",&a,&b,&c);
						ud(a,b,1,c);
					}
					else
					{
						sscanf(str,"%d%d%d%d",&a,&b,&c,&d);
						printf("%d\n",qu(a,b,c,d,1));
					}
				}
			gets(str);
		}
	}
	return 0;
}
示例#14
0
QCommDeviceController_Private::QCommDeviceController_Private(const QByteArray &devId,
        QCommDeviceController *parent) : QObject(parent), m_sock(0)
{
    m_parent = parent;
    m_devId = devId;

    QByteArray p("/Hardware/Devices/");
    p.append(m_devId);

    // Find out the path to connect the UNIX socket to
    QValueSpaceItem *vPath = new QValueSpaceItem(p);
    QVariant path = vPath->value("Path");
    m_path = path.toByteArray();
    delete vPath;

    // ValueSpaceItem for up/down information
    QByteArray ud(p);
    ud.append("/Status");
    m_upDown = new QValueSpaceItem(ud);
    connect(m_upDown, SIGNAL(contentsChanged()),
            this, SLOT(statusChanged()));

    // ValueSpaceItem for Power State information
    QByteArray powerState(p);
    powerState.append("/PowerState");
    m_state = new QValueSpaceItem(powerState);
    connect(m_state, SIGNAL(contentsChanged()),
            this, SLOT(powerStateChanged()));

    // ValueSpaceItem for whether there are any active sessions
    QByteArray sessionsActive(p);
    sessionsActive.append("/ActiveSessions");
    m_sessionsActive = new QValueSpaceItem(sessionsActive);

    m_sock = new QUnixSocket();

    if (!m_sock->connect(m_path)) {
        delete m_sock;
        m_sock = 0;
        return;
    }
}
示例#15
0
void BoostDateTimeTestCase::test_gregorian_dateAsString()
{
    try
    {
        //The following date is in ISO 8601 extended format (CCYY-MM-DD)
        std::string strDate("2012-12-12");
        boost::gregorian::date d(boost::gregorian::from_simple_string(strDate));

        std::cout<< boost::gregorian::to_simple_string(d) << std::endl;

        //Read ISO Standard(CCYYMMDD) and output ISO Extended
        std::string ud("20120117"); // my birth day
        boost::gregorian::date d1(boost::gregorian::from_undelimited_string(ud));

        std::cout << boost::gregorian::to_iso_extended_string(d1) << std::endl;

        
        //Output the parts of the date - Tuesday October 9, 2001
        boost::gregorian::date::ymd_type ymd = d1.year_month_day();
        boost::gregorian::greg_weekday wd = d1.day_of_week();

        std::cout << wd.as_long_string() << " "
                  << ymd.month.as_long_string() << " "
                  << ymd.day << ", " << ymd.year
                  << std::endl;
        
        //Let's send in month 25 by accident and create an exception
        std::string bad_date("20012509"); //2001-??-09
        std::cout << "An expected exception is next: " << std::endl;
        boost::gregorian::date wont_construct(boost::gregorian::from_undelimited_string(bad_date));
        //use wont_construct so compiler doesn't complain, but you wont get here!
        std::cout << "oh oh, you shouldn't reach this line: " 
                  << boost::gregorian::to_iso_string(wont_construct) << std::endl;
            
    }
    catch(std::exception& e)
    {
        std::cout<< "Exception:" << e.what() << std::endl;
    }
}
示例#16
0
/*!
  All distribution have a defualt constructor which sets the parameter
  distribution to default values. Look at a reference manual to have a
  complete list of the possible arguments.
 */
int main()
{
  // We use the knuth engine
    std::knuth_b e;
  
  // Try the random engine
  //  std::random_device e;
  
  // Note the <>. It is compulsory, since it is a 
  // full specialization of a class template
  std::uniform_real_distribution<> ud(0, 10);
  distr(ud,e,"uniform_real_distribution");
  
  // Default is mean 0 and standard deviation 1
  std::normal_distribution<> nd;
  distr(nd,e,"normal_distribution, mean 0, stdev 1");

  // Mean 1  Std dev 2.0
  std::normal_distribution<> nd2(1.0,2.0);
  distr(nd2,e,"normal_distribution, mean 1, stdev 2");
  
  std::exponential_distribution<> ed;
  distr(ed,e,"exponential_distribution (lambda=1.0)");
  
  std::gamma_distribution<> gd;
  distr(gd,e,"gamma_distribution");

  std::lognormal_distribution<> lnd;
  distr(lnd,e,"lognormal_distribution");

  std::weibull_distribution<> wd;
  distr(wd,e,"weibull_distribution");

  //This produces a very "elongated" distribution
  // so I have commented it out
  //  std::student_t_distribution<> sd;
  //distr(sd,e,"student_t_distribution");
}
示例#17
0
文件: 3381.cpp 项目: slgu/zoj_code
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		build(1,n,1);
		for(int i=1;i<=n;i++)
			scanf("%d%d%d",s+i,x+i,y+i);
		dp[n]=s[n];
		for(int i=n-1;i>=1;i--)
		{
			ud(1,n,i+1,1,dp[i+1]);
			if(i+y[i]-1<=n)
			dp[i]=s[i]+qu(1,n,i+x[i],i+y[i]-1,1);
			else
			if(i+x[i]<=n)
			dp[i]=s[i]+qu(1,n,i+x[i],n,1);
			else
			dp[i]=s[i];
		}
		printf("%d\n",dp[1]);
	}
	return 0;
}
示例#18
0
unsigned random_gen(unsigned seed, unsigned min, unsigned max)
{
    static std::default_random_engine e(seed);
    static std::uniform_int_distribution<unsigned> ud(min, max);
    return ud(e);
}
示例#19
0
void SparseSVD (
  const std::vector<int>& qR, // Spin quantum #s for row index
  const std::vector<int>& qC, // Spin quantum #s for col index
  const Wavefunction<double>& Wfn,
        std::vector<int>& qS, // Spin quantum #s for selected singular values
        std::vector<std::vector<double>>& lambda,
        MPS<double>& aMps,
        MPS<double>& bMps,
        double CUTOFF_)
{
  // define reference for convenience

  const matrix_type<double>& uu = Wfn.matrix_uu;
  const matrix_type<double>& ud = Wfn.matrix_ud;
  const matrix_type<double>& du = Wfn.matrix_du;
  const matrix_type<double>& dd = Wfn.matrix_dd;

  // Calculating qS0 from row quanta
  std::vector<int> qS0; qS0.reserve(2*qR.size());

  for(size_t i = 0; i < qR.size(); ++i) {
    qS0.push_back(qR[i]+1);
    qS0.push_back(qR[i]-1);
  }
  // Remove duplication...
  std::sort(qS0.begin(),qS0.end());
  qS0.resize(std::distance(qS0.begin(),std::unique(qS0.begin(),qS0.end())));

  qS.clear();
  qS.reserve(qS0.size());

  lambda.clear();
  lambda.reserve(qS0.size());

  MPS<double> aMps_;
  aMps_.matrix_u.resize(qR.size(),qS0.size());
  aMps_.matrix_d.resize(qR.size(),qS0.size());

  MPS<double> bMps_;
  bMps_.matrix_u.resize(qS0.size(),qC.size());
  bMps_.matrix_d.resize(qS0.size(),qC.size());

  matrix_type<double>& ua = aMps_.matrix_u;
  matrix_type<double>& da = aMps_.matrix_d;
  matrix_type<double>& ub = bMps_.matrix_u;
  matrix_type<double>& db = bMps_.matrix_d;

  size_t nSym = 0; // Total # of qunatum blocks to be seletected
  size_t nSel = 0; // Total # of states

  // Loop over symmetry of singular values

  for(size_t k = 0; k < qS0.size(); ++k) {

//  std::cout << "\t\t\tSymmetry sector " << std::setw(4) << k << " (" << std::setw(4) << qS0[k] << ")" << std::endl;

    // (0)  (4)  (f)  (2)
    // 0 0  0 1  1 1  0 0
    // 0 0, 0 0, 1 1, 1 0
    unsigned char bitShape = 0x0;

    int nrow = 0;
    int ncol = 0;

    // offset
    int prow = 0;
    int pcol = 0;

    // find spin symmetry viewed as forward...

    // e.g.)
    // cQ = 0 2 4 6 8 10 ...
    // rQ = 1 3 5 7 9 11 ...

    int iu,ju,id,jd;

    iu = findQuantaIndex(qR,qS0[k]-1); // Find qR[:]+1 == qS0[i]
    ju = findQuantaIndex(qC,qS0[k]+1); // Find -qS0[i] == -qC[:]+1

    id = findQuantaIndex(qR,qS0[k]+1); // Find qR[:]-1 == qS0[i]
    jd = findQuantaIndex(qC,qS0[k]-1); // Find -qS0[i] == -qC[:]+1

    if(iu >= 0 && ju >= 0 && uu(iu,ju)) {
      prow = uu(iu,ju)->rows();
      pcol = uu(iu,ju)->cols();
    //if((bitShape ^ 0xf) & 0x4) -- always true at this line
        nrow += prow;
    //if((bitShape ^ 0xf) & 0x2) -- always true at this line
        ncol += pcol;
      bitShape |= 0x8;
    }

    if(iu >= 0 && jd >= 0 && ud(iu,jd)) {
      prow = ud(iu,jd)->rows();
      if((bitShape ^ 0xf) & 0x8)
        nrow += prow;
    //if((bitShape ^ 0xf) & 0x1) -- always true at this line
        ncol += ud(iu,jd)->cols();
      bitShape |= 0x4;
    }

    if(id >= 0 && ju >= 0 && du(id,ju)) {
      pcol = du(id,ju)->cols();
    //if((bitShape ^ 0xf) & 0x1) -- always true at this line
        nrow += du(id,ju)->rows();
      if((bitShape ^ 0xf) & 0x8)
        ncol += pcol;
      bitShape |= 0x2;
    }

    if(id >= 0 && jd >= 0 && dd(id,jd)) {
      if((bitShape ^ 0xf) & 0x2)
        nrow += dd(id,jd)->rows();
      if((bitShape ^ 0xf) & 0x4)
        ncol += dd(id,jd)->cols();
      bitShape |= 0x1;
    }

    if(!bitShape) continue;

    local_matrix_type<double> C = local_matrix_type<double>::Zero(nrow,ncol);

    if(bitShape & 0x8)
      C.block(   0,   0,     prow,     pcol) = *uu(iu,ju);
    if(bitShape & 0x4)
      C.block(   0,pcol,     prow,ncol-pcol) = *ud(iu,jd);
    if(bitShape & 0x2)
      C.block(prow,   0,nrow-prow,     pcol) = *du(id,ju);
    if(bitShape & 0x1)
      C.block(prow,pcol,nrow-prow,ncol-pcol) = *dd(id,jd);

    // now having a merged blcok matrix

//  double cNorm2 = 0.0;
//  for(int ix = 0; ix < C.rows(); ++ix)
//    for(int jx = 0; jx < C.cols(); ++jx)
//      cNorm2 += C(ix,jx)*C(ix,jx);

    // Ignore the case |C| is too small, to avoid numerical instability?
//  if(cNorm2 < 1.0e-16) continue;

    Eigen::JacobiSVD<local_matrix_type<double>> svds(C,Eigen::ComputeThinU|Eigen::ComputeThinV);

    local_matrix_type<double> U = svds.matrixU();
    local_matrix_type<double> Vt= svds.matrixV().transpose();

    int nSvd = 0;
    for(; nSvd < svds.singularValues().size(); ++nSvd)
      if(svds.singularValues()[nSvd] < CUTOFF_) break;

//  std::cout << "\t\t\tTruncating " << std::setw(4) << svds.singularValues().size() << " vectors to " << std::setw(4) << nSvd << std::endl;

    // No singular value is selected...
    if(nSvd == 0) continue;

    nSel += nSvd;

    qS.push_back(qS0[k]);

    lambda.push_back(std::vector<double>(nSvd));
    for(int kSel = 0; kSel < nSvd; ++kSel)
      lambda[nSym][kSel] = svds.singularValues()[kSel];

//DEBUG
//  std::cout << "\t\t\tblock size :: " << std::setw(4) << lambda[k].size() << " ";
//  for(int ksel = 0; ksel < nSvd; ++ksel) {
//    std::cout << std::setw(10) << std::scientific << std::setprecision(2) << lambda[k][ksel];
//    if(ksel % 10 == 9) std::cout << std::endl;
//  }
//  if(lambda[k].size() % 10 > 0) std::cout << std::endl;
//DEBUG

    if(iu >= 0 && prow != 0)
      ua(iu,nSym).reset(new local_matrix_type<double>(U.block(   0,   0,     prow,nSvd)));

    if(id >= 0 && prow != nrow)
      da(id,nSym).reset(new local_matrix_type<double>(U.block(prow,   0,nrow-prow,nSvd)));

    if(ju >= 0 && pcol != 0)
      ub(nSym,ju).reset(new local_matrix_type<double>(Vt.block(   0,   0,nSvd,     pcol)));

    if(jd >= 0 && pcol != ncol)
      db(nSym,jd).reset(new local_matrix_type<double>(Vt.block(   0,pcol,nSvd,ncol-pcol)));

    ++nSym;
  }

  aMps.matrix_u.resize(qR.size(),qS.size());
  aMps.matrix_d.resize(qR.size(),qS.size());
  for(size_t i = 0; i < qR.size(); ++i)
    for(size_t j = 0; j < qS.size(); ++j) {
      aMps.matrix_u(i,j) = ua(i,j);
      aMps.matrix_d(i,j) = da(i,j);
    }

  bMps.matrix_u.resize(qS.size(),qC.size());
  bMps.matrix_d.resize(qS.size(),qC.size());
  for(size_t i = 0; i < qS.size(); ++i)
    for(size_t j = 0; j < qC.size(); ++j) {
      bMps.matrix_u(i,j) = ub(i,j);
      bMps.matrix_d(i,j) = db(i,j);
    }

//std::cout << "\t\t\t" << std::setw(4) << nSel << " vectors are selected..." << std::endl;

}
示例#20
0
文件: controls.c 项目: jordonwu/ICSim
int main(int argc, char *argv[]) {
  int opt;
  struct sockaddr_can addr;
  struct canfd_frame frame;
  int running = 1;
  int enable_canfd = 1;
  int play_traffic = 1;
  struct stat st;
  SDL_Event event;

  while ((opt = getopt(argc, argv, "Xdl:s:t:h?")) != -1) {
    switch(opt) {
	case 'l':
		difficulty = atoi(optarg);
		break;
	case 's':
		seed = atoi(optarg);
		break;
	case 't':
		traffic_log = optarg;
		break;
	case 'd':
		debug = 1;
		break;
	case 'X':
		play_traffic = 0;
		break;
	case 'h':
	case '?':
	default:
		usage(NULL);
		break;
    }
  }

  if (optind >= argc) usage("You must specify at least one can device");

  if(stat(traffic_log, &st) == -1) {
	char msg[256];
	snprintf(msg, 255, "CAN Traffic file not found: %s\n", traffic_log);
	usage(msg);
  }

  /* open socket */
  if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
       perror("socket");
       return 1;
  }

  addr.can_family = AF_CAN;

  strcpy(ifr.ifr_name, argv[optind]);
  if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
       perror("SIOCGIFINDEX");
       return 1;
  }
  addr.can_ifindex = ifr.ifr_ifindex;

  if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES,
                 &enable_canfd, sizeof(enable_canfd))){
       printf("error when enabling CAN FD support\n");
       return 1;
  }

  if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
       perror("bind");
       return 1;
  }

  door_id = DEFAULT_DOOR_ID;
  signal_id = DEFAULT_SIGNAL_ID;
  speed_id = DEFAULT_SPEED_ID;

  if (seed) {
	srand(seed);
        door_id = (rand() % 2046) + 1;
        signal_id = (rand() % 2046) + 1;
        speed_id = (rand() % 2046) + 1;
        door_pos = rand() % 9;
        signal_pos = rand() % 9;
        speed_pos = rand() % 8;
        printf("Seed: %d\n", seed);
	door_len = door_pos + 1;
	signal_len = signal_pos + 1;
	speed_len = speed_len + 2;
  }

  if(difficulty > 0) {
	if (door_len < 8) {
		door_len += rand() % (8 - door_len);
	} else {
		door_len = 0;
	}
	if (signal_len < 8) {
		signal_len += rand() % (8 - signal_len);
	} else {
		signal_len = 0;
	}
	if (speed_len < 8) {
		speed_len += rand() % (8 - speed_len);
	} else {
		speed_len = 0;
	}
  }

  if(play_traffic) {
	signal(SIGALRM,(void (*)(int))kill_child);
	play_id = fork();
	if((int)play_id == -1) {
		printf("Error: Couldn't fork bg player\n");
		exit(-1);
	} else if (play_id != 0) {
		play_can_traffic();
	}
  }

  // GUI Setup
  SDL_Window *window = NULL;
  SDL_Surface *screenSurface = NULL;
  if(SDL_Init ( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ) {
        printf("SDL Could not initializes\n");
        exit(40);
  }
  if( SDL_NumJoysticks() < 1) {
	printf(" Warning: No joysticks connected\n");
  } else {
	if(SDL_IsGameController(0)) {
	  gGameController = SDL_GameControllerOpen(0);
	  if(gGameController == NULL) {
		printf(" Warning: Unable to open game controller. %s\n", SDL_GetError() );
	  } else {
		gJoystick = SDL_GameControllerGetJoystick(gGameController);
		gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
		print_joy_info();
	  }
        } else {
		gJoystick = SDL_JoystickOpen(0);
		if(gJoystick == NULL) {
			printf(" Warning: Could not open joystick\n");
		} else {
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			if (gHaptic == NULL) printf("No Haptic support\n");
			print_joy_info();
		}
	}
  }
  window = SDL_CreateWindow("CANBus Control Panel", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
  if(window == NULL) {
        printf("Window could not be shown\n");
  }
  renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_Surface *image = IMG_Load(get_data("joypad.png"));
  base_texture = SDL_CreateTextureFromSurface(renderer, image);
  SDL_RenderCopy(renderer, base_texture, NULL, NULL);
  SDL_RenderPresent(renderer);
  int button, axis; // Used for checking dynamic joystick mappings

  while(running) {
    while( SDL_PollEvent(&event) != 0 ) {
        switch(event.type) {
            case SDL_QUIT:
                running = 0;
                break;
	    case SDL_WINDOWEVENT:
		switch(event.window.event) {
		case SDL_WINDOWEVENT_ENTER:
		case SDL_WINDOWEVENT_RESIZED:
			redraw_screen();
			break;
		}
	    case SDL_KEYDOWN:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = 1;
			break;
		    case SDLK_LEFT:
			turning = -1;
			break;
		    case SDLK_RIGHT:
			turning = 1;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_a:
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			break;
		    case SDLK_b:
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			break;
		    case SDLK_x:
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			break;
		    case SDLK_y:
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			break;
		}
		kk_check(event.key.keysym.sym);
	   	break;
	    case SDL_KEYUP:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = -1;
			break;
		    case SDLK_LEFT:
		    case SDLK_RIGHT:
			turning = 0;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 0;
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 0;
			break;
		}
		break;
	    case SDL_JOYAXISMOTION:
		axis = event.jaxis.axis;
		if(axis == gAxisLeftH) {
			ud(event.jaxis.value);
		} else if(axis == gAxisLeftV) {
			turn(event.jaxis.value);
		} else if(axis == gAxisR2) {
			accelerate(event.jaxis.value);
		} else if(axis == gAxisRightH ||
			  axis == gAxisRightV ||
			  axis == gAxisL2 ||
			  axis == gJoyX ||
			  axis == gJoyY ||
			  axis == gJoyZ) {
			// Do nothing, the axis is known just not connected
		} else {
			if (debug) printf("Unkown axis: %d\n", event.jaxis.axis);
		}
		break;
	    case SDL_JOYBUTTONDOWN:
                button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonUnlock) {
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonA) {
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			kk_check(SDLK_a);
		} else if (button == gButtonB) {
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			kk_check(SDLK_b);
		} else if (button == gButtonX) {
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			kk_check(SDLK_x);
		} else if (button == gButtonY) {
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			kk_check(SDLK_y);
		} else if (button == gButtonStart) {
			kk_check(SDLK_RETURN);
		} else {
			if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYBUTTONUP:
		button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 0;
		} else if(button == gButtonUnlock) {
			unlock_enabled = 0;
		} else {
			//if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYDEVICEADDED:
		// Only use the first controller
		if(event.cdevice.which == 0) {
			gJoystick = SDL_JoystickOpen(0);
			if(gJoystick) {
				gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
				print_joy_info();
			}
		}
		break;
	    case SDL_JOYDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_JoystickClose(gJoystick);
			gJoystick = NULL;
		}
		break;
	    case SDL_CONTROLLERDEVICEADDED:
		// Only use the first controller
		if(gGameController == NULL) {
			gGameController = SDL_GameControllerOpen(0);
			gJoystick = SDL_GameControllerGetJoystick(gGameController);
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			print_joy_info();
		}
		break;
	    case SDL_CONTROLLERDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_GameControllerClose(gGameController);
			gGameController = NULL;
		}
		break;
        }
    }
    currentTime = SDL_GetTicks();
    checkAccel();
    checkTurn();
    SDL_Delay(5);
  }

  kill_child(SIGKILL);
  close(s);
  SDL_DestroyTexture(base_texture);
  SDL_FreeSurface(image);
  SDL_GameControllerClose(gGameController);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

}
示例#21
0
void
GameEvent(CORE_DATA *cd)
{
	switch (cd->event) {
	case EVENT_START:
		RegisterPlugin(OPENCORE_VERSION, "rabbit", "cycad", "1.0", __DATE__, __TIME__, "A rabbit bot", sizeof(USER_DATA), 0);

		/* set rabbit pid to nobody */
		ud(cd)->rabbit_pid = PID_NONE;

		/* register rabbit command */
		RegisterCommand(COMMAND_RABBIT, "!rabbit", "Rabbit", 2, CMD_PRIVATE, "<name>:<bounty>[:<special>]", "Start the rabbit game", NULL); break;
	case EVENT_LOGIN:
		/* set the bot's location to center */
		SetPosition(16 * 512, 16 * 512, 0, 0);
		break;
	case EVENT_COMMAND:
		switch (cd->cmd_id) {
		case COMMAND_RABBIT: {
			int show_usage = 0;

			PLAYER_ID rpid = ud(cd)->rabbit_pid;

			if (rpid == PID_NONE) {	/* rabbit game is not runnig */
				if (cd->cmd_argc <= 1) {
					show_usage = 1;
				} else {
					char *cmd = cd->cmd_argr[1];
					int nargs = ArgCount(cmd, ':');

					if (nargs != 2 && nargs != 3) {
						show_usage = 1;
					} else {	/* args to command are valid */
						/* copy name out of command */
						char rname[20];
						DelimArgs(rname, sizeof(rname), cmd, 0, ':', 0);

						/* copy bounty out of command */
						int bty = AtoiArg(cmd, 1, ':');

						/* copy special out of command if it was specified */
						int special = 0;
						if (nargs == 3)
							special = AtoiArg(cmd, 2, ':');

						/* find the player specified on the command line */
						PLAYER *rabbit = FindPlayerName(rname, MATCH_HERE | MATCH_PREFIX);
						if (rabbit) {
							/* player found, start the game */
							start_rabbit_game(cd, rabbit, bty, special);
						} else {
							RmtMessageFmt(cd->cmd_name, "Player not found: %s", rname);
						}
					}
				}
			} else {
				/* rabbit game is already running */
				PLAYER *p = FindPlayerPid(rpid, MATCH_HERE);

				RmtMessageFmt(cd->cmd_name, "Rabbit is already running (%s is the rabbit)",
				    p ? p->name : "**UNKNOWN**");
			}

			/* display usage if necessary */
			if (show_usage) RmtMessageFmt(cd->cmd_name, "Usage: %s <name>:<bounty>[:<special>]", cd->cmd_argv[0]);
		}
		default: break;
		}
		break;
	case EVENT_UPDATE:
		if (ud(cd)->rabbit_pid == cd->p1->pid) {	/* if the update is for the rabbit */
			if (cd->p1->status & STATUS_SAFE) {	/* check if the rabbit is in safe */
				/* the rabbit entered safe, end the game */
				ArenaMessageFmt("%s has lost the rabbit game by entering safe!", cd->p1->name);
				ud(cd)->rabbit_pid = PID_NONE;
			}
		}
		break;
	case EVENT_TIMER:
		if (ud(cd)->rabbit_pid != PID_NONE) {	/* if the rabbit game is running */
			/* find the rabbit */
			PLAYER *p = FindPlayerPid(ud(cd)->rabbit_pid, MATCH_HERE);
			if (p) {
				if (ud(cd)->where_timer == cd->timer_id) {
					/* a *where timer expired, send the next one and look for response */
					PrivMessage(p, "*where");
					ud(cd)->expecting_where = 1;
				} else if (ud(cd)->gameover_timer == cd->timer_id) {
					/* the game over timer expired, the rabbit didnt die and he won */
					ArenaMessageFmt("%s wins the rabbit game by staying alive!", p->name);
					ud(cd)->rabbit_pid = PID_NONE;
				}
			} else {
				/* rabbit not found, this should never happen! */
			}
		}
	case EVENT_MESSAGE:
		/*
		 * Only look for a response of the game is running, the bot is expecting *where,
		 * and the message type is an arena message.
		 */
		if (ud(cd)->rabbit_pid != PID_NONE && ud(cd)->expecting_where && 
		    cd->msg_type == MSG_ARENA) {
			/* message is a possible *where response */

			/* find the rabbit */
			PLAYER *p = FindPlayerPid(ud(cd)->rabbit_pid, MATCH_HERE);
			if (p) {
				char where_prefix[32];
				snprintf(where_prefix, 32, "%s: ", p->name);
				where_prefix[32 - 1] = '\0';

				/*
				 * Verify that this is *where output by looking for "rabbit: " at the
				 * beginning of the string.
				 */
				if (strncasecmp(where_prefix, cd->msg, strlen(where_prefix)) == 0) {
					/* this must be a *where response, process it */
					char loc[4];
					snprintf(loc, 4, "%s", &cd->msg[strlen(where_prefix)]);
					loc[4 - 1] = '\0';

					/* announce the rabbits location */
					ArenaMessageFmt(">>> Rabbit %s is at %-3s <<<", p->name, loc);

					/* set the next *where timer */
					ud(cd)->where_timer = SetTimer(30 * 1000, 0, 0);

					/*
					 * The bot wont be looking for *where responses until the
					 * next time it sends the command, so turn parsing off
					 * for now.
					 */
					ud(cd)->expecting_where = 0;
				}
			}
		}
		break;
	case EVENT_KILL:
		if (cd->p1->pid == ud(cd)->rabbit_pid) {
			/* the rabbit died */
			ArenaMessageFmt("%s wins the rabbit game by killing Rabbit %s!", cd->p2->name, cd->p1->name);
			ud(cd)->rabbit_pid = PID_NONE;
		}
		break;
	case EVENT_LEAVE:
		if (ud(cd)->rabbit_pid == cd->p1->pid) {
			/* the rabbit left */
			ArenaMessageFmt("%s has lost the rabbit game by leaving the arena!", cd->p1->name);
			ud(cd)->rabbit_pid = PID_NONE;
		}
		break;
	case EVENT_CHANGE:
		if (ud(cd)->rabbit_pid == cd->p1->pid) {
			/* the rabbit changed ship */
			ArenaMessageFmt("%s has lost the rabbit game by changing ship/freq!", cd->p1->name);
			ud(cd)->rabbit_pid = PID_NONE;
		}
		break;
	}
}
示例#22
0
f32 rand_flt(f32 min = 0.f, f32 max = 1.f)
{
	std::uniform_real_distribution<f32> ud(min, max);
	return ud(s_rng);
}
示例#23
0
         bool passwordAuth::read(std::map<std::string, userData> & _dest)
         {
            bool status = false;

            // Open file for reading.
            std::ifstream file;

#if HAVE_IOS_BASE
            file.open(filename_.c_str(), std::ios_base::in);
#else
            file.open(filename_.c_str(), std::ios::in);
#endif

            if (!file.is_open())
               {
                  return status;
               }

            status = true;

            std::string input;
            t_strList separated;

            while (!file.eof())
               {
                  getline(file, input);

                  if ((input.size() > 0) && (input[0] != commentChr))
                     {
                        separated = btg::core::Util::splitLine(input, ":");
                        if (separated.size() == 8)
                           {
                              std::string username    = separated[0];
                              std::string passwd_hash = separated[1];
                              std::string temp_dir    = separated[2];
                              std::string work_dir    = separated[3];
                              std::string seed_dir    = separated[4];
                              std::string dest_dir    = separated[5];

                              bool control_flag        = false;
                              if (separated[6] == "1")
                                 {
                                    control_flag = true;
                                 }

                              std::string callback    = separated[7];
#if BTG_AUTH_DEBUG
                              BTG_MNOTICE(logWrapper(),
                                          "read: username '" << username    << "', " <<
                                          "hash     '" << passwd_hash << "', " <<
                                          "temp_dir '" << temp_dir    << "', " <<
                                          "work_dir '" << work_dir    << "', " <<
                                          "seed_dir '" << seed_dir    << "', " <<
                                          "dest_dir '" << dest_dir    << "', " <<
                                          "control_flag '" << control_flag    << "', " <<
                                          "callback '" << callback << "'");
#endif // BTG_AUTH_DEBUG
                              userData ud(passwd_hash, temp_dir, work_dir, seed_dir, dest_dir, control_flag, callback);
                              MVERBOSE_LOG(logWrapper(), verbose_, "Adding user '" << username << "'.");
                              std::pair<std::string, userData> p(username, ud);
                              _dest.insert(p);
                           }
                     }
               }

            file.close();

            if (_dest.size() == 0)
               {
#if BTG_AUTH_DEBUG
                  BTG_MNOTICE(logWrapper(), "no users");
#endif // BTG_AUTH_DEBUG
                  status = false;
               }

            return status;
         }
示例#24
0
ezQtShortcutEditorDlg::ezQtShortcutEditorDlg(QWidget* parent)
    : QDialog(parent)
{
  setupUi(this);

  EZ_VERIFY(connect(Shortcuts, SIGNAL(itemSelectionChanged()), this, SLOT(SlotSelectionChanged())) != nullptr,
            "signal/slot connection failed");

  m_iSelectedAction = -1;
  KeyEditor->setEnabled(false);

  ezMap<ezString, ezMap<ezString, ezInt32>> SortedItems;

  {
    auto itActions = ezActionManager::GetActionIterator();

    while (itActions.IsValid())
    {
      if (itActions.Value()->m_Type == ezActionType::Action)
      {
        SortedItems[itActions.Value()->m_sCategoryPath][itActions.Value()->m_sActionName] = m_ActionDescs.GetCount();
        m_ActionDescs.PushBack(itActions.Value());
      }

      itActions.Next();
    }
  }

  {
    ezQtScopedBlockSignals bs(Shortcuts);
    ezQtScopedUpdatesDisabled ud(Shortcuts);

    Shortcuts->setAlternatingRowColors(true);
    Shortcuts->setEditTriggers(QAbstractItemView::EditTrigger::NoEditTriggers);
    Shortcuts->setExpandsOnDoubleClick(true);

    ezStringBuilder sTemp;

    for (auto it = SortedItems.GetIterator(); it.IsValid(); ++it)
    {
      auto pParent = new QTreeWidgetItem();
      pParent->setData(0, Qt::DisplayRole, it.Key().GetData());
      Shortcuts->addTopLevelItem(pParent);

      pParent->setExpanded(true);
      pParent->setFirstColumnSpanned(true);
      pParent->setFlags(Qt::ItemFlag::ItemIsEnabled);

      QFont font = pParent->font(0);
      font.setBold(true);

      pParent->setFont(0, font);

      for (auto it2 : it.Value())
      {
        const auto& item = m_ActionDescs[it2.Value()];
        auto pItem = new QTreeWidgetItem(pParent);

        /// \todo Instead of removing &, replace it by underlined text (requires formatted text output)
        sTemp = ezTranslate(item->m_sActionName);
        sTemp.ReplaceAll("&", "");

        pItem->setData(0, Qt::UserRole, it2.Value());
        pItem->setData(0, Qt::DisplayRole, item->m_sActionName.GetData());
        pItem->setData(1, Qt::DisplayRole, sTemp.GetData());
        pItem->setData(2, Qt::DisplayRole, item->m_sShortcut.GetData());
        pItem->setData(3, Qt::DisplayRole, ezTranslateTooltip(item->m_sActionName));

        if (item->m_sShortcut == item->m_sDefaultShortcut)
          pItem->setBackground(2, QBrush());
        else
          pItem->setBackgroundColor(2, Qt::darkYellow);

        sTemp.Set("Default: ", item->m_sDefaultShortcut.IsEmpty() ? "<none>" : item->m_sDefaultShortcut);

        pItem->setToolTip(2, QString::fromUtf8(sTemp.GetData()));
      }
    }

    Shortcuts->resizeColumnToContents(0);
    Shortcuts->resizeColumnToContents(2);
  }

  ButtonAssign->setEnabled(false);
  ButtonRemove->setEnabled(false);
  ButtonReset->setEnabled(false);
}
void mtsTeleOperationECM::RunEnabled(void)
{
    if (mIsClutched) {
        return;
    }

    /* --- Forces on MTMs --- */
    const vct3 frictionForceCoeff(-10.0, -10.0, -40.0);
    const double distanceForceCoeff = 150.0;

    //-1- vector between MTMs
    vct3 vectorLR;
    vectorLR.DifferenceOf(mMTMR.PositionCartesianCurrent.Position().Translation(),
                          mMTML.PositionCartesianCurrent.Position().Translation());
    // -2- mid-point, aka center of image
    vct3 c;
    c.SumOf(mMTMR.PositionCartesianCurrent.Position().Translation(),
            mMTML.PositionCartesianCurrent.Position().Translation());
    c.Multiply(0.5);
    vct3 directionC = c.Normalized();
    // -3- image up vector
    vct3 up;
    up.CrossProductOf(vectorLR, c);
    up.NormalizedSelf();
    // -4- Width of image
    vct3 side;
    side.CrossProductOf(c, up);
    side.NormalizedSelf();
    // -5- find desired position for L and R
    vct3 goalL(c);
    goalL.AddProductOf(-mInitial.w, side);
    goalL.AddProductOf(-mInitial.d, directionC);
    vct3 goalR(c);
    goalR.AddProductOf(mInitial.w, side);
    goalR.AddProductOf(mInitial.d, directionC);


    // compute forces on L and R based on error in position
    vct3 forceFriction;
    vct3 force;
    prmForceCartesianSet wrenchR, wrenchL;

    // MTMR
    // apply force
    force.DifferenceOf(goalR,
                       mMTMR.PositionCartesianCurrent.Position().Translation());
    force.Multiply(distanceForceCoeff);
    wrenchR.Force().Ref<3>(0).Assign(force);
    // add friction force
    forceFriction.ElementwiseProductOf(frictionForceCoeff,
                                       mMTMR.VelocityCartesianCurrent.VelocityLinear());
    wrenchR.Force().Ref<3>(0).Add(forceFriction);
    // apply
    mMTMR.SetWrenchBody(wrenchR);

    // MTML
    // apply force
    force.DifferenceOf(goalL,
                       mMTML.PositionCartesianCurrent.Position().Translation());
    force.Multiply(distanceForceCoeff);
    wrenchL.Force().Ref<3>(0).Assign(force);
    // add friction force
    forceFriction.ElementwiseProductOf(frictionForceCoeff,
                                       mMTML.VelocityCartesianCurrent.VelocityLinear());
    wrenchL.Force().Ref<3>(0).Add(forceFriction);
    // apply
    mMTML.SetWrenchBody(wrenchL);

    /* --- Joint Control --- */
    static const vct3 normXZ(0.0, 1.0, 0.0);
    static const vct3 normYZ(1.0, 0.0, 0.0);
    static const vct3 normXY(0.0, 0.0, 1.0);
    // Initial ECM joints
    vctVec goalJoints(mInitial.ECMPositionJoint);
    // Change in directions and joints
    vctVec changeJoints(4);
    vctVec changeDir(4);
    vct3 crossN;  // normal to direction of motion

    // - Direction 0 - left/right, movement in the XZ plane
    vct3  lr(c[0], 0.0, c[2]);
    lr.NormalizedSelf();
    if (mInitial.Lr.AlmostEqual(lr)) {
        changeDir[0] = 0.0;
    } else {
        changeDir[0] = -acos(vctDotProduct(mInitial.Lr, lr));
        crossN = vctCrossProduct(mInitial.Lr, lr);
        if (vctDotProduct(normXZ, crossN) < 0.0) {
            changeDir[0] = -changeDir[0];
        }
    }

    // - Direction 1 - up/down, movement in the YZ plane
    vct3  ud(0.0, c[1], c[2]);
    ud.NormalizedSelf();
    if (mInitial.Ud.AlmostEqual(ud)) {
        changeDir[1] = 0.0;
    } else {
        changeDir[1] = acos(vctDotProduct(mInitial.Ud, ud));
        crossN = vctCrossProduct(mInitial.Ud, ud);
        if (vctDotProduct(normYZ, crossN) < 0.0) {
            changeDir[1] = -changeDir[1];
        }
    }

    // - Direction 2 - in/out
    changeDir[2] = mScale * (mInitial.C.Norm() - c.Norm());

    // - Direction 3 - cc/ccw, movement in the XY plane
    vct3 cw(up[0], up[1], 0);
    cw.NormalizedSelf();
    if (mInitial.Cw.AlmostEqual(cw)) {
        changeDir[3] = 0.0;
    } else {
        changeDir[3] = -acos(vctDotProduct(mInitial.Cw, cw));
        crossN = vctCrossProduct(mInitial.Cw, cw);
        if (vctDotProduct(normXY, crossN) < 0) {
            changeDir[3] = -changeDir[3];
        }
    }

    // adjusting movement for camera orientation
    double totalChangeJoint3 = changeDir[3] + mInitial.ECMPositionJoint[3];
    changeJoints[0] = changeDir[0] * cos(totalChangeJoint3) - changeDir[1] * sin(totalChangeJoint3);
    changeJoints[1] = changeDir[1] * cos(totalChangeJoint3) + changeDir[0] * sin(totalChangeJoint3);
    changeJoints[2] = changeDir[2];
    changeJoints[3] = changeDir[3];

    goalJoints.Add(changeJoints);
    mECM.PositionJointSet.Goal().ForceAssign(goalJoints);
    mECM.SetPositionJoint(mECM.PositionJointSet);

    /* --- Lock Orientation --- */

    //Calculate new rotations of MTMs
    vctMatRot3 currMTMLRot;
    vctMatRot3 currMTMRRot;
    // Current ECM Rotation
    vctEulerZYXRotation3 finalEulerAngles;
    vctMatrixRotation3<double> currECMRot;
    vctMatrixRotation3<double> finalECMRot;

    finalEulerAngles.Assign(goalJoints[3], goalJoints[0], goalJoints[1]);
    vctEulerToMatrixRotation3(finalEulerAngles, finalECMRot);
    currECMRot = finalECMRot * mInitial.ECMRotEuler.Inverse();

    // Set MTM Orientation
    currMTMLRot = currECMRot.Inverse() * mInitial.MTMLRot;
    currMTMRRot = currECMRot.Inverse() * mInitial.MTMRRot;

    // set cartesian effort parameters
    mMTML.SetWrenchBodyOrientationAbsolute(true);
    mMTML.LockOrientation(currMTMLRot);
    mMTMR.SetWrenchBodyOrientationAbsolute(true);
    mMTMR.LockOrientation(currMTMRRot);
}
示例#26
0
    std::shared_ptr<Buffer>
    AudioMixer::resample(const uint8_t* const buffer,
                         size_t size,
                         AudioBufferMetadata& metadata)
    {
        const auto inFrequncyInHz = metadata.getData<kAudioMetadataFrequencyInHz>();
        const auto inBitsPerChannel = metadata.getData<kAudioMetadataBitsPerChannel>();
        const auto inChannelCount = metadata.getData<kAudioMetadataChannelCount>();
        const auto inFlags = metadata.getData<kAudioMetadataFlags>();
        const auto inBytesPerFrame = metadata.getData<kAudioMetadataBytesPerFrame>();
        const auto inNumberFrames = metadata.getData<kAudioMetadataNumberFrames>();
        const auto inUsesOSStruct = metadata.getData<kAudioMetadataUsesOSStruct>();
        
        if(m_outFrequencyInHz == inFrequncyInHz &&
           m_outBitsPerChannel == inBitsPerChannel &&
           m_outChannelCount == inChannelCount
           && !(inFlags & kAudioFormatFlagIsNonInterleaved)
           && !(inFlags & kAudioFormatFlagIsFloat))
        {
            // No resampling necessary
            return std::make_shared<Buffer>();
        }
        
        uint64_t hash = uint64_t(inBytesPerFrame&0xFF) << 56 | uint64_t(inFlags&0xFF) << 48 | uint64_t(inChannelCount&0xFF) << 40
                        | uint64_t(inBitsPerChannel&0xFF) << 32 | inFrequncyInHz;
        
        auto it = m_converters.find(hash) ;
        ConverterInst converter = {0};
        
        if(it == m_converters.end()) {
            AudioStreamBasicDescription in = {0};
            AudioStreamBasicDescription out = {0};
            
            in.mFormatID = kAudioFormatLinearPCM;
            in.mFormatFlags =  inFlags;
            in.mChannelsPerFrame = inChannelCount;
            in.mSampleRate = inFrequncyInHz;
            in.mBitsPerChannel = inBitsPerChannel;
            in.mBytesPerFrame = inBytesPerFrame;
            in.mFramesPerPacket = 1;
            in.mBytesPerPacket = in.mBytesPerFrame * in.mFramesPerPacket;
            
            out.mFormatID = kAudioFormatLinearPCM;
            out.mFormatFlags =  kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
            out.mChannelsPerFrame = m_outChannelCount;
            out.mSampleRate = m_outFrequencyInHz;
            out.mBitsPerChannel = m_outBitsPerChannel;
            out.mBytesPerFrame = (out.mBitsPerChannel * out.mChannelsPerFrame) / 8;
            out.mFramesPerPacket = 1;
            out.mBytesPerPacket = out.mBytesPerFrame * out.mFramesPerPacket;
            
            converter.asbdIn = in;
            converter.asbdOut = out;
            
            OSStatus ret = AudioConverterNew(&in, &out, &converter.converter);
            
            AudioConverterSetProperty(converter.converter,
                                      kAudioConverterSampleRateConverterComplexity,
                                      sizeof(s_samplingRateConverterComplexity),
                                      &s_samplingRateConverterComplexity);
            
            AudioConverterSetProperty(converter.converter,
                                      kAudioConverterSampleRateConverterQuality,
                                      sizeof(s_samplingRateConverterQuality),
                                      &s_samplingRateConverterQuality);
        
            auto prime = kConverterPrimeMethod_None;
            
            AudioConverterSetProperty(converter.converter,
                                      kAudioConverterPrimeMethod,
                                      sizeof(prime),
                                      &prime);
            
            m_converters[hash] = converter;
            
            if(ret != noErr) {
                DLog("ret = %d (%x)", (int)ret, (unsigned)ret);
            }
            
        } else {
            converter = it->second;
        }
        
        auto & in = converter.asbdIn;
        auto & out = converter.asbdOut;

        const double inSampleCount = inNumberFrames;
        const double ratio = static_cast<double>(inFrequncyInHz) / static_cast<double>(m_outFrequencyInHz);
        
        const double outBufferSampleCount = std::round(double(inSampleCount) / ratio);
        
        const size_t outBufferSize = out.mBytesPerPacket * outBufferSampleCount;
        const auto outBuffer = std::make_shared<Buffer>(outBufferSize);
        
        
        std::unique_ptr<UserData> ud(new UserData());
        ud->size = static_cast<int>(size);
        ud->data = const_cast<uint8_t*>(buffer);
        ud->p = inUsesOSStruct ? 0 : ud->data;
        ud->packetSize = in.mBytesPerPacket;
        ud->numberPackets = inSampleCount;
        ud->numChannels = inChannelCount;
        ud->isInterleaved = !(inFlags & kAudioFormatFlagIsNonInterleaved);
        ud->usesOSStruct = inUsesOSStruct;
        
        AudioBufferList outBufferList;
        outBufferList.mNumberBuffers = 1;
        outBufferList.mBuffers[0].mDataByteSize = static_cast<UInt32>(outBufferSize);
        outBufferList.mBuffers[0].mNumberChannels = m_outChannelCount;
        outBufferList.mBuffers[0].mData = (*outBuffer)();
        
        UInt32 sampleCount = outBufferSampleCount;
        OSStatus ret = AudioConverterFillComplexBuffer(converter.converter, /* AudioConverterRef inAudioConverter */
                                        AudioMixer::ioProc, /* AudioConverterComplexInputDataProc inInputDataProc */
                                        ud.get(), /* void *inInputDataProcUserData */
                                        &sampleCount, /* UInt32 *ioOutputDataPacketSize */
                                        &outBufferList, /* AudioBufferList *outOutputData */
                                        NULL /* AudioStreamPacketDescription *outPacketDescription */
                                        );
        if(ret != noErr) {
            DLog("ret = %d (%x)", (int)ret, (unsigned)ret);
        }
      
        outBuffer->setSize(outBufferList.mBuffers[0].mDataByteSize);
        return outBuffer;
    }