Example #1
0
//===========================================================================
int main ()
{
    {
        //------------------------------------------------------
        // Test: Construct with 0
        // Setup fixture

        // Test 
        bigint bi(0);

        // Verify
        assert(bi == 0);
    }

    {
        //------------------------------------------------------
        // Test: Construct with 1
        // Setup fixture

        // Test 
        bigint bi(1);

        // Verify
        assert(bi == 1);
    }

    {
        //------------------------------------------------------
        // Test: Construct with two-digit value
        // Setup fixture

        // Test 
        bigint bi(27);

        // Verify
        assert(bi == 27);
    }

    {
        //------------------------------------------------------
        // Test: Construct with six-digit value
        // Setup fixture

        // Test 
        bigint bi(456789);

        // Verify
        assert(bi == 456789);
    }

}
Example #2
0
int calc_dist( const scrypt::sha1& d ) {
  scrypt::bigint bi((char*)d.hash, sizeof(d.hash));
  scrypt::sha1   mx; memset( mx.hash,0xff,sizeof(mx.hash));
  scrypt::bigint max((char*)mx.hash,sizeof(mx.hash));

  return ((bi * scrypt::bigint( 1000 )) / max).to_int64();
}
Example #3
0
/// \brief Begins channel browsing.
/// \note This may only be called from the UI thread.
bool TVBrowseHelper::BrowseStart(PlayerContext *ctx, bool skip_browse)
{
    if (!gCoreContext->IsUIThread())
        return false;

    QMutexLocker locker(&m_lock);

    if (m_ctx)
        return m_ctx == ctx;

    m_tv->ClearOSD(ctx);

    ctx->LockPlayingInfo(__FILE__, __LINE__);
    if (ctx->playingInfo)
    {
        m_ctx       = ctx;
        m_channum   = ctx->playingInfo->GetChanNum();
        m_chanid    = ctx->playingInfo->GetChanID();
        m_starttime = ctx->playingInfo->GetScheduledStartTime(MythDate::ISODate);
        ctx->UnlockPlayingInfo(__FILE__, __LINE__);

        if (!skip_browse)
        {
            BrowseInfo bi(BROWSE_SAME, m_channum, m_chanid, m_starttime);
            locker.unlock();
            BrowseDispInfo(ctx, bi);
        }
        return true;
    }
    else
    {
        ctx->UnlockPlayingInfo(__FILE__, __LINE__);
        return false;
    }
}
bool CAICallback::CanBuildAt(const UnitDef* unitDef, float3 pos, int facing)
{
	CFeature* f;
	BuildInfo bi(unitDef, pos, facing);
	bi.pos=helper->Pos2BuildPos (bi);
	return !!uh->TestUnitBuildSquare(bi,f,gs->AllyTeam(team));
}
Example #5
0
void CUnitLoader::FlattenGround(const CUnit* unit)
{
    const UnitDef* unitDef = unit->unitDef;
    const float groundheight = ground->GetHeightReal(unit->pos.x, unit->pos.z);

    if (mapDamage->disabled) return;
    if (!unitDef->levelGround) return;
    if (!unitDef->IsImmobileUnit()) return;
    if (unitDef->floatOnWater && groundheight <= 0.0f) return;

    // if we are float-capable, only flatten
    // if the terrain here is above sea level
    BuildInfo bi(unitDef, unit->pos, unit->buildFacing);
    bi.pos = CGameHelper::Pos2BuildPos(bi, true);

    const float hss = 0.5f * SQUARE_SIZE;
    const int tx1 = (int) std::max(0.0f ,(bi.pos.x - (bi.GetXSize() * hss)) / SQUARE_SIZE);
    const int tz1 = (int) std::max(0.0f ,(bi.pos.z - (bi.GetZSize() * hss)) / SQUARE_SIZE);
    const int tx2 = std::min(gs->mapx, tx1 + bi.GetXSize());
    const int tz2 = std::min(gs->mapy, tz1 + bi.GetZSize());

    for (int z = tz1; z <= tz2; z++) {
        for (int x = tx1; x <= tx2; x++) {
            readMap->SetHeight(z * gs->mapxp1 + x, bi.pos.y);
        }
    }

    mapDamage->RecalcArea(tx1, tx2, tz1, tz2);
}
Example #6
0
void THierarchicalCluster::permute(const TIntList &neworder)
{
  if ((!branches && neworder.size()) || (branches->size() != neworder.size()))
    raiseError("the number of clusters does not match the lenght of the permutation vector");

  int *temp = new int [last - first], *t = temp;
  TIntList::const_iterator pi = neworder.begin();
  THierarchicalClusterList::iterator bi(branches->begin()), be(branches->end());
  THierarchicalClusterList newBranches;

  for(; bi != be; bi++, pi++) {
    PHierarchicalCluster branch = branches->at(*pi);
    newBranches.push_back(branch);
    TIntList::const_iterator bei(mapping->begin() + branch->first), bee(mapping->begin() + branch->last);
    const int offset = (t - temp) - (branch->first - first);
    for(; bei != bee; *t++ = *bei++);
    if (offset)
      branch->recursiveMove(offset);
  }

  TIntList::iterator bei(mapping->begin() + first), bee(mapping->begin() + last);
  for(t = temp; bei!=bee; *bei++ = *t++);

  bi = branches->begin();
  THierarchicalClusterList::const_iterator nbi(newBranches.begin());
  for(; bi != be; *bi++ = *nbi++);
}
Example #7
0
bool CAICallback::CanBuildAt(const UnitDef* unitDef, const float3& pos, int facing)
{
	CFeature* blockingF = NULL;
	BuildInfo bi(unitDef, pos, facing);
	bi.pos = CGameHelper::Pos2BuildPos(bi, false);
	return !!CGameHelper::TestUnitBuildSquare(bi, blockingF, teamHandler->AllyTeam(team), false);
}
Example #8
0
void CUnitLoader::FlattenGround(const CUnit* unit)
{
	const UnitDef* unitDef = unit->unitDef;
	const float groundheight = ground->GetHeight2(unit->pos.x, unit->pos.z);

	if (!mapDamage->disabled && unitDef->levelGround &&
		!(unitDef->floater && groundheight <= 0) &&
		!(unitDef->canmove && (unitDef->speed > 0.0f))) {
		// if we are float-capable, only flatten
		// if the terrain here is above sea level

		BuildInfo bi(unitDef, unit->pos, unit->buildFacing);
		bi.pos = helper->Pos2BuildPos(bi);
		const float hss = 0.5f * SQUARE_SIZE;
		const int tx1 = (int) std::max(0.0f ,(bi.pos.x - (bi.GetXSize() * hss)) / SQUARE_SIZE);
		const int tz1 = (int) std::max(0.0f ,(bi.pos.z - (bi.GetZSize() * hss)) / SQUARE_SIZE);
		const int tx2 = std::min(gs->mapx, tx1 + bi.GetXSize());
		const int tz2 = std::min(gs->mapy, tz1 + bi.GetZSize());

		for (int z = tz1; z <= tz2; z++) {
			for (int x = tx1; x <= tx2; x++) {
				readmap->SetHeight(z * (gs->mapx + 1) + x, bi.pos.y);
			}
		}

		mapDamage->RecalcArea(tx1, tx2, tz1, tz2);
	}
}
Example #9
0
 asset  asset::operator *  ( const fc::uint128_t& fix6464 )const
 {
     fc::bigint bi(amount);
     bi *= fix6464;
     bi >>= 64;
     return asset( fc::uint128(bi), unit );
 }
Example #10
0
int main()
{
    Blob<int> bi({2,3,4,5,6,6});
    blob_ptr<int> p(bi,3);
    std::cout << *p << std::endl;
    return 0;
}
void BatteryStatus::fireEvents() {
    int fullCount = 0;
    bool isPlugged = false;

    int remaining = 0, total = 0;
    for (int i = 0; i < _batteryInfo.batteryCount(); i++) {
        QBatteryInfo bi(i);

        if (bi.isValid()) {
          isPlugged = (bi.chargingState() == QBatteryInfo::Charging) || isPlugged;
          fullCount += bi.chargingState() == QBatteryInfo::LevelFull;

          remaining += bi.remainingCapacity();
          total += bi.maximumCapacity();
        }
    }

    isPlugged = isPlugged || (_batteryInfo.batteryCount() == fullCount);

    if (_scId) {
        QVariantMap obj;
        obj.insert("isPlugged", (int)isPlugged);
        if (total != 0)
          obj.insert("level", remaining * 100 / total);
        else
          obj.insert("level", 100);

        this->callbackWithoutRemove(_scId, CordovaInternal::format(obj));
    }
}
// OVS-2204: there were errors even on retry with a new connection which actually
// should have succeeded - try to get to the bottom of that
TEST_F(BackendInterfaceTest, retry_on_error)
{
    const std::string oname("some-object");
    const fs::path opath(path_ / oname);

    const yt::CheckSum cs(createTestFile(opath,
                                         4096,
                                         "some pattern"));

    yt::CheckSum wrong_cs(1);

    ASSERT_NE(wrong_cs,
              cs);

    std::unique_ptr<be::BackendTestSetup::WithRandomNamespace>
        nspace(make_random_namespace());

    const size_t retries = 7;
    ASSERT_LE(retries,
              cm_->capacity());

    be::BackendInterfacePtr bi(cm_->newBackendInterface(nspace->ns(),
                                                        retries));

    ASSERT_THROW(bi->write(opath,
                           oname,
                           OverwriteObject::F,
                           &wrong_cs),
                 be::BackendInputException);

    ASSERT_EQ(retries + 1,
              cm_->size());
}
Example #13
0
std::string JtagShiftedData::GetDecimalString(const std::vector<U8>& bits)
{
	std::string ret_val("0");
	std::vector<U8>::const_iterator bi(bits.begin());
	int carry, digit;
	while (bi != bits.end())
	{
		carry = *bi ? 1 : 0;		

		// multiply ret_val by 2 and add the carry bit
		std::string::reverse_iterator ai(ret_val.rbegin());
		while (ai != ret_val.rend())
		{
			digit = (*ai - '0') * 2 + carry;
			*ai = (digit % 10) + '0';
			carry = digit / 10;

			++ai;
		}

		if (carry > 0)
			ret_val = char(carry + '0') + ret_val;

		++bi;
	}

	return ret_val;
}
Example #14
0
bool BundleManager::InstallBundle() {
	wxASSERT(m_currentBundle);

	// Create temp dir
	wxString tempDir = wxStandardPaths::Get().GetTempDir();
	tempDir += wxFILE_SEP_PATH + m_currentBundle->m_name;
	if (wxDirExists(tempDir)) {
		// Delete old first
		DelTree(tempDir);
	}
	wxMkdir(tempDir);

	// Show progress dialog
	wxProgressDialog dlg(_("Downloading..."), m_currentBundle->m_name, 200, this, wxPD_AUTO_HIDE|wxPD_APP_MODAL);

	// Download bundle
	const wxString& repoUrl = GetCurrentRepoUrl();
	const wxString url = repoUrl + m_currentBundle->m_name + wxT('/');
	wxFileName path(tempDir, wxEmptyString);
	if (!DownloadDir(url, path, dlg)) {
		DelTree(tempDir); // clean up
		return false;
	}

	// Set modDate to match repo
	// Windows does not support changing dates on directories under FAT so
	// to make sure it works we set the date on info.plist instead
	path.SetFullName(wxT("info.plist"));
	path.SetTimes(NULL, &m_currentBundle->m_modDate, NULL);

	// Delete installed version (if any)
	wxString installPath = dynamic_cast<IAppPaths*>(wxTheApp)->GetAppDataPath() + wxT("InstalledBundles") + wxFILE_SEP_PATH;
	if (!wxDirExists(installPath)) wxMkdir(installPath);
	installPath += m_currentBundle->m_name;
	if (wxDirExists(installPath)) DelTree(installPath);

	// Move bundle to install dir
	wxRenameFile(tempDir, installPath);

	// Update list
	bool inList = false;
	for (vector<cxBundleInfo>::iterator p = m_installedBundles.begin(); p != m_installedBundles.end(); ++p) {
		if (p->dirName == m_currentBundle->m_name) {
			p->modDate = m_currentBundle->m_modDate;
			inList = true;
			break;
		}
	}
	if (!inList) {
		cxBundleInfo bi(-1, m_currentBundle->m_name, m_currentBundle->m_modDate);
		m_installedBundles.push_back(bi);
	}

	// Update the UI
	m_bundleList->SetItemImage(m_currentSel, 1); // up-to-date image
	SelectItem(m_currentSel, true);

	m_needBundleReload = true;
	return true;
}
Example #15
0
//找最大的团并返回外轮廓
std::vector<MYPOINT> FindBiggestContour(cimg_library::CImg<unsigned char> origin, std::vector<MYPOINT> Points)
{
	std::vector<MYPOINT> contour;
	cimg_library::CImg<unsigned char> mask;
	//compute the binary img
	int threshold = otsu(origin, Points, mask, 1);
	unsigned char *bi_img = new unsigned char[origin.width()*origin.height()];
	for (int i = 0; i < origin.height(); i++){
		for (int j = 0; j < origin.width(); j++){
			if (origin.atXY(j, i) >= threshold && mask.atXY(j, i) == 255)
				bi_img[i*origin.width() + j] = 255;
			else
				bi_img[i*origin.width() + j] = 0;
		}
	}
	//返回二值图像
	cimg_library::CImg<unsigned char> bi(bi_img, origin.width(), origin.height());
	//done
	
	//找团
	std::vector<int> stRun, enRun, rowRun, masRun;
	int NumberofRuns = 0, offset = 1, maxRun = 1;
	fillRunVector(bi, NumberofRuns, stRun, enRun, rowRun, masRun);
	std::vector<int> runLabels;
	std::vector<std::pair<int, int>> equivalences;
	firstPass(stRun, enRun, rowRun, NumberofRuns, runLabels, equivalences, offset);
	if (!NumberofRuns){
		std::cout << "NOTHING FOUND!!!" << std::endl 
			<<"size of contour is: "<< contour.size() <<  std::endl;
		return contour;
	}
	replaceSameLabel(runLabels, equivalences);

	int maxLabel = *max_element(runLabels.begin(), runLabels.end());
	int *MassofRuns = new int[maxLabel + 1];
	memset(MassofRuns, 0, (maxLabel + 1)*sizeof(int));

	memset(bi_img, 0, (bi.height()*bi.width())*sizeof(unsigned char));
	for (int c = 0; c < NumberofRuns; c++){
		MassofRuns[runLabels[c]] += masRun[c];
		if (MassofRuns[runLabels[c]]>maxRun){
			maxRun = MassofRuns[runLabels[c]];
			maxLabel = runLabels[c];
		}
		int i = rowRun[c]; 
		for (int j = stRun[c]; j <= enRun[c]; j++){
			bi_img[i*bi.width() + j] = runLabels[c];
		}
	}
	for (int i = 0; i < bi.height(); i++)
	for (int j = 0; j < bi.width(); j++) {
		if (bi_img[i*bi.width()+j] == maxLabel)
			bi_img[i*bi.width() + j] = 255;
		else
			bi_img[i*bi.width() + j] = 0;
	}

	return FindContour(bi_img, bi.width(), bi.height());
}
// This is not too interesting either; it's mainly a debugging / testing help
TEST_F(BackendObjectTest, cache_invalidation)
{
    const std::string oname("some-object");
    const fs::path src(path_ / (oname + ".src"));
    const fs::path dst(path_ / (oname + ".dst"));
    const size_t size = 1ULL << 20;

    BackendInterfacePtr bi(bi_(nspace_->ns()));

    const std::string pattern1("some pattern");

    const yt::CheckSum chksum1(createPutAndVerify(src,
                                                  size,
                                                  pattern1,
                                                  cm_,
                                                  oname,
                                                  nspace_->ns(),
                                                  OverwriteObject::F));

    auto check([&](const std::string& pattern,
                   const yt::CheckSum& chksum,
                   InsistOnLatestVersion insist)
               {
                   bi->read(dst,
                            oname,
                            insist);

                   ALWAYS_CLEANUP_FILE(dst);

                   EXPECT_TRUE(verifyTestFile(dst,
                                              size,
                                              pattern,
                                              &chksum));
               });

    check(pattern1,
          chksum1,
          InsistOnLatestVersion::F);

    const std::string pattern2("some other pattern");

    const yt::CheckSum chksum2(createAndPut(src,
                                            size,
                                            pattern2,
                                            cm_,
                                            oname,
                                            nspace_->ns(),
                                            OverwriteObject::T));

    check(pattern2,
          chksum2,
          InsistOnLatestVersion::T);

    bi->invalidate_cache();

    check(pattern2,
          chksum2,
          InsistOnLatestVersion::F);
}
Example #17
0
bool divDot(const string &name, string &before, string &after)
{ string::const_iterator bi(name.begin()), ei(name.end());
  for(; (ei!=bi) && (*(--ei)!='.'); );
  if (*ei!='.') return false;
  
  before=string(bi, ei); after=string(ei++, name.end());
  return true;
}
Example #18
0
//#define TEST
int main(int argc, char **argv){
	#ifdef TEST	
	BitMap bi(11);
	std::cout<<"initailize the bitmap"<<std::endl;
	bi.printBitMap();

	std::cout<<"set the first bit to 1"<<std::endl;	
	bi.setBit(1,true);
	bi.printBitMap();

	std::cout<<"set the twenty bit to 1"<<std::endl;
	bi.setBit(2,true);
	bi.printBitMap();

	bool tp=bi.getBit(2);
	std::cout<<"is the twenty bit 1? "<< tp<<std::endl;
	#endif	

	const int init_length=10000000;
	const int am_factor=1;
	std::cout<<"bit_length:"<<init_length<<std::endl;
	std::cout<<"amplification factor:"<<am_factor<<std::endl;

	time_t t1;
	time(&t1);
	long tb1=getSystemTime();
	std::cout<<"time: "<<ctime(&t1)<<std::endl;
	
	std::cout<<"our BitMap to execut ... "<<std::endl;
	BitMap bit(init_length);
	for(int t=0;t<am_factor;t++){
		for(int i=0;i<init_length;i++)
			bit.setBit(i,true);
	}
	
	time_t t2;
	time(&t2);
	long tb2=getSystemTime();
	std::cout<<"time: "<<ctime(&t2)<<std::endl;
	
	std::cout<<"using c++ bitset to execut ... "<<std::endl;
	std::bitset<init_length> bvec;
	for(int t=0;t<am_factor;t++){
		for(int i=0;i<init_length;i++)
			bvec.set(i);
	}
	
	time_t t3;
	time(&t3);
	long tb3=getSystemTime();
	std::cout<<"time: "<<ctime(&t3)<<std::endl;
	std::cout<<"tb1="<<tb1<<"\ttb2="<<tb2<<"\ttb3="<<tb3<<std::endl;
	std::cout<<"BitMap elapsed: "<<tb2-tb1<<"ms"<<std::endl;
	std::cout<<"bitset elapsed: "<<tb3-tb2<<"ms"<<std::endl;

}
Example #19
0
void
TR_BackwardReachability::propagateInputs(blocknum_t blockNum, int32_t depth, blocknum_t *stack, blocknum_t *depth_map, TR_BitVector *closure)
   {
   TR::Block *block = getBlock(blockNum);
   TR_SuccessorIterator bi(block);
   for (TR::CFGEdge *edge = bi.getFirst(); edge != NULL; edge = bi.getNext())
      {
      TR::Block *inputBlock = toBlock(edge->getTo());
      propagateOneInput(inputBlock->getNumber(), blockNum, depth, stack, depth_map, closure);
      }
   }
int
sc_main( int argc, char* argv[] )
{
	sc_bigint<6>  bi;
	sc_biguint<6> bui;
    sc_bv<4>      bv;
	sc_int<6>     i;
    sc_lv<4>      lv;
	sc_int<6>     ui;

	bi =  10;
	bui = 10;
	bv =  "1010";
	i =   10;
	lv =  "1010";
	ui =  10;

    DISPLAY(bi(3,0))	
    DISPLAY(bui(3,0))	
    DISPLAY(bv)	
    DISPLAY(i(3,0))	
    DISPLAY(lv)	
    DISPLAY(ui(3,0))	

    DISPLAY((bi(3,2),i(1,0)))	
    DISPLAY((bi(3,2),ui(1,0)))	
    DISPLAY((bi(3,2),bui(1,0)))	
    DISPLAY((bi(3,2),bi(1,0)))	

    DISPLAY((bui(3,2),i(1,0)))	
    DISPLAY((bui(3,2),ui(1,0)))	
    DISPLAY((bui(3,2),bui(1,0)))	
    DISPLAY((bui(3,2),bi(1,0)))	

    DISPLAY((i(3,2),i(1,0)))	
    DISPLAY((i(3,2),ui(1,0)))	
    DISPLAY((i(3,2),bui(1,0)))	
    DISPLAY((i(3,2),bi(1,0)))	

    DISPLAY((ui(3,2),i(1,0)))	
    DISPLAY((ui(3,2),ui(1,0)))	
    DISPLAY((ui(3,2),bui(1,0)))	
    DISPLAY((ui(3,2),bi(1,0)))	

    return 0;
}
Example #21
0
BrowseInfo TVBrowseHelper::GetBrowsedInfo(void) const
{
    QMutexLocker locker(&m_lock);
    BrowseInfo bi(BROWSE_SAME);
    if (m_ctx != NULL)
    {
        bi.m_channum   = m_channum;
        bi.m_chanid    = m_chanid;
        bi.m_starttime = m_starttime;
    }
    return bi;
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
void UIFileWatcherLeds::triggerUpdate(const int flags)
{
    BigInteger bi(flags);

    for (int i=0; i<16; i++)
    {
        if (bi[i])
        {
            blinkLed(i, true);
        }
    }
}
Example #23
0
int AppGunzip::run(int argc, char **argv)
{
    _options.parse(argc, argv);
    ifstream ifs(argv[1]);
    ofstream ofs(argv[2]);
    BitInput2Stream bi(&ifs);
    GzipStream gz(&bi);
    gz.extractTo(ofs);
    ofs.close();
    ifs.close();
    return 0;
}
 /**
    Converts ar to a list. atomToNative<ListType::value_type>()
    is used for the conversions.
 */
 inline ReturnType operator()( Array const & ar ) const
 {
     ListType rc;
     Array::ConstIterator it = ar.begin();
     Array::ConstIterator const et = ar.end();
     std::back_insert_iterator<ListType> bi( std::back_inserter<ListType>(rc) );
     for( ; it != et; ++it )
     {
         *(bi++) = atomToNative<typename ListType::value_type>(*it);
     }
     return rc;
 }
Example #25
0
void MGRadBndry::setHomogValues(const BCRec& bc, IntVect& ratio)
{

  setBndryConds(bc, geom, ratio);

  for (OrientationIter fi; fi; ++fi) {
    Orientation face(fi());
    for (FabSetIter bi(bndry[face]); bi.isValid(); ++bi) {
      FArrayBox& bnd_fab = bndry[face][bi];
      bnd_fab.setVal(0.);
    }
  }
}
Example #26
0
int main(int argc, char* argv[])
{
	char check;
	initscr();
	cbreak();
	nodelay(stdscr, FALSE);
	scrollok(stdscr, TRUE);
	wprintw(stdscr, "This is the enemy adder ver. %d.%d for the Brave Quest engine.\nCopyright 2012 Mad Science Inc.\nPlease do not redistrubute.\nLoads .enm files!\nPress any key to continue!\n\n",enemytablevernum,enemytablevernum2);
	hang(1);
	while(check != ERR)
	{
		check = nbi();
	}
	bi();
	stufffilename();
				wprintw(stdscr, "\nWoohoo!\n");
				wrefresh(stdscr);
				hang(1);
	if(loaden(filename) == 1)
	{
		wprintw(stdscr, "File %s not Found. Would you like to make a new file?\n", filename);
		if(bie() == 'y')
		{
			enemynum = 0;
//			for(frunx = 0; frunx < 256; frunx++)
//				for(fruny = 0; fruny < 16; fruny++)
//					enemytable[frunx][fruny] = sep;
			if(saveen(filename) == 1)
			{
				wprintw(stdscr, "Your disk sucks.\n");
				bi();
				return 1;
			}
		}
	}
	
	charted();
	return 0;
};
void BSONCollectionCatalogEntry::IndexMetaData::updateTTLSetting(long long newExpireSeconds) {
    BSONObjBuilder b;
    for (BSONObjIterator bi(spec); bi.more();) {
        BSONElement e = bi.next();
        if (e.fieldNameStringData() == "expireAfterSeconds") {
            continue;
        }
        b.append(e);
    }

    b.append("expireAfterSeconds", newExpireSeconds);
    spec = b.obj();
}
Example #28
0
Num solve_Ss(Num X, Num T, Num r, Num b, Num v)
{
  Num N = 2 * b / (v * v);
  Num M = 2 * r / (v * v);
  Num Si = seed_Ss(N, M, X, T, b, v);

  Num K = 1 - exp(-r * T);
  Num d1 = bsm_general::d1(Si, X, T, b, v);
  Num q2_ = q2(N, M, K);
  Num LHS = Si - X;
  Num RHS = rhs(d1, Si, X, T, r, b, v, q2_);
  Num bi_ = bi(d1, T, r, b, v, q2_);
  Num eps = 1e-6;
  while (std::abs(LHS - RHS) / X > eps){
    Si = (X + RHS - bi_ * Si) / (1 - bi_);
    d1 = bsm_general::d1(Si, X, T, b, v);
    LHS = Si - X;
    RHS = rhs(d1, Si, X, T, r, b, v, q2_);
    bi_ = bi(d1, T, r, b, v, q2_);
  }
  return Si;
}
Example #29
0
	void generate_color_wheel(int num_points, std::vector<glm::u8vec4>* color_array, const Color& centre, float start_hue, float end_hue)
	{
		ASSERT_LOG(num_points > 0, "Must be more than one point in call to generate_color_wheel()");
		color_array->emplace_back(centre.ri(), centre.gi(), centre.bi(), centre.ai()); // center color.
		float hue = start_hue;
		const float sat = 1.0f;
		const float value = 1.0f;
		for(int n = 0; n != num_points; n++) {
			auto c = Color::from_hsv(hue, sat, value);
			color_array->emplace_back(c.ri(), c.gi(), c.bi(), c.ai());
			hue += (end_hue - start_hue)/static_cast<float>(num_points);
		}
		color_array->emplace_back((*color_array)[1]);
	}
Example #30
0
void CUnitLoader::RestoreGround(const CUnit* unit)
{
    const UnitDef* unitDef = unit->unitDef;
    const float groundheight = ground->GetHeightReal(unit->pos.x, unit->pos.z);

    if (mapDamage->disabled) return;
    if (!unitDef->levelGround) return;
    if (!unitDef->IsImmobileUnit()) return;
    if (unitDef->floatOnWater && groundheight <= 0.0f) return;

    BuildInfo bi(unitDef, unit->pos, unit->buildFacing);
    bi.pos = CGameHelper::Pos2BuildPos(bi, true);
    const float hss = 0.5f * SQUARE_SIZE;
    const int tx1 = (int) std::max(0.0f ,(bi.pos.x - (bi.GetXSize() * hss)) / SQUARE_SIZE);
    const int tz1 = (int) std::max(0.0f ,(bi.pos.z - (bi.GetZSize() * hss)) / SQUARE_SIZE);
    const int tx2 = std::min(gs->mapx, tx1 + bi.GetXSize());
    const int tz2 = std::min(gs->mapy, tz1 + bi.GetZSize());


    const float* heightmap = readMap->GetCornerHeightMapSynced();
    int num = 0;
    float heightdiff = 0.0f;
    for (int z = tz1; z <= tz2; z++) {
        for (int x = tx1; x <= tx2; x++) {
            int index = z * gs->mapxp1 + x;
            heightdiff += heightmap[index] - readMap->GetOriginalHeightMapSynced()[index];
            ++num;
        }
    }
    // adjust the terrain profile to match orgheightmap
    heightdiff /= (float)num;
    heightdiff += unit->pos.y - bi.pos.y;
    for (int z = tz1; z <= tz2; z++) {
        for (int x = tx1; x <= tx2; x++) {
            int index = z * gs->mapxp1 + x;
            readMap->SetHeight(index, heightdiff + readMap->GetOriginalHeightMapSynced()[index]);
        }
    }
    // but without affecting the build height
    heightdiff = bi.pos.y - CGameHelper::Pos2BuildPos(bi, true).y;
    for (int z = tz1; z <= tz2; z++) {
        for (int x = tx1; x <= tx2; x++) {
            int index = z * gs->mapxp1 + x;
            readMap->SetHeight(index, heightdiff + heightmap[index]);
        }
    }

    mapDamage->RecalcArea(tx1, tx2, tz1, tz2);
}