コード例 #1
0
ファイル: cubes.cpp プロジェクト: adderly/bgfx
int _main_(int /*_argc*/, char** /*_argv*/)
{
	uint32_t width = 1280;
	uint32_t height = 720;
	uint32_t debug = BGFX_DEBUG_TEXT;
	uint32_t reset = BGFX_RESET_VSYNC;

	bgfx::init();
	bgfx::reset(width, height, reset);

	// Enable debug text.
	bgfx::setDebug(debug);

	// Set view 0 clear state.
	bgfx::setViewClear(0
		, BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
		, 0x303030ff
		, 1.0f
		, 0
		);

	// Setup root path for binary shaders. Shader binaries are different 
	// for each renderer.
	switch (bgfx::getRendererType() )
	{
	default:
	case bgfx::RendererType::Direct3D9:
		s_shaderPath = "shaders/dx9/";
		break;

	case bgfx::RendererType::Direct3D11:
		s_shaderPath = "shaders/dx11/";
		break;

	case bgfx::RendererType::OpenGL:
		s_shaderPath = "shaders/glsl/";
		break;

	case bgfx::RendererType::OpenGLES:
		s_shaderPath = "shaders/gles/";
		break;
	}

	// Create vertex stream declaration.
	s_PosColorDecl.begin();
	s_PosColorDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
	s_PosColorDecl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
	s_PosColorDecl.end();

	const bgfx::Memory* mem;

	// Create static vertex buffer.
	mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) );
	bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosColorDecl);

	// Create static index buffer.
	mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) );
	bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem);

	// Load vertex shader.
	mem = loadShader("vs_cubes");
	bgfx::ShaderHandle vsh = bgfx::createShader(mem);

	// Load fragment shader.
	mem = loadShader("fs_cubes");
	bgfx::ShaderHandle fsh = bgfx::createShader(mem);

	// Create program from shaders.
	bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh);

	// We can destroy vertex and fragment shader here since
	// their reference is kept inside bgfx after calling createProgram.
	// Vertex and fragment shader will be destroyed once program is
	// destroyed.
	bgfx::destroyShader(vsh);
	bgfx::destroyShader(fsh);

	float at[3] = { 0.0f, 0.0f, 0.0f };
	float eye[3] = { 0.0f, 0.0f, -35.0f };

	int64_t timeOffset = bx::getHPCounter();

	while (!entry::processEvents(width, height, debug, reset) )
	{
		float view[16];
		float proj[16];
		mtxLookAt(view, eye, at);
		mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);

		// Set view and projection matrix for view 0.
		bgfx::setViewTransform(0, view, proj);

		// Set view 0 default viewport.
		bgfx::setViewRect(0, 0, 0, width, height);

		// This dummy draw call is here to make sure that view 0 is cleared
		// if no other draw calls are submitted to view 0.
		bgfx::submit(0);

		int64_t now = bx::getHPCounter();
		static int64_t last = now;
		const int64_t frameTime = now - last;
		last = now;
		const double freq = double(bx::getHPFrequency() );
		const double toMs = 1000.0/freq;

		float time = (float)( (now-timeOffset)/double(bx::getHPFrequency() ) );

		// Use debug font to print information about this example.
		bgfx::dbgTextClear();
		bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/01-cube");
		bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Rendering simple static mesh.");
		bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);

		// Submit 11x11 cubes.
		for (uint32_t yy = 0; yy < 11; ++yy)
		{
			for (uint32_t xx = 0; xx < 11; ++xx)
			{
				float mtx[16];
				mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f);
				mtx[12] = -15.0f + float(xx)*3.0f;
				mtx[13] = -15.0f + float(yy)*3.0f;
				mtx[14] = 0.0f;

				// Set model matrix for rendering.
				bgfx::setTransform(mtx);

				// Set vertex and fragment shaders.
				bgfx::setProgram(program);

				// Set vertex and index buffer.
				bgfx::setVertexBuffer(vbh);
				bgfx::setIndexBuffer(ibh);

				// Set render states.
				bgfx::setState(BGFX_STATE_DEFAULT);

				// Submit primitive for rendering to view 0.
				bgfx::submit(0);
			}
		}

		// Advance to next frame. Rendering thread will be kicked to 
		// process submitted rendering primitives.
		bgfx::frame();
	}

	// Cleanup.
	bgfx::destroyIndexBuffer(ibh);
	bgfx::destroyVertexBuffer(vbh);
	bgfx::destroyProgram(program);

	// Shutdown bgfx.
	bgfx::shutdown();

	return 0;
}
コード例 #2
0
#include <cmath>
#include <set>
#include <numeric>

#define LIMIT		100000000
static const unsigned SQRT_LIMIT = (unsigned)sqrt(float(LIMIT));

static bool ispandigital(unsigned number)
{	// 是否为回文数.
	const unsigned tmp = number;
	unsigned reverse = 0;
	for(; number != 0; number /= 10)
		reverse = reverse * 10 + number % 10;
	return reverse == tmp;
}

__int64 solve_125()
{
	unsigned* buffer = new unsigned[SQRT_LIMIT + 1];
	for(unsigned i = 1; i < SQRT_LIMIT; ++i)
		buffer[i] = i * i;

	std::set<unsigned> sqrtsum;

	// 依次累加2个数,3个数...为一组的和.并判断是否是回文数,是的话加入set中.
	for(unsigned len = 2; len <= SQRT_LIMIT; ++len)
	{	
		unsigned tmp = std::accumulate(buffer + 1, buffer + len + 1, 0u);
		
		if(tmp > LIMIT)
			break;
コード例 #3
0
ファイル: testPyGTBMulticlass.C プロジェクト: davidlt/root
int testPyGTBMulticlass(){
   // Get data file
   std::cout << "Get test data..." << std::endl;
   TString fname = "./tmva_example_multiple_background.root";
   if (gSystem->AccessPathName(fname)){  // file does not exist in local directory
      std::cout << "Create multiclass test data..." << std::endl;
      TString createDataMacro = TString(gROOT->GetTutorialsDir()) + "/tmva/createData.C";
      gROOT->ProcessLine(TString::Format(".L %s",createDataMacro.Data()));
      gROOT->ProcessLine("create_MultipleBackground(200)");
      std::cout << "Created " << fname << " for tests of the multiclass features" << std::endl;
   }
   TFile *input = TFile::Open(fname);

   // Setup PyMVA and factory
   std::cout << "Setup TMVA..." << std::endl;
   TMVA::PyMethodBase::PyInitialize();
   TFile* outputFile = TFile::Open("ResultsTestPyGTBMulticlass.root", "RECREATE");
   TMVA::Factory *factory = new TMVA::Factory("testPyGTBMulticlass", outputFile,
      "!V:Silent:Color:!DrawProgressBar:AnalysisType=multiclass");

   // Load data
   TMVA::DataLoader *dataloader = new TMVA::DataLoader("datasetTestPyGTBMulticlass");

   TTree *signal = (TTree*)input->Get("TreeS");
   TTree *background0 = (TTree*)input->Get("TreeB0");
   TTree *background1 = (TTree*)input->Get("TreeB1");
   TTree *background2 = (TTree*)input->Get("TreeB2");
   dataloader->AddTree(signal, "Signal");
   dataloader->AddTree(background0, "Background_0");
   dataloader->AddTree(background1, "Background_1");
   dataloader->AddTree(background2, "Background_2");

   dataloader->AddVariable("var1");
   dataloader->AddVariable("var2");
   dataloader->AddVariable("var3");
   dataloader->AddVariable("var4");

   dataloader->PrepareTrainingAndTestTree("",
      "SplitMode=Random:NormMode=NumEvents:!V");

   // Book and train method
   factory->BookMethod(dataloader, TMVA::Types::kPyGTB, "PyGTB",
      "!H:!V:VarTransform=None:NEstimators=100:Verbose=0");
   std::cout << "Train classifier..." << std::endl;
   factory->TrainAllMethods();

   // Clean-up
   delete factory;
   delete dataloader;
   delete outputFile;

   // Setup reader
   UInt_t numEvents = 100;
   std::cout << "Run reader and classify " << numEvents << " events..." << std::endl;
   TMVA::Reader *reader = new TMVA::Reader("!Color:Silent");
   Float_t vars[4];
   reader->AddVariable("var1", vars+0);
   reader->AddVariable("var2", vars+1);
   reader->AddVariable("var3", vars+2);
   reader->AddVariable("var4", vars+3);
   reader->BookMVA("PyGTB", "datasetTestPyGTBMulticlass/weights/testPyGTBMulticlass_PyGTB.weights.xml");

   // Get mean response of method on signal and background events
   signal->SetBranchAddress("var1", vars+0);
   signal->SetBranchAddress("var2", vars+1);
   signal->SetBranchAddress("var3", vars+2);
   signal->SetBranchAddress("var4", vars+3);

   background0->SetBranchAddress("var1", vars+0);
   background0->SetBranchAddress("var2", vars+1);
   background0->SetBranchAddress("var3", vars+2);
   background0->SetBranchAddress("var4", vars+3);

   background1->SetBranchAddress("var1", vars+0);
   background1->SetBranchAddress("var2", vars+1);
   background1->SetBranchAddress("var3", vars+2);
   background1->SetBranchAddress("var4", vars+3);

   background2->SetBranchAddress("var1", vars+0);
   background2->SetBranchAddress("var2", vars+1);
   background2->SetBranchAddress("var3", vars+2);
   background2->SetBranchAddress("var4", vars+3);

   Float_t meanMvaSignal = 0;
   Float_t meanMvaBackground0 = 0;
   Float_t meanMvaBackground1 = 0;
   Float_t meanMvaBackground2 = 0;
   for(UInt_t i=0; i<numEvents; i++){
      signal->GetEntry(i);
      meanMvaSignal += reader->EvaluateMulticlass("PyGTB")[0];
      background0->GetEntry(i);
      meanMvaBackground0 += reader->EvaluateMulticlass("PyGTB")[1];
      background1->GetEntry(i);
      meanMvaBackground1 += reader->EvaluateMulticlass("PyGTB")[2];
      background2->GetEntry(i);
      meanMvaBackground2 += reader->EvaluateMulticlass("PyGTB")[3];
   }
   meanMvaSignal = meanMvaSignal/float(numEvents);
   meanMvaBackground0 = meanMvaBackground0/float(numEvents);
   meanMvaBackground1 = meanMvaBackground1/float(numEvents);
   meanMvaBackground2 = meanMvaBackground2/float(numEvents);

   // Check whether the response is obviously better than guessing
   std::cout << "Mean MVA response on signal: " << meanMvaSignal << std::endl;
   if(meanMvaSignal < 0.3){
      std::cout << "[ERROR] Mean response on signal is " << meanMvaSignal << " (<0.3)" << std::endl;
      return 1;
   }
   std::cout << "Mean MVA response on background 0: " << meanMvaBackground0 << std::endl;
   if(meanMvaBackground0 < 0.3){
      std::cout << "[ERROR] Mean response on background 0 is " << meanMvaBackground0 << " (<0.3)" << std::endl;
      return 1;
   }
   std::cout << "Mean MVA response on background 1: " << meanMvaBackground1 << std::endl;
   if(meanMvaBackground0 < 0.3){
      std::cout << "[ERROR] Mean response on background 1 is " << meanMvaBackground1 << " (<0.3)" << std::endl;
      return 1;
   }
   std::cout << "Mean MVA response on background 2: " << meanMvaBackground2 << std::endl;
   if(meanMvaBackground0 < 0.3){
      std::cout << "[ERROR] Mean response on background 2 is " << meanMvaBackground2 << " (<0.3)" << std::endl;
      return 1;
   }

   return 0;
}
コード例 #4
0
void WorldSession::HandleNpcTextQueryOpcode(WorldPacket & recv_data)
{
    uint32 textID;
    uint64 guid;

    recv_data >> textID;
    sLog->outDetail("WORLD: CMSG_NPC_TEXT_QUERY ID '%u'", textID);

    recv_data >> guid;
    GetPlayer()->SetSelection(guid);

    GossipText const* pGossip = sObjectMgr->GetGossipText(textID);

    WorldPacket data(SMSG_NPC_TEXT_UPDATE, 100);          // guess size
    data << textID;

    if (!pGossip)
    {
        for (uint32 i = 0; i < MAX_GOSSIP_TEXT_OPTIONS; ++i)
        {
            data << float(0);
            data << "Greetings $N";
            data << "Greetings $N";
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
        }
    }
    else
    {
        std::string Text_0[MAX_LOCALES], Text_1[MAX_LOCALES];
        for (int i = 0; i < MAX_GOSSIP_TEXT_OPTIONS; ++i)
        {
            Text_0[i]=pGossip->Options[i].Text_0;
            Text_1[i]=pGossip->Options[i].Text_1;
        }

        int loc_idx = GetSessionDbLocaleIndex();
        if (loc_idx >= 0)
        {
            if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textID))
            {
                for (int i = 0; i < MAX_LOCALES; ++i)
                {
                    ObjectMgr::GetLocaleString(nl->Text_0[i], loc_idx, Text_0[i]);
                    ObjectMgr::GetLocaleString(nl->Text_1[i], loc_idx, Text_1[i]);
                }
            }
        }

        for (int i = 0; i < MAX_GOSSIP_TEXT_OPTIONS; ++i)
        {
            data << pGossip->Options[i].Probability;

            if (Text_0[i].empty())
                data << Text_1[i];
            else
                data << Text_0[i];

            if (Text_1[i].empty())
                data << Text_0[i];
            else
                data << Text_1[i];

            data << pGossip->Options[i].Language;

            for (int j = 0; j < MAX_GOSSIP_TEXT_EMOTES; ++j)
            {
                data << pGossip->Options[i].Emotes[j]._Delay;
                data << pGossip->Options[i].Emotes[j]._Emote;
            }
        }
    }

    SendPacket(&data);

    sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_NPC_TEXT_UPDATE");
}
コード例 #5
0
ファイル: core_func.cpp プロジェクト: c1rew/EasyPR-Android
//! 根据一幅图像与颜色模板获取对应的二值图
//! 输入RGB图像, 颜色模板(蓝色、黄色)
//! 输出灰度图(只有0和255两个值,255代表匹配,0代表不匹配)
Mat colorMatch(const Mat &src, Mat &match, const Color r,
               const bool adaptive_minsv)
{
    // S和V的最小值由adaptive_minsv这个bool值判断
    // 如果为true,则最小值取决于H值,按比例衰减
    // 如果为false,则不再自适应,使用固定的最小值minabs_sv
    // 默认为false
    const float max_sv = 255;
    const float minref_sv = 64;

    const float minabs_sv = 95;

    // blue的H范围
    const int min_blue = 100;  // 100
    const int max_blue = 140;  // 140

    // yellow的H范围
    const int min_yellow = 15;  // 15
    const int max_yellow = 40;  // 40

    // white的H范围
    const int min_white = 0;   // 15
    const int max_white = 30;  // 40

    Mat src_hsv;
    // 转到HSV空间进行处理,颜色搜索主要使用的是H分量进行蓝色与黄色的匹配工作
    cvtColor(src, src_hsv, CV_BGR2HSV);

    vector<Mat> hsvSplit;
    split(src_hsv, hsvSplit);
    equalizeHist(hsvSplit[2], hsvSplit[2]);
    merge(hsvSplit, src_hsv);

    //匹配模板基色,切换以查找想要的基色
    int min_h = 0;
    int max_h = 0;
    switch (r) {
    case BLUE:
        min_h = min_blue;
        max_h = max_blue;
        break;
    case YELLOW:
        min_h = min_yellow;
        max_h = max_yellow;
        break;
    case WHITE:
        min_h = min_white;
        max_h = max_white;
        break;
    default:
        // Color::UNKNOWN
        break;
    }

    float diff_h = float((max_h - min_h) / 2);
    float avg_h = min_h + diff_h;

    int channels = src_hsv.channels();
    int nRows = src_hsv.rows;
    //图像数据列需要考虑通道数的影响;
    int nCols = src_hsv.cols * channels;

    if (src_hsv.isContinuous()) {  //连续存储的数据,按一行处理
        nCols *= nRows;
        nRows = 1;
    }

    int i, j;
    uchar *p;
    float s_all = 0;
    float v_all = 0;
    float count = 0;
    for (i = 0; i < nRows; ++i) {
        p = src_hsv.ptr<uchar>(i);
        for (j = 0; j < nCols; j += 3) {
            int H = int(p[j]);      // 0-180
            int S = int(p[j + 1]);  // 0-255
            int V = int(p[j + 2]);  // 0-255

            s_all += S;
            v_all += V;
            count++;

            bool colorMatched = false;

            if (H > min_h && H < max_h) {
                float Hdiff = 0;
                if (H > avg_h) Hdiff = H - avg_h;
                else Hdiff = avg_h - H;

                float Hdiff_p = float(Hdiff) / diff_h;

                // S和V的最小值由adaptive_minsv这个bool值判断
                // 如果为true,则最小值取决于H值,按比例衰减
                // 如果为false,则不再自适应,使用固定的最小值minabs_sv
                float min_sv = 0;
                if (true == adaptive_minsv) min_sv =
                        minref_sv -
                        minref_sv / 2 *
                        (1 - Hdiff_p);  // inref_sv - minref_sv / 2 * (1 - Hdiff_p)
                else min_sv = minabs_sv;  // add

                if ((S > min_sv && S < max_sv) && (V > min_sv && V < max_sv)) colorMatched = true;
            }

            if (colorMatched == true) {
                p[j] = 0;
                p[j + 1] = 0;
                p[j + 2] = 255;
            } else {
                p[j] = 0;
                p[j + 1] = 0;
                p[j + 2] = 0;
            }
        }
    }

    // cout << "avg_s:" << s_all / count << endl;
    // cout << "avg_v:" << v_all / count << endl;

    // 获取颜色匹配后的二值灰度图
    Mat src_grey;
    vector<Mat> hsvSplit_done;
    split(src_hsv, hsvSplit_done);
    src_grey = hsvSplit_done[2];

    match = src_grey;

    return src_grey;
}
コード例 #6
0
//-----------------------------------------------------------------------
void xrMU_Model::calc_lighting	(xr_vector<base_color>& dest, const Fmatrix& xform, CDB::MODEL* MDL, base_lighting& lights, u32 flags)
{
	// trans-map
	typedef	xr_multimap<float,v_vertices>	mapVert;
	typedef	mapVert::iterator				mapVertIt;
	mapVert									g_trans;
	u32										I;

	// trans-epsilons
	const float eps			= EPS_L;
	const float eps2		= 2.f*eps;

	// calc pure rotation matrix
	Fmatrix Rxform,tmp,R;
	R.set						(xform	);
	R.translate_over			(0,0,0	);
	tmp.transpose				(R		);
	Rxform.invert				(tmp	);

	// Perform lighting
	CDB::COLLIDER				DB;
	DB.ray_options				(0);

	// Disable faces if needed
	/*
	BOOL bDisableFaces			= flags&LP_UseFaceDisable;
	if	(bDisableFaces)
		for (I=0; I<m_faces.size(); I++)	m_faces[I]->flags.bDisableShadowCast	= true;
	*/

	// Perform lighting
	for (I = 0; I<m_vertices.size(); I++)
	{
		_vertex*	V			= m_vertices[I];

		// Get ambient factor
		float		v_amb		= 0.f;
		float		v_trans		= 0.f;
		for (u32 f=0; f<V->m_adjacents.size(); f++)
		{
			_face*	F			=	V->m_adjacents[f];
			v_amb				+=	F->Shader().vert_ambient;
			v_trans				+=	F->Shader().vert_translucency;
		}
		v_amb					/=	float(V->m_adjacents.size());
		v_trans					/=	float(V->m_adjacents.size());
		float v_inv				=	1.f-v_amb;

		base_color_c			vC;
		Fvector					vP,vN;
		xform.transform_tiny	(vP,V->P);
		Rxform.transform_dir	(vN,V->N);
		exact_normalize			(vN); 

		// multi-sample
		const int n_samples		= (g_params().m_quality==ebqDraft)?1:6;
		for (u32 sample=0; sample<(u32)n_samples; sample++)
		{
			float				a	= 0.2f * float(sample) / float(n_samples);
			Fvector				P,N;
			N.random_dir		(vN,deg2rad(30.f));
			P.mad				(vP,N,a);
			LightPoint			(&DB, MDL, vC, P, N, lights, flags, 0);
		}
		vC.scale				(n_samples);
		vC._tmp_				=	v_trans;
		if (flags&LP_dont_hemi) ;
		else					vC.hemi	+=	v_amb;
		V->C._set				(vC);

		// Search
		const float key			= V->P.x;
		mapVertIt	it			= g_trans.lower_bound	(key);
		mapVertIt	it2			= it;

		// Decrement to the start and inc to end
		while (it!=g_trans.begin() && ((it->first+eps2)>key)) it--;
		while (it2!=g_trans.end() && ((it2->first-eps2)<key)) it2++;
		if (it2!=g_trans.end())	it2++;

		// Search
		BOOL	found = FALSE;
		for (; it!=it2; it++)
		{
			v_vertices&	VL		= it->second;
			_vertex* Front		= VL.front();
			R_ASSERT			(Front);
			if (Front->P.similar(V->P,eps))
			{
				found				= TRUE;
				VL.push_back		(V);
			}
		}

		// Register
		if (!found)				{
			mapVertIt	ins			= g_trans.insert(mk_pair(key,v_vertices()));
			ins->second.reserve		(32);
			ins->second.push_back	(V);
		}
	}

	// Enable faces if needed
	/*
	if	(bDisableFaces)
		for (I=0; I<m_faces.size(); I++)	m_faces[I]->flags.bDisableShadowCast	= true;
	*/

	// Process all groups
	for (mapVertIt it=g_trans.begin(); it!=g_trans.end(); it++)
	{
		// Unique
		v_vertices&	VL		= it->second;
		std::sort			(VL.begin(),VL.end());
		VL.erase			(std::unique(VL.begin(),VL.end()),VL.end());

		// Calc summary color
		base_color_c	C;
		for (int v=0; v<int(VL.size()); v++)
		{
			base_color_c	vC;
			VL[v]->C._get	(vC);
			C.max			(vC);
		}

		// Calculate final vertex color
		for (u32 v=0; v<int(VL.size()); v++)
		{
			base_color_c		vC;
			VL[v]->C._get		(vC);

			// trans-level
			float	level		= vC._tmp_;

			// 
			base_color_c		R;
			R.lerp				(vC,C,level);
			R.max				(vC);
			R.mul				(.5f);
			VL[v]->C._set		(R);
		}
	}

	// Transfer colors to destination
	dest.resize				(m_vertices.size());
	for (I = 0; I<m_vertices.size(); I++)
	{
		Fvector		ptPos	= m_vertices[I]->P;
		base_color	ptColor	= m_vertices[I]->C;
		dest[I]				= ptColor;
	}
}
コード例 #7
0
void DistanceToAtom::compute(const QVector<QVector3D> &pointsOriginal, float cutoff)
{
    if(pointsOriginal.size() == 0) {
        qDebug() << "DistanceToAtom::compute WARNING: input vector is empty.";
        return;
    }

    QElapsedTimer timer;
    timer.start();

    float min = 1e90;
    float max = -1e90;
    for(const QVector3D &point : pointsOriginal) {
        min = std::min(min, point[0]);
        min = std::min(min, point[1]);
        min = std::min(min, point[2]);

        max = std::max(max, point[0]);
        max = std::max(max, point[1]);
        max = std::max(max, point[2]);
    }
    max += 1e-5;
    const float systemSize = max - min;

    // Now translate all points
    QVector<QVector3D> points = pointsOriginal;
    for(QVector3D &point : points) {
        point[0] -= min;
        point[1] -= min;
        point[2] -= min;
    }
    float cellSize;
    CellList cellList = buildCellList(points, systemSize, cutoff, cellSize);
    const int numCells = cellList.size(); // Each index should be identical


    m_values.clear();
    m_values.resize(m_numberOfRandomVectors);
    m_randomNumbers.resize(3*m_numberOfRandomVectors);


    for(int i=0; i<3*m_numberOfRandomVectors; i++) {
        m_randomNumbers[i] = floatRandom(0, systemSize);
    }

    const float oneOverCellSize = 1.0/cellSize;

#pragma omp parallel for num_threads(8)
    for(int i=0; i<m_numberOfRandomVectors; i++) {
        const float x = m_randomNumbers[3*i+0];
        const float y = m_randomNumbers[3*i+1];
        const float z = m_randomNumbers[3*i+2];

        const int cx = x * oneOverCellSize;
        const int cy = y * oneOverCellSize;
        const int cz = z * oneOverCellSize;
        float minimumDistanceSquared = 1e10;
        const float minimumDistanceSquared0 = minimumDistanceSquared;

        // Loop through all 27 cells with size=cutoff
        for(int dx=-1; dx<=1; dx++) {
            for(int dy=-1; dy<=1; dy++) {
                for(int dz=-1; dz<=1; dz++) {
                    const vector<QVector3D> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)];
                    const int numberOfPointsInCell = pointsInCell.size();

                    for(int j=0; j<numberOfPointsInCell; j++) {
                        // const QVector3D &point = points[pointIndex];
                        const QVector3D &point = pointsInCell[j];

                        float dx = x - point[0];
                        float dy = y - point[1];
                        float dz = z - point[2];
                        if(dx < -0.5*systemSize) dx += systemSize;
                        else if(dx > 0.5*systemSize) dx -= systemSize;

                        if(dy < -0.5*systemSize) dy += systemSize;
                        else if(dy > 0.5*systemSize) dy -= systemSize;

                        if(dz < -0.5*systemSize) dz += systemSize;
                        else if(dz > 0.5*systemSize) dz -= systemSize;
                        const float distanceSquared = dx*dx + dy*dy + dz*dz;
                        if(distanceSquared < minimumDistanceSquared) minimumDistanceSquared = distanceSquared;
                    }
                }
            }
        }

        if(minimumDistanceSquared == minimumDistanceSquared0) {
            minimumDistanceSquared = -1;
        }

        m_values[i] = float(minimumDistanceSquared);
    }

    m_randomNumbers.clear();
    points.clear();

    // qDebug() << "DTO finished after " << timer.elapsed() << " ms.";
    m_isValid = true;

    //    if(pointsOriginal.size() == 0) {
    //        qDebug() << "DistanceToAtom::compute WARNING: input vector is empty.";
    //        return;
    //    }

    //    float min = 1e90;
    //    float max = -1e90;
    //    for(const QVector3D &point : pointsOriginal) {
    //        min = std::min(min, point[0]);
    //        min = std::min(min, point[1]);
    //        min = std::min(min, point[2]);

    //        max = std::max(max, point[0]);
    //        max = std::max(max, point[1]);
    //        max = std::max(max, point[2]);
    //    }
    //    max += 1e-5;
    //    const float systemSize = max - min;

    //    // Now translate all points
    //    QVector<QVector3D> points = pointsOriginal;
    //    for(QVector3D &point : points) {
    //        point[0] -= min;
    //        point[1] -= min;
    //        point[2] -= min;
    //    }

    //    float cellSize;
    //    CellList cellList = buildCellList(points, systemSize, cutoff, cellSize);
    //    const int numCells = cellList.size(); // Each index should be identical

    //    const float voxelSize = systemSize / m_size;
    //    for(int i=0; i<m_size; i++) {
    //        for(int j=0; j<m_size; j++) {
    //            for(int k=0; k<m_size; k++) {
    //                const QVector3D voxelCenter((i+0.5)*voxelSize, (j+0.5)*voxelSize, (k+0.5)*voxelSize);
    //                float minimumDistanceSquared0 = 1e10;
    //                float minimumDistanceSquared = 1e10;
    //                // Find the cell list where this position belongs and loop through all cells around
    //                const int cx = voxelCenter[0] / cellSize;
    //                const int cy = voxelCenter[1] / cellSize;
    //                const int cz = voxelCenter[2] / cellSize;

    //                // Loop through all 27 cells with size=cutoff
    //                for(int dx=-1; dx<=1; dx++) {
    //                    for(int dy=-1; dy<=1; dy++) {
    //                        for(int dz=-1; dz<=1; dz++) {
    //                            const vector<int> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)];
    //                            for(const int &pointIndex : pointsInCell) {
    //                                const QVector3D &point = points[pointIndex];

    //                                const float distanceSquared = periodicDistanceSquared(point, voxelCenter, systemSize);
    //                                minimumDistanceSquared = std::min(minimumDistanceSquared, distanceSquared);
    //                            }
    //                        }
    //                    }
    //                }
    //                if(minimumDistanceSquared == minimumDistanceSquared0) {
    //                    minimumDistanceSquared = -1;
    //                }
    //                setValue(i,j,k,float(minimumDistanceSquared));
    //            }
    //        }
    //    }

    //    m_isValid = true;
}
コード例 #8
0
ファイル: mask_draw.c プロジェクト: BlueLabelStudio/blender
/* return non-zero if spline is selected */
static void draw_spline_points(const bContext *C, MaskLayer *masklay, MaskSpline *spline,
                               const char UNUSED(draw_flag), const char draw_type)
{
	const bool is_spline_sel = (spline->flag & SELECT) && (masklay->restrictflag & MASK_RESTRICT_SELECT) == 0;
	unsigned char rgb_spline[4];
	MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
	SpaceClip *sc = CTX_wm_space_clip(C);
	int undistort = FALSE;

	int i, hsize, tot_feather_point;
	float (*feather_points)[2], (*fp)[2];

	if (!spline->tot_point)
		return;

	if (sc)
		undistort = sc->clip && sc->user.render_flag & MCLIP_PROXY_RENDER_UNDISTORT;

	/* TODO, add this to sequence editor */
	hsize = 4; /* UI_GetThemeValuef(TH_HANDLE_VERTEX_SIZE); */

	glPointSize(hsize);

	mask_spline_color_get(masklay, spline, is_spline_sel, rgb_spline);

	/* feather points */
	feather_points = fp = BKE_mask_spline_feather_points(spline, &tot_feather_point);
	for (i = 0; i < spline->tot_point; i++) {

		/* watch it! this is intentionally not the deform array, only check for sel */
		MaskSplinePoint *point = &spline->points[i];

		int j;

		for (j = 0; j <= point->tot_uw; j++) {
			float feather_point[2];
			int sel = FALSE;

			copy_v2_v2(feather_point, *fp);

			if (undistort)
				mask_point_undistort_pos(sc, feather_point, feather_point);

			if (j == 0) {
				sel = MASKPOINT_ISSEL_ANY(point);
			}
			else {
				sel = point->uw[j - 1].flag & SELECT;
			}

			if (sel) {
				if (point == masklay->act_point)
					glColor3f(1.0f, 1.0f, 1.0f);
				else
					glColor3f(1.0f, 1.0f, 0.0f);
			}
			else {
				glColor3f(0.5f, 0.5f, 0.0f);
			}

			glBegin(GL_POINTS);
			glVertex2fv(feather_point);
			glEnd();

			fp++;
		}
	}
	MEM_freeN(feather_points);

	/* control points */
	for (i = 0; i < spline->tot_point; i++) {

		/* watch it! this is intentionally not the deform array, only check for sel */
		MaskSplinePoint *point = &spline->points[i];
		MaskSplinePoint *point_deform = &points_array[i];
		BezTriple *bezt = &point_deform->bezt;

		float handle[2];
		float vert[2];
		const bool has_handle = BKE_mask_point_has_handle(point);

		copy_v2_v2(vert, bezt->vec[1]);
		BKE_mask_point_handle(point_deform, handle);

		if (undistort) {
			mask_point_undistort_pos(sc, vert, vert);
			mask_point_undistort_pos(sc, handle, handle);
		}

		/* draw handle segment */
		if (has_handle) {

			/* this could be split into its own loop */
			if (draw_type == MASK_DT_OUTLINE) {
				const unsigned char rgb_gray[4] = {0x60, 0x60, 0x60, 0xff};
				glLineWidth(3);
				glColor4ubv(rgb_gray);
				glBegin(GL_LINES);
				glVertex2fv(vert);
				glVertex2fv(handle);
				glEnd();
				glLineWidth(1);
			}

			glColor3ubv(rgb_spline);
			glBegin(GL_LINES);
			glVertex2fv(vert);
			glVertex2fv(handle);
			glEnd();
		}

		/* draw CV point */
		if (MASKPOINT_ISSEL_KNOT(point)) {
			if (point == masklay->act_point)
				glColor3f(1.0f, 1.0f, 1.0f);
			else
				glColor3f(1.0f, 1.0f, 0.0f);
		}
		else
			glColor3f(0.5f, 0.5f, 0.0f);

		glBegin(GL_POINTS);
		glVertex2fv(vert);
		glEnd();

		/* draw handle points */
		if (has_handle) {
			if (MASKPOINT_ISSEL_HANDLE(point)) {
				if (point == masklay->act_point)
					glColor3f(1.0f, 1.0f, 1.0f);
				else
					glColor3f(1.0f, 1.0f, 0.0f);
			}
			else {
				glColor3f(0.5f, 0.5f, 0.0f);
			}

			glBegin(GL_POINTS);
			glVertex2fv(handle);
			glEnd();
		}
	}

	glPointSize(1.0f);
}
コード例 #9
0
ファイル: mask_draw.c プロジェクト: BlueLabelStudio/blender
static void mask_draw_curve_type(const bContext *C, MaskSpline *spline, float (*orig_points)[2], int tot_point,
                                 const bool is_feather, const bool is_smooth, const bool is_active,
                                 const unsigned char rgb_spline[4], const char draw_type)
{
	const int draw_method = (spline->flag & MASK_SPLINE_CYCLIC) ? GL_LINE_LOOP : GL_LINE_STRIP;
	const unsigned char rgb_black[4] = {0x00, 0x00, 0x00, 0xff};
//	const unsigned char rgb_white[4] = {0xff, 0xff, 0xff, 0xff};
	unsigned char rgb_tmp[4];
	SpaceClip *sc = CTX_wm_space_clip(C);
	float (*points)[2] = orig_points;

	if (sc) {
		int undistort = sc->clip && sc->user.render_flag & MCLIP_PROXY_RENDER_UNDISTORT;

		if (undistort) {
			int i;

			points = MEM_callocN(2 * tot_point * sizeof(float), "undistorthed mask curve");

			for (i = 0; i < tot_point; i++) {
				mask_point_undistort_pos(sc, points[i], orig_points[i]);
			}
		}
	}

	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(2, GL_FLOAT, 0, points);

	switch (draw_type) {

		case MASK_DT_OUTLINE:
			glLineWidth(3);

			mask_color_active_tint(rgb_tmp, rgb_black, is_active);
			glColor4ubv(rgb_tmp);

			glDrawArrays(draw_method, 0, tot_point);

			glLineWidth(1);
			mask_color_active_tint(rgb_tmp, rgb_spline, is_active);
			glColor4ubv(rgb_tmp);
			glDrawArrays(draw_method, 0, tot_point);

			break;

		case MASK_DT_DASH:
		default:
			glEnable(GL_LINE_STIPPLE);

#ifdef USE_XOR
			glEnable(GL_COLOR_LOGIC_OP);
			glLogicOp(GL_OR);
#endif
			mask_color_active_tint(rgb_tmp, rgb_spline, is_active);
			glColor4ubv(rgb_tmp);
			glLineStipple(3, 0xaaaa);
			glEnableClientState(GL_VERTEX_ARRAY);
			glVertexPointer(2, GL_FLOAT, 0, points);
			glDrawArrays(draw_method, 0, tot_point);

#ifdef USE_XOR
			glDisable(GL_COLOR_LOGIC_OP);
#endif
			mask_color_active_tint(rgb_tmp, rgb_black, is_active);
			glColor4ubv(rgb_tmp);
			glLineStipple(3, 0x5555);
			glDrawArrays(draw_method, 0, tot_point);

			glDisable(GL_LINE_STIPPLE);
			break;


		case MASK_DT_BLACK:
		case MASK_DT_WHITE:
			if (draw_type == MASK_DT_BLACK) { rgb_tmp[0] = rgb_tmp[1] = rgb_tmp[2] = 0;   }
			else                            { rgb_tmp[0] = rgb_tmp[1] = rgb_tmp[2] = 255; }
			/* alpha values seem too low but gl draws many points that compensate for it */
			if (is_feather) { rgb_tmp[3] = 64; }
			else            { rgb_tmp[3] = 128; }

			if (is_feather) {
				rgb_tmp[0] = (unsigned char)(((short)rgb_tmp[0] + (short)rgb_spline[0]) / 2);
				rgb_tmp[1] = (unsigned char)(((short)rgb_tmp[1] + (short)rgb_spline[1]) / 2);
				rgb_tmp[2] = (unsigned char)(((short)rgb_tmp[2] + (short)rgb_spline[2]) / 2);
			}

			if (is_smooth == FALSE && is_feather) {
				glEnable(GL_BLEND);
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			}

			mask_color_active_tint(rgb_tmp, rgb_tmp, is_active);
			glColor4ubv(rgb_tmp);

			glEnableClientState(GL_VERTEX_ARRAY);
			glVertexPointer(2, GL_FLOAT, 0, points);
			glDrawArrays(draw_method, 0, tot_point);

			if (is_smooth == FALSE && is_feather) {
				glDisable(GL_BLEND);
			}

			break;
	}

	glDisableClientState(GL_VERTEX_ARRAY);

	if (points != orig_points)
		MEM_freeN(points);
}
コード例 #10
0
ファイル: render_dx9.cpp プロジェクト: as2120/ZNginx
static void ParticleSimulation(void)
{
	LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9();

	device->SetRenderTarget(0, g_pSurfaces[TEX_POSITION1]);
	device->SetRenderTarget(1, g_pSurfaces[TEX_VELOCITY1]);
	device->SetDepthStencilSurface(NULL);

	RECT rect;
	rect.left = 0;
	rect.right = g_texture_width;
	rect.top = 0;
	rect.bottom = g_num_particles / g_texture_width;
	
	if ( rect.bottom==0 )
		return;

	device->SetScissorRect(&rect);
	device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);

	D3DXHANDLE shader = g_pParticleFX->GetTechniqueByName("Simulate");
	D3DXHANDLE positiontex_var = g_pParticleFX->GetParameterByName(NULL, "PositionTex");
	D3DXHANDLE velocitytex_var = g_pParticleFX->GetParameterByName(NULL, "VelocityTex");
	D3DXHANDLE noisetex_var = g_pParticleFX->GetParameterByName(NULL, "NoiseTex");
	D3DXHANDLE force_var = g_pParticleFX->GetParameterByName(NULL, "Force");
	D3DXHANDLE time_var = g_pParticleFX->GetParameterByName(NULL, "fTimeAdvance");
	D3DXHANDLE rand_var = g_pParticleFX->GetParameterByName(NULL, "Rand");
	D3DXHANDLE tan_var = g_pParticleFX->GetParameterByName(NULL, "fTan");
	D3DXHANDLE liferange_var = g_pParticleFX->GetParameterByName(NULL, "LifeRange");
	D3DXHANDLE speedrange_var = g_pParticleFX->GetParameterByName(NULL, "SpeedRange");
	D3DXHANDLE sizerange_var = g_pParticleFX->GetParameterByName(NULL, "SizeRange");

	Vector4 vForce = g_vForce * g_fTimeAdvance;
	Vector4 vRand[3];
	Vector4 vLifeRange(1.0f, 2.0f, 0.0f, 0.0f);
	Vector4 vSpeedRange(1.0f, 2.0f, 0.0f, 0.0f);
	Vector4 vSizeRange(0.01f, 0.02f, 0.0f, 0.0f);

	for ( int i=0; i<3; i++ )
	{
		vRand[i][0] = float(rand()%1024)/1024.0f;
		vRand[i][1] = float(rand()%1024)/1024.0f;
		vRand[i][2] = float(rand()%1024)/1024.0f;
		vRand[i][3] = float(rand()%1024)/1024.0f;
	}

	g_pParticleFX->SetTechnique(shader);
	g_pParticleFX->SetTexture(positiontex_var, g_pTextures[TEX_POSITION0]);
	g_pParticleFX->SetTexture(velocitytex_var, g_pTextures[TEX_VELOCITY0]);
	g_pParticleFX->SetTexture(noisetex_var, g_pNoiseTexture);
	g_pParticleFX->SetVector(force_var, (D3DXVECTOR4*)&vForce);
	g_pParticleFX->SetVectorArray(rand_var, (D3DXVECTOR4*)&vRand, 3);
	g_pParticleFX->SetVector(liferange_var, (D3DXVECTOR4*)&vLifeRange);
	g_pParticleFX->SetVector(speedrange_var, (D3DXVECTOR4*)&vSpeedRange);
	g_pParticleFX->SetVector(sizerange_var, (D3DXVECTOR4*)&vSizeRange);
	g_pParticleFX->SetFloat(time_var, g_fTimeAdvance);
	g_pParticleFX->SetFloat(tan_var, FastMath::Tan(FastMath::DegToRad(g_fEmitTheta)));

	g_pParticleFX->Begin(NULL,0);
	g_pParticleFX->BeginPass(0);
		GutDrawFullScreenQuad_DX9(&g_ImageInfo);
	g_pParticleFX->EndPass();
	g_pParticleFX->End();

	device->SetRenderTarget(1, NULL);
	device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
}
コード例 #11
0
void ffireModel::doFFstep() {
		int xFire, yFire, rFire, dnBurning, nBurning;
		int aveVol, aveRho;
		timeStep++;	// note: time starts at 1...
		//
		// first do the sheep:
		// note, we can remove sheep by setting sheepSpeed=0
		// use smarter sheep; sheep move to (and eat) an occupied site or at random.
		// printf("sheepSpeed: %d\n", sheepSpeed);
		// yodapause();
		//
		for (unsigned short isheep = 0; isheep<sheepSpeed; isheep++) {
			switch (*(grids+sheepPos)) {
				case 0: case rockAge:
					// move:
					//sheepPos = sheepPos + getRandDir((xmax+2), sheepRand);
					sheepPos = sheepPos + getSheepDir(sheepPos, grids, (xmax+2), sheepRand);
					break;
				case 1:
					// eat:
					*(grids+sheepPos)=0;
					break;
				default:
					// nothing.
					break;
				};
			
			//
			// 28 april 2008 yoder:
			// put sheep on torroid gemoetry. in principle, fire and sheep differer in that a cluster's probability of
			// catching fire is proportional to area. its probability of being eaten by sheep is related to its circumference,
			// specifically, C-loops. except where we drop sheep from space. the sheep always wander...
			// note: we use a series of if statements but are careful that none maps the test value to a subsequent test range...
			if (sheepPos<(xmax+2)) sheepPos=sheepPos + ymax*(xmax+2);	// if he wanders off the top...
			if (sheepPos>((xmax+2)*(ymax+1))) sheepPos=sheepPos-ymax*(xmax+2);	// wanders off the bottom.  also, sheepPos^(xmax+2)??
			if (sheepPos%(xmax+2)==0) sheepPos=sheepPos+xmax;	// off left side
			if (sheepPos%(xmax+1)==0) sheepPos=sheepPos-xmax;	// off right side
			}; // sheep-speed

		//
		// PLANT A TREE:
		// select a grid for tree planting:
		// yoder, v7: introduce dendritic growth. we have two prams, nRand, nClst. define a P(rand)-> Pr, P(clust)->Pc: Pr=nRand/(nRand+nClust), etc.
		//for (unsigned int irp=0; irp<randPlant; irp++) {
		thisX = plantRandx.nextInt(xmax);
		thisY = plantRandy.nextInt(ymax);
		gridPos = (xmax+2)*(thisY+1)+1+thisX;
		//
		*(grids+gridPos) = 1;
		
	// we've planted a tree. do we throw a match?
	// a 1 in fMatch chance (use any value between 0 and fMatch)
		if (rfMatch.nextInt(fMatch) == 1) {
			//yodapause();
			// throw a match.
			xFire = fireRandx.nextInt(xmax) + 1;
			yFire = fireRandy.nextInt(ymax) + 1;
			//
			fireSquare = grids + (xmax+2)*yFire + xFire;
			//printf("match: (%d, %d) :: %d\n", xFire, yFire, *fireSquare);
			//yodapause();
			//
			if (*fireSquare > 0 and *fireSquare<rockAge) {
				// initiate a new fire.
				// start from the epicenter and work out in concentric rectangles (squares)
				// until there are no new fires.
				// note: we make two passes over each circle. for now, we assume all squares
				// continue to burn until the fire is over. this is a subtle consideration that
				// will not matter for simpler versions of the model, but if we introduce burn probabilities,
				// we will have to be more careful.

				*fireSquare=-(*fireSquare);	// the fire-square starts burning
				//
				rFire = 1;
				dnBurning = 1;
				//
				nBurning = dnBurning;
				int yFireMin = int(yodacode::greaterOf((yFire-rFire), 1));	// we always start with a 1 squar boundary. we might, however, encounter the edges.
				int yFireMax = int(yodacode::lesserOf((yFire+rFire), float(ymax)));
				int xFireMin = int(yodacode::greaterOf(float(xFire-rFire), 1));
				int xFireMax = int(yodacode::lesserOf(float(xFire+rFire), float(xmax)));
				if (doSQL==0) {
					printGrid(grids, timeStep, xmax, ymax);
					};
				//while (dnBurning > 0) {
				while (dnBurning > 0) {
					dnBurning=0;
					for (char doTwice = 0; doTwice <=1; doTwice++) {	// "char" is a 1 byte integer. we could also use a boolean to count to 2.
					for (int iy = (yFireMin); iy <= (yFireMax); iy++) {
						for (int ix = (xFireMin); ix <= (xFireMax); ix++) {
							// also note: Gelb is right. a recursive approach is faster, though this bredth-first appraoch is more like real fire propagation.
							// printf("try-burn: %d, %d\n", ix, iy);
							//plotGrid(&grids[0], xmax, ymax);
							//yodapause();
							//
							int * centerGrid = (grids + ix + (xmax+2)*iy);
							int cStat, uStat, dStat, lStat, rStat;
							//int ulStat, urStat, llStat, lrStat;	// diagonal elements.
							cStat = *centerGrid;
							//
							uStat = *(centerGrid + (xmax+2));
							dStat = *(centerGrid - (xmax+2));
							lStat = *(centerGrid - 1);
							rStat = *(centerGrid + 1);
							//
							// diagonal elements:
							//ulStat = getGridStatus(*(centerGrid + (xmax+2) - 1), i);
							//urStat = getGridStatus(*(centerGrid + (xmax+2) + 1), i);
							//llStat = getGridStatus(*(centerGrid - (xmax+2) - 1), i);
							//lrStat = getGridStatus(*(centerGrid - (xmax+2) + 1), i);
							//yodapause();
								//if (*centerGrid >= burnAge and (*leftGrid==-1 or *rightGrid==-1 or *upGrid==-1 or *downGrid==-1)) {
								//if (*centerGrid >= burnAge and (*leftGrid<=-burnPropAge or *rightGrid<=-burnPropAge or *upGrid<=-burnPropAge or *downGrid<=-burnPropAge)) {
								//if (cStat >= burnAge and cStat < rockAge and (lStat<=-burnPropAge or rStat<=-burnPropAge or uStat<=-burnPropAge or dStat<=-burnPropAge)) {
								//
							// no immunity:
							if (cStat >= 1 and cStat < rockAge 
								and (lStat<=-1 or rStat<=-1 or uStat<=-1 or dStat<=-1) ) {
		//						// next nearest neighbors:
		//						if (cStat >= burnAge and cStat < rockAge 
		//							and  ( (lStat<=-burnPropAge or rStat<=-burnPropAge or uStat<=-burnPropAge or dStat<=-burnPropAge)
		//								 or ( (ulStat<=-nnnAge or urStat<=-nnnAge  or llStat<=-nnnAge  or lrStat<=-nnnAge)
		//									 and (ulStat<=-burnPropAge or urStat<=-burnPropAge or llStat<=-burnPropAge  or lrStat<=-burnPropAge)
		//									 )
		//						 		)
		//							) {
								*centerGrid = -(*centerGrid);
								// age -> number of trees in that grid...
								dnBurning ++;
								//printf("[%d, %d] catches from [%d, %d]\n", ix, iy, xFire, yFire);
								};
							}; // ix
						}; // iy
						}; // doTwice	
						// plotGridSimple (grids, i, xmax, ymax);
						nBurning = nBurning + dnBurning;
						//yodapause();
					xFireMin = int(yodacode::greaterOf(1, float(xFireMin-1)));
					xFireMax = int(yodacode::lesserOf(float(xmax), xFireMax+1));
					yFireMin = int(yodacode::greaterOf(1, float(yFireMin-1)));
					yFireMax = int(yodacode::lesserOf(float(ymax), yFireMax+1));
					// g1.plot_xy(vfireX, vfireY, "");
					};	// end "while" fire still burining
				//
				nFires++;
				nBurnedTotal = nBurnedTotal + nBurning;
				fCounts[nBurning-1]++;
				//
				// fires finished burning; extinguish:
				for (int iy = (yFireMin); iy <= (yFireMax); iy++) {
					for (int ix = (xFireMin); ix <= (xFireMax); ix++) {
						// &grids[0] + ix + (xmax+2)*iy
						//if (grids[ix + (xmax+2)*iy] < 0) grids[ix + (xmax+2)*iy]=0;
						if (*(grids +ix + (xmax+2)*iy) < 0) *(grids +ix + (xmax+2)*iy)=0;
						};
					};

				}; //else printf("no tree at match point.\n");	// if match -> tree...
			}; // if match-time
		};
コード例 #12
0
ファイル: helix.cpp プロジェクト: DimondTheCat/xray
int HelixObjCreateCallBack::proc(ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat ) {
	float r;
#ifdef _3D_CREATE
	DWORD snapdim = SNAP_IN_3D;
#else
	DWORD snapdim = SNAP_IN_PLANE;
#endif

#ifdef _OSNAP
	if (msg == MOUSE_FREEMOVE)
	{
			vpt->SnapPreview(m,m,NULL, snapdim);
	}
#endif

	if (msg==MOUSE_POINT||msg==MOUSE_MOVE) {
		switch(point) {
			case 0:
				ob->suspendSnap = TRUE;
				sp0 = m;
				createType = ob->dlgCreateMeth;
				p[0] = vpt->SnapPoint(m,m,NULL,snapdim);
				mat.SetTrans(p[0]); // Set Node's transform
				ob->pblock->SetValue(PB_RADIUS1,0,0.01f);
				ob->pmapParam->Invalidate();
				break;
			case 1:
				sp1 = m; 
				p[1] = vpt->SnapPoint(m,m,NULL,snapdim);
				if ( createType ) {	// radius	
					r = Length(p[1]-p[0]);
					center = p[0];
					}
				else {// diameter
					center = (p[0]+p[1]) / 2.0f;
					r = Length(center-p[0]);
					mat.SetTrans(center);  // Modify Node's transform
					}
				ob->pblock->SetValue(PB_RADIUS1,0,r);
				ob->pblock->SetValue(PB_RADIUS2,0,r);	// Make this the same for now
				ob->pmapParam->Invalidate();
				r1 = r;
				if (msg==MOUSE_POINT) {
					if(Length(m-sp0)<3 ||
					   Length(p[1]-p[0])<0.1f) {
						return CREATE_ABORT;
						}
					}
				break;
			case 2:
				sp2 = m;
#ifdef _OSNAP
				ht = vpt->SnapLength(vpt->GetCPDisp(p[1],Point3(0,0,1),sp1,m,TRUE));  
#else
				ht = vpt->SnapLength(vpt->GetCPDisp(p[1],Point3(0,0,1),sp1,m));  
#endif
				ob->pblock->SetValue(PB_HEIGHT,0,float(ht));
				ob->pmapParam->Invalidate();
				break;
			case 3:
				r = vpt->SnapLength(vpt->GetCPDisp(p[1],Point3(0,0,1),sp2,m))
						+ r1;
				ob->pblock->SetValue(PB_RADIUS2,0,r);
				ob->pmapParam->Invalidate();
				if (msg==MOUSE_POINT) {
					ob->suspendSnap = FALSE;
					return CREATE_STOP;
					}
				break;
			}
		}
	else
	if (msg == MOUSE_ABORT) {
		return CREATE_ABORT;
		}

	return TRUE;
	}
コード例 #13
0
int test_main(int,char *[])
{
    // default constructor
    const bu::quantity<bu::dimensionless>           E1; 
    BOOST_CHECK(E1.value() == double());
    
    // value_type constructor
    const bu::quantity<bu::dimensionless>           E2(E_);
    BOOST_CHECK(E2.value() == E_);

    // copy constructor
    const bu::quantity<bu::dimensionless>           E3(E2);
    BOOST_CHECK(E3.value() == E_);

    // operator=
    const bu::quantity<bu::dimensionless>           E4 = E2;
    BOOST_CHECK(E4.value() == E_);

    // implicit copy constructor value_type conversion
    const bu::quantity<bu::dimensionless,float>     E5(E2);
    BOOST_UNITS_CHECK_CLOSE(E5.value(), float(E_));

    const bu::quantity<bu::dimensionless,long>      E6(E2);
    BOOST_CHECK(E6.value() == long(E_));

    // implicit operator= value_type conversion
    // narrowing conversion disallowed
//    const bu::quantity<bu::dimensionless,float>     E7 = E2;
//    BOOST_UNITS_CHECK_CLOSE(E7.value(),float(E_));
    
    // narrowing conversion disallowed
//    const bu::quantity<bu::dimensionless,long>      E8 = E2;
//    BOOST_CHECK(E8.value() == long(E_));
    
    // const construction
    bu::quantity<bu::dimensionless>                 E9(E2); 
    BOOST_CHECK(E9.value() == E_);
    
//    // value assignment
//    E9.value() = 1.5*bu::dimensionless();
//    BOOST_CHECK(E9.value() == 1.5);
//    
//    // value assignment with implicit conversion
//    E9.value() = 1.5;
//    BOOST_CHECK(E9.value() == 1.5);
//    
//    // value assignment with implicit value_type conversion
//    E9.value() = 2*bu::dimensionless();
//    BOOST_CHECK(E9.value() == double(2));
//
//    // value assignment with implicit value_type conversion
//    E9.value() = 2;
//    BOOST_CHECK(E9.value() == double(2));
    
    // operator+=(this_type)
    E9 = 2.0;
    E9 += E9;
    BOOST_CHECK(E9.value() == 4.0);
    
    // operator-=(this_type)
    E9 = 2.0;
    E9 -= E9;
    BOOST_CHECK(E9.value() == 0.0);
    
    // operator*=(value_type)
    E9 = 2.0;
    E9 *= 2.0;
    BOOST_CHECK(E9.value() == 4.0);
    
    // operator/=(value_type)
    E9 = 2.0;
    E9 /= 2.0;
    BOOST_CHECK(E9.value() == 1.0);
    
    // static construct quantity from value_type
    const bu::quantity<bu::dimensionless>           E(bu::quantity<bu::dimensionless>::from_value(2.5));
    BOOST_CHECK(E.value() == 2.5);
    
    // implicit conversion to value_type
    const double    V1(E9);
    BOOST_CHECK(V1 == E9.value());
    
    const double    V2 = E9;
    BOOST_CHECK(V2 == E9.value());
            
    // unit * scalar
    BOOST_CHECK(bu::dimensionless()*2.0 == bu::quantity<bu::dimensionless>::from_value(2.0));
    
    // unit / scalar
    BOOST_CHECK(bu::dimensionless()/2.0 == bu::quantity<bu::dimensionless>::from_value(0.5));
    
    // scalar * unit
    BOOST_CHECK(2.0*bu::dimensionless() == bu::quantity<bu::dimensionless>::from_value(2.0));
    
    // scalar / unit
    BOOST_CHECK(2.0/bu::dimensionless() == bu::quantity<bu::dimensionless>::from_value(2.0));

    //  quantity * scalar
    BOOST_CHECK(E*2.0 == bu::quantity<bu::dimensionless>::from_value(5.0));

    //  quantity / scalar
    BOOST_CHECK(E/2.0 == bu::quantity<bu::dimensionless>::from_value(1.25));
    
    // scalar * quantity
    BOOST_CHECK(2.0*E == bu::quantity<bu::dimensionless>::from_value(5.0));

    // scalar / quantity
    BOOST_CHECK(2.0/E == bu::quantity<bu::dimensionless>::from_value(0.8));

    const bu::quantity<bu::dimensionless>       D1(1.0),
                                                D2(2.0);
    
    // unit * quantity
    BOOST_CHECK(bu::dimensionless()*D1 == D1);
    
    // unit / quantity
    BOOST_CHECK(bu::dimensionless()/D1 == D1);
    
    // quantity * unit
    BOOST_CHECK(D1*bu::dimensionless() == D1);
    
    // quantity / unit
    BOOST_CHECK(D1*bu::dimensionless() == D1);
    
    // +quantity
    BOOST_CHECK(+D1 == 1.0*bu::dimensionless());
    
    // -quantity
    BOOST_CHECK(-D1 == -1.0*bu::dimensionless());
    
    // quantity + quantity
    BOOST_CHECK(D2+D1 == 3.0*bu::dimensionless());
    
    // quantity - quantity
    BOOST_CHECK(D2-D1 == 1.0*bu::dimensionless());
    
    // quantity * quantity
    BOOST_CHECK(D1*D2 == 2.0*bu::dimensionless());
    
    // quantity / quantity
    BOOST_CHECK(D2/D1 == 2.0*bu::dimensionless());
    
    // integer power of quantity
    BOOST_CHECK(2.0*bu::pow<2>(D2) == 2.0*std::pow(2.0,2.0)*bu::dimensionless());
    
    // rational power of quantity
    BOOST_CHECK((2.0*bu::pow< bu::static_rational<2,3> >(D2) == 2.0*std::pow(2.0,2.0/3.0)*bu::dimensionless()));
    
    // integer root of quantity
    BOOST_CHECK(2.0*bu::root<2>(D2) == 2.0*std::pow(2.0,1.0/2.0)*bu::dimensionless());
    
    // rational root of quantity
    BOOST_CHECK((2.0*bu::root< bu::static_rational<3,2> >(D2) == 2.0*std::pow(2.0,2.0/3.0)*bu::dimensionless()));
    
    const bu::quantity<bu::dimensionless>   A1(0.0),
                                            A2(0.0),
                                            A3(1.0),
                                            A4(-1.0);
                                    
    // operator==
    BOOST_CHECK((A1 == A2) == true);
    BOOST_CHECK((A1 == A3) == false);
    
    // operator!=
    BOOST_CHECK((A1 != A2) == false);
    BOOST_CHECK((A1 != A3) == true);
    
    // operator<
    BOOST_CHECK((A1 < A2) == false);
    BOOST_CHECK((A1 < A3) == true);
    
    // operator<=
    BOOST_CHECK((A1 <= A2) == true);
    BOOST_CHECK((A1 <= A3) == true);
    
    // operator>
    BOOST_CHECK((A1 > A2) == false);
    BOOST_CHECK((A1 > A4) == true);
    
    // operator>=
    BOOST_CHECK((A1 >= A2) == true);
    BOOST_CHECK((A1 >= A4) == true);
    
    return 0;
}
コード例 #14
0
ファイル: 16.cpp プロジェクト: chrismp/learning-c-plus-plus
//explicit type conversions
// http://www.learncpp.com/cpp-tutorial/4-4a-explicit-type-conversion-casting/

// C-style casts
int i1 = 10;
int i2 = 4;
float f = (float)i1/i2; // promotes `i1` to float, so result is float instead of `int`

float f = float(i1)/i1; // same result as above


/*
	Because C-style casts are not checked by the compiler at compile time, 
	C-style casts can be inherently misused, 
	because they will let you do things that may not make sense, 
	such as getting rid of a const or changing 
	a data type without changing the underlying representation 
	(leading to garbage results).

	Consequently, C-style casts should generally be avoided.
*/

char c = 97;
std::cout << static_cast<int>(c) << std::endl; // prints 97, not 'a'

int i1 = 10;
int i2 = 4;
float f = static_cast<float>(i1)/i2; // better than the C-style casting apparently


// Compilers will often complain 
コード例 #15
0
inline float GetAge(uint64 t) { return float(time(NULL) - t) / DAY; }
コード例 #16
0
ファイル: mask_draw.c プロジェクト: BlueLabelStudio/blender
static void draw_spline_curve(const bContext *C, MaskLayer *masklay, MaskSpline *spline,
                              const char draw_flag, const char draw_type,
                              const bool is_active,
                              int width, int height)
{
	const unsigned int resol = max_ii(BKE_mask_spline_feather_resolution(spline, width, height),
	                                  BKE_mask_spline_resolution(spline, width, height));

	unsigned char rgb_tmp[4];

	const bool is_spline_sel = (spline->flag & SELECT) && (masklay->restrictflag & MASK_RESTRICT_SELECT) == 0;
	const bool is_smooth = (draw_flag & MASK_DRAWFLAG_SMOOTH) != 0;
	const bool is_fill = (spline->flag & MASK_SPLINE_NOFILL) == 0;

	unsigned int tot_diff_point;
	float (*diff_points)[2];

	unsigned int tot_feather_point;
	float (*feather_points)[2];

	diff_points = BKE_mask_spline_differentiate_with_resolution(spline, &tot_diff_point, resol);

	if (!diff_points)
		return;

	if (is_smooth) {
		glEnable(GL_LINE_SMOOTH);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}

	feather_points = BKE_mask_spline_feather_differentiated_points_with_resolution(spline, &tot_feather_point, resol, (is_fill != FALSE));

	/* draw feather */
	mask_spline_feather_color_get(masklay, spline, is_spline_sel, rgb_tmp);
	mask_draw_curve_type(C, spline, feather_points, tot_feather_point,
	                     TRUE, is_smooth, is_active,
	                     rgb_tmp, draw_type);

	if (!is_fill) {

		float *fp         = &diff_points[0][0];
		float *fp_feather = &feather_points[0][0];
		float tvec[2];
		int i;

		BLI_assert(tot_diff_point == tot_feather_point);

		for (i = 0; i < tot_diff_point; i++, fp += 2, fp_feather += 2) {
			sub_v2_v2v2(tvec, fp, fp_feather);
			add_v2_v2v2(fp_feather, fp, tvec);
		}

		/* same as above */
		mask_draw_curve_type(C, spline, feather_points, tot_feather_point,
		                     TRUE, is_smooth, is_active,
		                     rgb_tmp, draw_type);
	}

	MEM_freeN(feather_points);

	/* draw main curve */
	mask_spline_color_get(masklay, spline, is_spline_sel, rgb_tmp);
	mask_draw_curve_type(C, spline, diff_points, tot_diff_point,
	                     FALSE, is_smooth, is_active,
	                     rgb_tmp, draw_type);
	MEM_freeN(diff_points);

	if (draw_flag & MASK_DRAWFLAG_SMOOTH) {
		glDisable(GL_LINE_SMOOTH);
		glDisable(GL_BLEND);
	}

	(void)draw_type;
}
コード例 #17
0
ファイル: NGLScene.cpp プロジェクト: galek/DeferredShading
void NGLScene::initializeGL()
{
  // we must call this first before any other GL commands to load and link the
  // gl commands from the lib, if this is not done program will crash
  ngl::NGLInit::instance();
  // Now we will create a basic Camera from the graphics library
  // This is a static camera so it only needs to be set once
  // First create Values for the camera position
  ngl::Vec3 from(0.0f,2.0f,5.0f);
  ngl::Vec3 to(0.0f,0.0f,0.0f);
  ngl::Vec3 up(0.0f,1.0f,0.0f);
  // now load to our new camera
  m_cam.set(from,to,up);
  // set the shape using FOV 45 Aspect Ratio based on Width and Height
  // The final two are near and far clipping planes of 0.5 and 10
  m_cam.setShape(45.0f,(float)float(width()/height()),0.05f,350.0f);

  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);			   // Grey Background
  // enable depth testing for drawing
  glEnable(GL_DEPTH_TEST);
  // enable multisampling for smoother drawing
  glEnable(GL_MULTISAMPLE);
   // now to load the shader and set the values
  // grab an instance of shader manager
  ngl::ShaderLib *shader=ngl::ShaderLib::instance();
  // we are creating a shader for Pass 1
  shader->createShaderProgram("Pass1");
  // now we are going to create empty shaders for Frag and Vert
  shader->attachShader("Pass1Vertex",ngl::ShaderType::VERTEX);
  shader->attachShader("Pass1Fragment",ngl::ShaderType::FRAGMENT);
  // attach the source
  shader->loadShaderSource("Pass1Vertex","shaders/Pass1Vert.glsl");
  shader->loadShaderSource("Pass1Fragment","shaders/Pass1Frag.glsl");
  // compile the shaders
  shader->compileShader("Pass1Vertex");
  shader->compileShader("Pass1Fragment");
  // add them to the program
  shader->attachShaderToProgram("Pass1","Pass1Vertex");
  shader->attachShaderToProgram("Pass1","Pass1Fragment");
//  shader->bindFragDataLocation("Pass1",0,"pointDeferred");
//  shader->bindFragDataLocation("Pass1",1,"normalDeferred");
//  shader->bindFragDataLocation("Pass1",2,"colourDeferred");
//  shader->bindFragDataLocation("Pass1",3,"shadingDeferred");

  shader->linkProgramObject("Pass1");
  shader->use("Pass1");

  // we are creating a shader for Pass 2
  shader->createShaderProgram("Pass2");
  // now we are going to create empty shaders for Frag and Vert
  shader->attachShader("Pass2Vertex",ngl::ShaderType::VERTEX);
  shader->attachShader("Pass2Fragment",ngl::ShaderType::FRAGMENT);
  // attach the source
  shader->loadShaderSource("Pass2Vertex","shaders/Pass2Vert.glsl");
  shader->loadShaderSource("Pass2Fragment","shaders/Pass2Frag.glsl");
  // compile the shaders
  shader->compileShader("Pass2Vertex");
  shader->compileShader("Pass2Fragment");
  // add them to the program
  shader->attachShaderToProgram("Pass2","Pass2Vertex");
  shader->attachShaderToProgram("Pass2","Pass2Fragment");
  shader->linkProgramObject("Pass2");
  shader->use("Pass2");
  shader->setShaderParam1i("pointTex",0);
  shader->setShaderParam1i("normalTex",1);
  shader->setShaderParam1i("colourTex",2);
  shader->setShaderParam1i("lightPassTex",3);
  shader->setShaderParam1i("diffusePassTex",4);

  // we are creating a shader for Debug pass
  shader->createShaderProgram("Debug");
  // now we are going to create empty shaders for Frag and Vert
  shader->attachShader("DebugVertex",ngl::ShaderType::VERTEX);
  shader->attachShader("DebugFragment",ngl::ShaderType::FRAGMENT);
  // attach the source
  shader->loadShaderSource("DebugVertex","shaders/DebugVert.glsl");
  shader->loadShaderSource("DebugFragment","shaders/DebugFrag.glsl");
  // compile the shaders
  shader->compileShader("DebugVertex");
  shader->compileShader("DebugFragment");
  // add them to the program
  shader->attachShaderToProgram("Debug","DebugVertex");
  shader->attachShaderToProgram("Debug","DebugFragment");
  shader->linkProgramObject("Debug");
  shader->use("Debug");
  shader->setShaderParam1i("pointTex",0);
  shader->setShaderParam1i("normalTex",1);
  shader->setShaderParam1i("colourTex",2);
  shader->setShaderParam1i("lightPassTex",3);
  shader->setShaderParam1i("diffusePassTex",4);

  shader->setRegisteredUniform1i("mode",1);


  // we are creating a shader for Lighting pass
  shader->createShaderProgram("Lighting");
  // now we are going to create empty shaders for Frag and Vert
  shader->attachShader("LightingVertex",ngl::ShaderType::VERTEX);
  shader->attachShader("LightingFragment",ngl::ShaderType::FRAGMENT);
  // attach the source
  shader->loadShaderSource("LightingVertex","shaders/LightingPassVert.glsl");
  shader->loadShaderSource("LightingFragment","shaders/LightingPassFrag.glsl");
  // compile the shaders
  shader->compileShader("LightingVertex");
  shader->compileShader("LightingFragment");
  // add them to the program
  shader->attachShaderToProgram("Lighting","LightingVertex");
  shader->attachShaderToProgram("Lighting","LightingFragment");
  shader->linkProgramObject("Lighting");
  shader->use("Lighting");
  shader->setShaderParam1i("pointTex",0);
  shader->setShaderParam1i("normalTex",1);
  shader->setShaderParam1i("colourTex",2);
  shader->setShaderParam1i("lightPassTex",3);

  shader->setShaderParam2f("wh",width()*devicePixelRatio(),height()*devicePixelRatio());

  m_text.reset(new ngl::Text(QFont("Arial",14)));
  m_text->setScreenSize(width(),height());

  m_screenQuad = new ScreenQuad("Debug");
  ngl::VAOPrimitives *prim=ngl::VAOPrimitives::instance();
  prim->createSphere("sphere",0.5f,50.0f);

  prim->createSphere("lightSphere",0.1f,10.0f);
  prim->createCylinder("cylinder",0.5f,1.4f,40.0f,40.0f);

  prim->createCone("cone",0.5f,1.4f,20.0f,20.0f);

  prim->createDisk("disk",0.8f,120.0f);
  prim->createTorus("torus",0.15f,0.4f,40.0f,40.0f);
  prim->createTrianglePlane("plane",14.0f,14.0f,80.0f,80.0f,ngl::Vec3(0.0f,1.0f,0.0f));

  createFrameBuffer();
  printFrameBufferInfo(m_gbuffer);
  printFrameBufferInfo(m_lightBuffer);
  m_fpsTimer =startTimer(0);

}
コード例 #18
0
SpellInfo const* ScriptedAI::SelectSpell(Unit* target, uint32 school, uint32 mechanic, SelectTargetType targets, uint32 powerCostMin, uint32 powerCostMax, float rangeMin, float rangeMax, SelectEffect effects)
{
    //No target so we can't cast
    if (!target)
        return false;

    //Silenced so we can't cast
    if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
        return false;

    //Using the extended script system we first create a list of viable spells
    SpellInfo const* apSpell[CREATURE_MAX_SPELLS];
    memset(apSpell, 0, CREATURE_MAX_SPELLS * sizeof(SpellInfo*));

    uint32 spellCount = 0;

    SpellInfo const* tempSpell = NULL;

    //Check if each spell is viable(set it to null if not)
    for (uint32 i = 0; i < CREATURE_MAX_SPELLS; i++)
    {
        tempSpell = sSpellMgr->GetSpellInfo(me->m_spells[i]);

        //This spell doesn't exist
        if (!tempSpell)
            continue;

        // Targets and Effects checked first as most used restrictions
        //Check the spell targets if specified
        if (targets && !(SpellSummary[me->m_spells[i]].Targets & (1 << (targets-1))))
            continue;

        //Check the type of spell if we are looking for a specific spell type
        if (effects && !(SpellSummary[me->m_spells[i]].Effects & (1 << (effects-1))))
            continue;

        //Check for school if specified
        if (school && (tempSpell->SchoolMask & school) == 0)
            continue;

        //Check for spell mechanic if specified
        if (mechanic && tempSpell->Mechanic != mechanic)
            continue;

        //Make sure that the spell uses the requested amount of power
        if (powerCostMin && tempSpell->ManaCost < powerCostMin)
            continue;

        if (powerCostMax && tempSpell->ManaCost > powerCostMax)
            continue;

        //Continue if we don't have the mana to actually cast this spell
        if (tempSpell->ManaCost > me->GetPower(Powers(tempSpell->PowerType)))
            continue;

        //Check if the spell meets our range requirements
        if (rangeMin && me->GetSpellMinRangeForTarget(target, tempSpell) < rangeMin)
            continue;
        if (rangeMax && me->GetSpellMaxRangeForTarget(target, tempSpell) > rangeMax)
            continue;

        //Check if our target is in range
        if (me->IsWithinDistInMap(target, float(me->GetSpellMinRangeForTarget(target, tempSpell))) || !me->IsWithinDistInMap(target, float(me->GetSpellMaxRangeForTarget(target, tempSpell))))
            continue;

        //All good so lets add it to the spell list
        apSpell[spellCount] = tempSpell;
        ++spellCount;
    }

    //We got our usable spells so now lets randomly pick one
    if (!spellCount)
        return NULL;

    return apSpell[urand(0, spellCount - 1)];
}
コード例 #19
0
void Opt_ntuple_midmass_225(){

  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetHistLineWidth(2);
  gStyle->SetPalette(1);
  gStyle->SetOptStat(1111);

  TChain * f_chain = new TChain("MyTree");
  f_chain->Add("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_SKnonprompt_dilep_5_3_14.root");
  f_chain->LoadTree(0) ;
  
  TChain * f_chainmc = new TChain("MyTree");
  f_chainmc->Add("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_mc_5_3_14.root");
  f_chainmc->LoadTree(0) ;

  TChain * f_chainsig = new TChain("MyTree");
  f_chainsig->Add("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_SKHNee225_nocut_5_3_14.root");
  TFile * file = new TFile("/home/jalmond/Analysis/LQanalyzer/data/output/SSElectron_ntup/HNDiElectron_SKHNee225_nocut_5_3_14.root");
  cout << file << endl;
  float  k_met=0., k_eemass=0., k_eejjmass=0., k_e1jjmass=0., k_e2jjmass=0.,  k_st=0., k_ht;
  float k_weight=0.;
  int k_njet, k_nbjet_m;
  float k_el1pt=0., k_el2pt=0., k_j1pt=0., k_jjmass=0., k_el1eta=0., k_el2eta=0.;
  bool k_cl1bjet,k_cl2bjet,k_cll1bjet,k_cll2bjet;
  

  f_chain->SetBranchAddress("met", &k_met);
  f_chain->SetBranchAddress("ee_mass", &k_eemass);
  f_chain->SetBranchAddress("eejj_mass", &k_eejjmass);
  f_chain->SetBranchAddress("e1jj_mass", &k_e1jjmass);
  f_chain->SetBranchAddress("e2jj_mass", &k_e2jjmass);
  f_chain->SetBranchAddress("jj_mass", &k_jjmass);
  f_chain->SetBranchAddress("st", &k_st);
  f_chain->SetBranchAddress("ht", &k_ht);
  f_chain->SetBranchAddress("njet", &k_njet);
  f_chain->SetBranchAddress("nbjet_m", &k_nbjet_m);
  f_chain->SetBranchAddress("el1_eta", &k_el1eta);
  f_chain->SetBranchAddress("el2_eta", &k_el2eta);
  f_chain->SetBranchAddress("el1_pt", &k_el1pt);
  f_chain->SetBranchAddress("el2_pt", &k_el2pt);
  f_chain->SetBranchAddress("jet1_pt", &k_j1pt);
  f_chain->SetBranchAddress("weight", &k_weight);
  f_chain->SetBranchAddress("el1_clbjet", &k_cl1bjet);
  f_chain->SetBranchAddress("el2_clbjet", &k_cl2bjet);
  f_chain->SetBranchAddress("el1_cllbjet", &k_cll1bjet);
  f_chain->SetBranchAddress("el2_cllbjet", &k_cll2bjet);

  

  f_chainmc->SetBranchAddress("met", &k_met);
  f_chainmc->SetBranchAddress("ee_mass", &k_eemass);
  f_chainmc->SetBranchAddress("eejj_mass", &k_eejjmass);
  f_chainmc->SetBranchAddress("e1jj_mass", &k_e1jjmass);
  f_chainmc->SetBranchAddress("e2jj_mass", &k_e2jjmass);
  f_chainmc->SetBranchAddress("jj_mass", &k_jjmass);
  f_chainmc->SetBranchAddress("st", &k_st);
  f_chainmc->SetBranchAddress("ht", &k_ht);
  f_chainmc->SetBranchAddress("njet", &k_njet);
  f_chainmc->SetBranchAddress("el1_pt", &k_el1pt);
  f_chainmc->SetBranchAddress("el2_pt", &k_el2pt);
  f_chainmc->SetBranchAddress("el1_eta", &k_el1eta);
  f_chainmc->SetBranchAddress("el2_eta", &k_el2eta);
  f_chainmc->SetBranchAddress("jet1_pt", &k_j1pt);
  f_chainmc->SetBranchAddress("weight", &k_weight);
  f_chainmc->SetBranchAddress("el1_clbjet", &k_cl1bjet);
  f_chainmc->SetBranchAddress("el2_clbjet", &k_cl2bjet);
  f_chainmc->SetBranchAddress("el1_cllbjet", &k_cll1bjet);
  f_chainmc->SetBranchAddress("el2_cllbjet", &k_cll2bjet);


  f_chainsig->SetBranchAddress("met", &k_met);
  f_chainsig->SetBranchAddress("ee_mass", &k_eemass);
  f_chainsig->SetBranchAddress("eejj_mass", &k_eejjmass);
  f_chainsig->SetBranchAddress("e1jj_mass", &k_e1jjmass);
  f_chainsig->SetBranchAddress("e2jj_mass", &k_e2jjmass);
  f_chainsig->SetBranchAddress("jj_mass", &k_jjmass);
  f_chainsig->SetBranchAddress("st", &k_st);
  f_chainsig->SetBranchAddress("ht", &k_ht);
  f_chainsig->SetBranchAddress("njet", &k_njet);
  f_chainsig->SetBranchAddress("el1_pt", &k_el1pt);
  f_chainsig->SetBranchAddress("el2_pt", &k_el2pt);
  f_chainsig->SetBranchAddress("el1_eta", &k_el1eta);
  f_chainsig->SetBranchAddress("el2_eta", &k_el2eta);
  f_chainsig->SetBranchAddress("jet1_pt", &k_j1pt);
  f_chainsig->SetBranchAddress("weight", &k_weight);
  f_chainsig->SetBranchAddress("el1_clbjet", &k_cl1bjet);
  f_chainsig->SetBranchAddress("el2_clbjet", &k_cl2bjet);
  f_chainsig->SetBranchAddress("el1_cllbjet", &k_cll1bjet);
  f_chainsig->SetBranchAddress("el2_cllbjet", &k_cll2bjet);


  float sum_event =0.;
  for(Int_t i = 0; i < f_chain->GetEntries(); i++){
    f_chain->GetEntry(i) ;
    
    if( (i % 100000) == 0) cout << "Bkg: N processing = " << i << endl;
    sum_event+= k_weight;
  }
  
  for(Int_t i = 0; i < f_chainmc->GetEntries(); i++){
    f_chainmc->GetEntry(i) ;

    if( (i % 100000) == 0) cout << "Bkg: N processing = " << i << endl;
    sum_event+= k_weight;
  }

  
  float sum_sigevent =0.;
  for(Int_t i = 0; i < f_chainsig->GetEntries(); i++){
    f_chainsig->GetEntry(i) ;

    if( (i % 100000) == 0) cout << "Sig: N processing = " << i << endl;
    sum_sigevent+=k_weight;
  }

  cout << "Total bkg = " << sum_event  << endl;
  cout << "Total sig = " <<  sum_sigevent << endl;
  

  std::vector<float> METcut;
  METcut.push_back(35.);

  
  int imet_opt=0;
  float imeejjmin_opt=0.;
  float imeejjmax_opt=0.;
  float ipt1_opt=0.;
  float ipt2_opt=0.;
  float ipt3_opt=0.;

  float sig_eff_opt=0.;
  float sig_eff_opt_presel=0.;
  float cut_sum_opt=0.;
  float opt_cut_sb=0.;
  float ieemin_opt=0.;
  float ieemax_opt=0.;
  float ie2jjmin_opt=0.;
  float ie2jjmax_opt=0.;
  float ie1jjmin_opt=0.;
  float ie1jjmax_opt=0.;
  float istmin_opt=0.;
  float istmax_opt=0.;
  float ihtmin_opt=0.;
  float ihtmax_opt=0.;
  float ijetpt_opt=0.;
  int injet_opt=0.;
  bool clbjet_opt=false;


  TH1* hnsig =   (TH1F*)file->Get(("eventcutflow"));
  
  float nsig = float(hnsig->GetBinContent(2));
  cout << "Number of signal events before any cut = " << nsig << endl; 
  
  for(unsigned int imet=0; imet < METcut.size(); imet++){
    float met_cut = METcut.at(imet);
    cout << "MET : "<< met_cut << endl;
    for(int imeejjmin= 0; imeejjmin < 1 ; imeejjmin++){
      float meejjmin_cut = 290. + float(imeejjmin) * 10.;
      for(int imeejjmax= 0; imeejjmax <1. ; imeejjmax++){
	float meejjmax_cut = 10000.+ float(imeejjmax)*5.;
	cout << meejjmin_cut <<   "  < M(eejj) < "<< meejjmax_cut << endl;
	for(int ipt1= 0; ipt1 <1. ; ipt1++){
	  float pt1_cut =  70. + float(ipt1)*5.;
	  for(int ipt2= 0; ipt2 < 1. ; ipt2++){
	    float pt2_cut =  45. + float(ipt2)*5.;
	    if(pt2_cut > pt1_cut) continue;
	    
	    cout << "pt1_cut = " << pt1_cut << " pt2_cut = " << pt2_cut << endl;
	    
	    float pt3_cut = pt2_cut;
	    
	    cout << "pt3_cut  =  " << pt3_cut << endl;
	    for(int ieemin =0 ; ieemin < 1; ieemin++){
	      float eemin_cut =  30. + float(ieemin)* 5.;
	      if(ieemin == 7) eemin_cut = 100.;
	      
		for(int ieemax =0 ; ieemax <1 ; ieemax++){
		  float eemax_cut =  10000000. + float(ieemax) * 5. ;
		  
		  cout << eemin_cut << " <  ee < " <<   eemax_cut << endl;
		  
		  for(int ie1jjmin =0 ; ie1jjmin < 1 ; ie1jjmin++){
		    float e1jjmin_cut = 0. + float(ie1jjmin)* 10.;
		    
		    for(int ie1jjmax =0 ; ie1jjmax < 1 ; ie1jjmax++){
		      float e1jjmax_cut =  10000. + float(ie1jjmax)* 10.;
		      
		      for(int ie2jjmin =0; ie2jjmin < 1 ; ie2jjmin++){
			float e2jjmin_cut = 0. + float(ie2jjmin)* 10.;
			
			for(int ie2jjmax =0; ie2jjmax <1 ; ie2jjmax++){
			  float e2jjmax_cut =  10050. + float(ie2jjmax)* 10.;
			  if(ie2jjmax == 10) e2jjmax_cut = 10000.;
			  
			  for(int ihtmin =0 ; ihtmin < 1 ; ihtmin++){
			  float htmin_cut = 0. + float(ihtmin)*5.;
			  for(int ihtmax =16 ; ihtmax < 17 ; ihtmax++){
			    float htmax_cut =10000. + float(ihtmax)*25.;
			    for(int istmin =0; istmin < 1 ; istmin++){
			      float stmin_cut = float(istmin)*10.;  
			      for(int istmax =0 ; istmax < 1 ; istmax++){
				float stmax_cut =1000. + float(istmax) *10.;
				
				for(int ijpt =0 ; ijpt <1 ; ijpt++){
				  float jetpt_cut = 20. + float(ijpt)*5.;
				  
				  for(int injet = 10 ; injet< 11 ; injet ++){
				    for(int iclj = 0 ; iclj< 1 ; iclj ++){
				      bool check_closebjet = false;
                                      if(iclj == 1) check_closebjet= true;
				      
				      /// Optmise cuts:
				      float cut_sum=0.;
				      float np_sum=0.;
				      int n_mc=0;
				      for(Int_t i = 0; i < f_chain->GetEntries(); i++){
					f_chain->GetEntry(i) ;
					if(k_eemass > 80. && k_eemass < 100) continue;
					if(k_jjmass > 110.) continue;
					if(k_jjmass < 50.) continue;
					if(k_nbjet_m !=0) continue;
					if(check_closebjet){
					  if(k_cl1bjet ||k_cl2bjet) continue;
					}
					if(k_e1jjmass < e1jjmin_cut) continue;
					if(k_e1jjmass > e1jjmax_cut) continue;
					if(k_e2jjmass < e2jjmin_cut) continue;
					if(k_e2jjmass > e2jjmax_cut) continue;
					if(k_eemass < eemin_cut) continue;
					if(k_eemass > eemax_cut) continue;
					if(k_met > met_cut) continue;
					if(k_eejjmass < meejjmin_cut) continue;
					if(k_eejjmass > meejjmax_cut) continue;
					if(k_st <  stmin_cut) continue;
					if(k_st >  stmax_cut) continue;
					if(k_ht <  htmin_cut) continue;
					if(k_ht >  htmax_cut) continue;
					if(k_j1pt < jetpt_cut) continue;
					if(k_el1pt < pt1_cut) continue;
					if(fabs(k_el2eta) < 1.5){
					  if(k_el2pt < pt2_cut) continue;
					}
					else{
					  if(k_el2pt < pt3_cut) continue;
					}
					
					if(k_njet> injet) continue;
					cut_sum+=k_weight;
					np_sum+=k_weight;
				      }
				      
				      for(Int_t i = 0; i < f_chainmc->GetEntries(); i++){
					f_chainmc->GetEntry(i) ;

					if(k_jjmass > 110.) continue;
                                        if(k_jjmass < 50.) continue;
					if(k_eemass > 80. && k_eemass < 100) continue;
					if(k_eemass < eemin_cut) continue;
					if(k_eemass > eemax_cut) continue;
					
					if(check_closebjet){
					  if(k_cl1bjet ||k_cl2bjet) continue;
					}	
					if(k_nbjet_m !=0) continue;
					if(k_e1jjmass < e1jjmin_cut) continue;
					if(k_e1jjmass > e1jjmax_cut) continue;
					if(k_e2jjmass < e2jjmin_cut) continue;
					if(k_e2jjmass > e2jjmax_cut) continue;
					if(k_met > met_cut) continue;
					if(k_eejjmass < meejjmin_cut) continue;
					if(k_eejjmass > meejjmax_cut) continue;
					if(k_st <  stmin_cut) continue;
					if(k_st >  stmax_cut) continue;
					if(k_ht <  htmin_cut) continue;
					if(k_ht >  htmax_cut) continue;
					if(k_j1pt < jetpt_cut) continue;
					if(k_el1pt < pt1_cut) continue;
					if(fabs(k_el2eta) < 1.5){
					  if(k_el2pt < pt2_cut) continue;
					}
					else{
					  if(k_el2pt < pt3_cut) continue;
					}
					
					if(k_njet> injet) continue;
					n_mc += 1;
					cut_sum+=k_weight;
				      }
				      
				      float cut_sum_sig=0.;
				      for(Int_t i = 0; i < f_chainsig->GetEntries(); i++){
					f_chainsig->GetEntry(i) ;
					if(k_eemass > 80. && k_eemass < 100) continue;
					if(k_jjmass > 110.) continue;
                                        if(k_jjmass < 50.) continue;

					if(check_closebjet){
					  if(k_cl1bjet ||k_cl2bjet) continue;
					}

					if(k_e1jjmass < e1jjmin_cut) continue;
					if(k_e1jjmass > e1jjmax_cut) continue;
					if(k_e2jjmass < e2jjmin_cut) continue;
					if(k_e2jjmass > e2jjmax_cut) continue;
					
					if(k_nbjet_m !=0) continue;
					if(k_eemass < eemin_cut) continue;
					if(k_eemass > eemax_cut) continue;
					
					if(k_met > met_cut)continue;
					
					
					if(k_eejjmass < meejjmin_cut) continue;
					if(k_eejjmass > meejjmax_cut) continue;
					if(k_st <  stmin_cut) continue;
					if(k_st >  stmax_cut) continue;
					if(k_ht <  htmin_cut) continue;
					if(k_ht >  htmax_cut) continue;
					if(k_j1pt < jetpt_cut) continue;
					
					if(k_el1pt < pt1_cut) continue;
					
					if(fabs(k_el2eta) < 1.5){
					  if(k_el2pt < pt2_cut) continue;
					}
					else{
					  if(k_el2pt < pt3_cut) continue;
					}
					
					if(k_njet> injet) continue;
					
					cut_sum_sig+=k_weight;
				      }
				      
				      float sig_eff = cut_sum_sig /nsig ;
				      float total_bkg = cut_sum;
				      float bkgtmp = total_bkg + (0.28* np_sum)* (0.28* np_sum);
				      float denom = 1. + sqrt(bkgtmp);
				      float punzi = sig_eff / denom;
				      
				      cout << cut_sum_sig / sum_sigevent << endl;
				      if( (cut_sum_sig / sum_sigevent) < 0.3) continue;
				      
				      if( (punzi) > opt_cut_sb){
					opt_cut_sb = punzi;
					imet_opt = imet;
					injet_opt = injet;
					imeejjmin_opt = meejjmin_cut;
					imeejjmax_opt = meejjmax_cut;
					ipt1_opt=  pt1_cut;
					ipt2_opt=  pt2_cut;
					ipt3_opt=  pt3_cut;
					clbjet_opt = check_closebjet;
					
					ieemin_opt =  eemin_cut;
					ieemax_opt =  eemax_cut;
					ie1jjmin_opt = e1jjmin_cut;
					ie1jjmax_opt = e1jjmax_cut;
					ie2jjmin_opt = e2jjmin_cut;
					ie2jjmax_opt = e2jjmax_cut;
					istmin_opt = stmin_cut;
					istmax_opt = stmax_cut;
					ihtmin_opt = htmin_cut;
					ihtmax_opt = htmax_cut;
					ijetpt_opt = jetpt_cut;
					sig_eff_opt = sig_eff;
					
					sig_eff_opt_presel = cut_sum_sig / sum_sigevent;
					cut_sum_opt= cut_sum;
					cout << "Max punzi = " << punzi << " : nbkg = " << total_bkg <<  " : %sig = " << sig_eff_opt_presel*100. << endl;
					
				      }
				    }
				  }
				  
				}//jetpt
			      }
			    }
			}
		      }//stmax
		    }//stmin
		  }//e2jjmax
		}//eemax
	      }//eemin
	    }//pt2
	    }//pt1
	  }// meejjmax
	}/// meejjmin
      }/// MET 
    }
  }
  //Opt cut
  cout << "Opt punzi = " << opt_cut_sb << endl;
  cout << "Opt cut : MET <  " << METcut.at(imet_opt) << endl;
  cout << "Opt cut : njet <  " << injet_opt<< endl;
  cout << "Opt cut : " << imeejjmin_opt << " < M(eejj) <  " << imeejjmax_opt << endl;
  cout << "Opt cut : " << ie1jjmin_opt << " < M(e1jj) <  " << ie1jjmax_opt << endl;
  cout << "Opt cut : " << ie2jjmin_opt << " < M(e2jj) <  " << ie2jjmax_opt << endl;
  cout << "Opt cut : " << ieemin_opt << " < M(ee) < " << ieemax_opt<< endl;
  cout << "Opt cut : " << istmin_opt << " < ST < " << istmax_opt<< endl;
  cout << "Opt cut : " << ihtmin_opt << " < HT < " << ihtmax_opt<< endl;
  cout << "clbjet_opt = " << clbjet_opt << endl;

  
  cout << "Number of mc = " << n_mc << endl;

  cout << "Opt pt1 = " << ipt1_opt << endl;
  cout << "Opt pt2 = " << ipt2_opt << endl;
  cout << "Opt pt2 (endcap) = " << ipt3_opt << endl;

  cout << "Opt jet1pt = " << ijetpt_opt << endl;
  cout << "Cut (opt) eff. bkg = " << cut_sum_opt/sum_event  <<  " nbkg = " << cut_sum_opt << endl;
  cout << "Cut eff .sig = " <<  sig_eff_opt << " : wrt preselection "<< sig_eff_opt_presel*100 <<  endl;
  
  
}
コード例 #20
0
void
RockPhysicsInversion4D::SetGridValue(int TableNr,int i0,int i1,int i2,int i3,double value)
{
  meanRockPrediction_(TableNr,i0)->setRealValue(i1,i2,i3,float(value));
}
コード例 #21
0
/// Only _static_ data is sent in this packet !!!
void WorldSession::HandleCreatureQueryOpcode(WorldPacket & recv_data)
{
    uint32 entry;
    recv_data >> entry;
    uint64 guid;
    recv_data >> guid;

    CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(entry);
    if (ci)
    {
        std::string Name, SubName;
        Name = ci->Name;
        SubName = ci->SubName;

        int loc_idx = GetSessionDbLocaleIndex();
        if (loc_idx >= 0)
        {
            if (CreatureLocale const* cl = sObjectMgr->GetCreatureLocale(entry))
            {
                ObjectMgr::GetLocaleString(cl->Name, loc_idx, Name);
                ObjectMgr::GetLocaleString(cl->SubName, loc_idx, SubName);
            }
        }
        sLog->outDetail("WORLD: CMSG_CREATURE_QUERY '%s' - Entry: %u.", ci->Name.c_str(), entry);
                                                            // guess size
        WorldPacket data(SMSG_CREATURE_QUERY_RESPONSE, 100);
        data << uint32(entry);                              // creature entry
        data << Name;
        data << uint8(0) << uint8(0) << uint8(0);           // name2, name3, name4, always empty
        data << SubName;
        data << ci->IconName;                               // "Directions" for guard, string for Icons 2.3.0
        data << uint32(ci->type_flags);                     // flags
        data << uint32(ci->type);                           // CreatureType.dbc
        data << uint32(ci->family);                         // CreatureFamily.dbc
        data << uint32(ci->rank);                           // Creature Rank (elite, boss, etc)
        data << uint32(ci->KillCredit[0]);                  // new in 3.1, kill credit
        data << uint32(ci->KillCredit[1]);                  // new in 3.1, kill credit
        data << uint32(ci->Modelid1);                       // Modelid1
        data << uint32(ci->Modelid2);                       // Modelid2
        data << uint32(ci->Modelid3);                       // Modelid3
        data << uint32(ci->Modelid4);                       // Modelid4
        data << float(ci->ModHealth);                       // dmg/hp modifier
        data << float(ci->ModMana);                         // dmg/mana modifier
        data << uint8(ci->RacialLeader);
        for (uint32 i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i)
            data << uint32(ci->questItems[i]);              // itemId[6], quest drop
        data << uint32(ci->movementId);                     // CreatureMovementInfo.dbc
        data << uint32(ci->expansion);                      // client will not allow interaction if this value is not in line with its stored exp
        SendPacket(&data);
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_CREATURE_QUERY_RESPONSE");
    }
    else
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_CREATURE_QUERY - NO CREATURE INFO! (GUID: %u, ENTRY: %u)",
            GUID_LOPART(guid), entry);
        WorldPacket data(SMSG_CREATURE_QUERY_RESPONSE, 4);
        data << uint32(entry | 0x80000000);
        SendPacket(&data);
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_CREATURE_QUERY_RESPONSE");
    }
}
コード例 #22
0
void
RockPhysicsInversion4D::AddToGridValue(int TableNr,int i0,int i1,int i2,int i3,double value)
{
  double newValue=meanRockPrediction_(TableNr,i0)->getRealValue(i1,i2,i3)+value;
  meanRockPrediction_(TableNr,i0)->setRealValue(i1,i2,i3,float(newValue));
}
コード例 #23
0
void OceanSurface::updateOcean(float t) {
	if (!gpu) {

		for (int i = 0; i < N; i++) {
			float k_x = float(M_PI) * (2.0f * i - N) / L_x; // x-coordinate of wavevector at 'pos'

			for (int j = 0; j < M; j++) {
				int pos = i * M + j;

				float k_z = M_PI * (2.0f * j - M) / L_z; // z-coordinate of wavevector at 'pos'
				float k_length = sqrtf(k_x * k_x + k_z * k_z); // length of wavevector 'k'

				// calc all complex amplitudes in time t
				h_fft[pos] = h_t(i, j, t);

				// calc all displacements in time t
				if (k_length < 0.000001) { // ignore small wavevectors, put (0, 0) displacement
					dx_fft[pos] = complex_number();
					dz_fft[pos] = complex_number();
				}
				else { // calculate displacement via formula
					dx_fft[pos] = complex_number(0.0f, -k_x / k_length) * h_fft[pos];
					dz_fft[pos] = complex_number(0.0f, -k_z / k_length) * h_fft[pos];
				}

				// calc x-, and z- component of gradient of h_fft
				gradient_x[pos] = complex_number(0.0f, k_x) * h_fft[pos];
				gradient_z[pos] = complex_number(0.0f, k_z) * h_fft[pos];
			}
		}

		// row flipping
		/*/complex_number *h_fft_2 = new complex_number[N * N];
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				int pos_1 = i * M + j;
				int pos_2 = (N - i - 1) * M + j;
				h_fft_2[pos_2] = h_fft[pos_1];
			}
		}*/
	} 
	else {

		// first update height map with time amplitudes (and displacement map with gradient map);
		glUseProgram(upd_height_program);

		glUniform1f(total_time_location, t);
		// height map
		glBindImageTexture(0, texture_H_t0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, texture_H_t0_cc, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(2, texture_H_t, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);

		// displacement map
		glBindImageTexture(3, texture_Dx, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glBindImageTexture(4, texture_Dz, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);

		// gradient map
		glBindImageTexture(5, texture_Gradx, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glBindImageTexture(6, texture_Gradz, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);

		glDispatchCompute(N, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		glUseProgram(0);

		// fft in compute shader
		glUseProgram(fft_comp_program);

		// update texture
		/*glBindTexture(GL_TEXTURE_2D, texture_H_t);
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, N, N, GL_RG, GL_FLOAT, h_fft);
		//glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32F, N, N, 0, GL_RG, GL_FLOAT, h_fft);
		glBindTexture(GL_TEXTURE_2D, 0);*/


		// bind reverse indices
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, rev_ind_buffer);

		/*______________HEIGHT MAP FFT________________*/

		// fft per rows
		glUniform1i(fft_column_location, 0);
		glBindImageTexture(0, texture_H_t, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, texture_H_fft_t_row, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		// fft per columns
		glUniform1i(fft_column_location, 1);
		glBindImageTexture(0, texture_H_fft_t_row, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, texture_H_fft_t_col, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		/*______________DISPLACEMENT-X MAP FFT________________*/

		// fft per rows
		glUniform1i(fft_column_location, 0);
		glBindImageTexture(0, texture_Dx, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_dx_fft_row, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		// fft per columns
		glUniform1i(fft_column_location, 1);
		glBindImageTexture(0, tex_dx_fft_row, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_dx_fft, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		/*______________DISPLACEMENT-Z MAP FFT________________*/

		// fft per rows
		glUniform1i(fft_column_location, 0);
		glBindImageTexture(0, texture_Dz, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_dz_fft_row, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		// fft per columns
		glUniform1i(fft_column_location, 1);
		glBindImageTexture(0, tex_dz_fft_row, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_dz_fft, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		/*______________GRADIENT-X MAP FFT________________*/

		// fft per rows
		glUniform1i(fft_column_location, 0);
		glBindImageTexture(0, texture_Gradx, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_gradx_fft_row, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		// fft per columns
		glUniform1i(fft_column_location, 1);
		glBindImageTexture(0, tex_gradx_fft_row, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_gradx_fft, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		/*______________GRADIENT-Z MAP FFT________________*/

		// fft per rows
		glUniform1i(fft_column_location, 0);
		glBindImageTexture(0, texture_Gradz, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_gradz_fft_row, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		// fft per columns
		glUniform1i(fft_column_location, 1);
		glBindImageTexture(0, tex_gradz_fft_row, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RG32F);
		glBindImageTexture(1, tex_gradz_fft, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RG32F);
		glDispatchCompute(1, N, 1);
		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);

		glUseProgram(0);
	}

	int error = glGetError();
	if (error != GL_NO_ERROR) {
		int b = 4;
	}

	if (gpu) {
		return;
	}
	for (unsigned int i = 0; i < N; i++) { // horizontal fft for rows
		/*fft->fft(h_fft, h_fft, 1, i * M);
		fft->fft(dx_fft, dx_fft, 1, i * M);
		fft->fft(dz_fft, dz_fft, 1, i * M);
		fft->fft(gradient_x, gradient_x, 1, i * M);
		fft->fft(gradient_z, gradient_z, 1, i * M);*/
		myFFT->processVertical(h_fft, 1, i * M);
		myFFT->processVertical(dx_fft, 1, i * M);
		myFFT->processVertical(dz_fft, 1, i * M);
		myFFT->processVertical(gradient_x, 1, i * M);
		myFFT->processVertical(gradient_z, 1, i * M);
	}

	for (unsigned int j = 0; j < M; j++) { // vertical fft for columns
		/*fft->fft(h_fft, h_fft, M, j);
		fft->fft(dx_fft, dx_fft, M, j);
		fft->fft(dz_fft, dz_fft, M, j);
		fft->fft(gradient_x, gradient_x, M, j);
		fft->fft(gradient_z, gradient_z, M, j);*/
		myFFT->processHorizontal(h_fft, M, j);
		myFFT->processHorizontal(dx_fft, M, j);
		myFFT->processHorizontal(dz_fft, M, j);
		myFFT->processHorizontal(gradient_x, M, j);
		myFFT->processHorizontal(gradient_z, M, j);
	}

	
	glm::vec3 normal; // temp variable for normal calculation
	int sign;
	float signs[] = { 1.0f, -1.0f };
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++) {
			int pos = i * M + j;

			// flip sign for height
			sign = signs[(i + j) & 1];
			grid[pos].y = h_fft[pos].re * sign;

			// flip sign for displacement
			dx_fft[pos] = dx_fft[pos] * sign;
			dz_fft[pos] = dz_fft[pos] * sign;
			// then calc displacement for original position in grid
			//grid[pos].x = init_positions[pos].x + lambda * dx_fft[pos].re;
			//grid[pos].z = init_positions[pos].z + lambda * dz_fft[pos].re;

			// flip sign for gradient component;
			gradient_x[pos] = gradient_x[pos] * sign;
			gradient_z[pos] = gradient_z[pos] * sign;

			// then calculate normal of vertex and normalize it
			normal = glm::vec3(-gradient_x[pos].re, 1.0f, -gradient_z[pos].re);
			normal = glm::normalize(normal);
			// and save it to vertex structure
			grid[pos].normal_x = normal.x;
			grid[pos].normal_y = normal.y;
			grid[pos].normal_z = normal.z;
		}
	}
}
コード例 #24
0
void
RockPhysicsInversion4D::DivideAndSmoothTable(int tableInd,std::vector<std::vector<double> > priorDistribution, std::vector<fftw_complex*> smoothingFilter)
{
  for (int j=0; j<nf_[0]; j++){
      meanRockPrediction_(tableInd,j)->setAccessMode(FFTGrid::RANDOMACCESS);
   }

  int cnfp=nfp_/2+1;
  int rnfp=2*cnfp;

  fftw_real*    rTemp = static_cast<fftw_real*>(fftw_malloc(sizeof(float)*rnfp));
  fftw_complex* cTemp = reinterpret_cast<fftw_complex*>(rTemp);

  double minDivisor = 1e-3;

  LogKit::LogFormatted(LogKit::Low,"\n Smoothing direction 1 of 4\n");
  float monitorSize = std::max(1.0f, static_cast<float>(nf_[0]*nf_[1]*nf_[2]*nf_[3])*0.02f);
  float nextMonitor = monitorSize;
  std::cout
    << "\n  0%       20%       40%       60%       80%      100%"
    << "\n  |    |    |    |    |    |    |    |    |    |    |  "
    << "\n  ^";

  // divide and smooth direction1
  for(int i1=0;i1<nf_[1];i1++)
    for(int i2=0;i2<nf_[2];i2++)
      for(int i3=0;i3<nf_[3];i3++)
      {
        for(int i0=0;i0<nf_[0];i0++)
        {
          double divisor=std::max(minDivisor,priorDistribution_[0][i0]);
          rTemp[i0]=float(GetGridValue(tableInd,i0,i1,i2,i3)/ divisor);
        }
        for(int i0=nf_[0];i0<nfp_;i0++)
          rTemp[i0]=0.0f;

        rfftwnd_one_real_to_complex(fftplan1_,rTemp,cTemp);

        for(int i0=0;i0<cnfp;i0++)
        {
          cTemp[i0].re=cTemp[i0].re*smoothingFilter[0][i0].re;
          cTemp[i0].im=cTemp[i0].im*smoothingFilter[0][i0].re;
        }

        rfftwnd_one_complex_to_real(fftplan2_,cTemp,rTemp);
        for(int i0=0;i0<nf_[0];i0++)
        {
          SetGridValue(tableInd,i0,i1,i2,i3, rTemp[i0]);
          if ( i1*nf_[2]*nf_[3]*nf_[0] +i2*nf_[3]*nf_[0]+ i3*nf_[0] + i0 + 1 >= static_cast<int>(nextMonitor)) {
            nextMonitor += monitorSize;
            std::cout << "^";
          }
        }
      }

  LogKit::LogFormatted(LogKit::Low,"\n\n Smoothing direction 2 of 4\n");
  monitorSize = std::max(1.0f, static_cast<float>(nf_[0]*nf_[1]*nf_[2]*nf_[3])*0.02f);
  nextMonitor = monitorSize;
  std::cout
    << "\n  0%       20%       40%       60%       80%      100%"
    << "\n  |    |    |    |    |    |    |    |    |    |    |  "
    << "\n  ^";

  // divide and smoothdirection2
  for(int i0=0;i0<nf_[0];i0++)
    for(int i2=0;i2<nf_[2];i2++)
      for(int i3=0;i3<nf_[3];i3++)
      {
        for(int i1=0;i1<nf_[1];i1++)
        {
          double divisor=std::max(minDivisor,priorDistribution_[1][i1]);
          rTemp[i1]=float(GetGridValue(tableInd,i0,i1,i2,i3)/divisor);
        }
        for(int i1=nf_[1];i1<nfp_;i1++)
          rTemp[i1]=0.0f;

        rfftwnd_one_real_to_complex(fftplan1_,rTemp,cTemp);

        for(int i1=0;i1<cnfp;i1++)
        {
          cTemp[i1].re=cTemp[i1].re*smoothingFilter[1][i1].re;
          cTemp[i1].im=cTemp[i1].im*smoothingFilter[1][i1].re;
        }

        rfftwnd_one_complex_to_real(fftplan2_,cTemp,rTemp);
        for(int i1=0;i1<nf_[1];i1++)
        {
          SetGridValue(tableInd,i0,i1,i2,i3, rTemp[i1]);
          if ( i0*nf_[2]*nf_[3]*nf_[1] +i2*nf_[3]*nf_[1]+ i3*nf_[1] + i1 + 1 >= static_cast<int>(nextMonitor)) {
            nextMonitor += monitorSize;
            std::cout << "^";
          }
        }
      }

  LogKit::LogFormatted(LogKit::Low,"\n\n Smoothing direction 3 of 4\n");
  monitorSize = std::max(1.0f, static_cast<float>(nf_[0]*nf_[1]*nf_[2]*nf_[3])*0.02f);
  nextMonitor = monitorSize;
  std::cout
    << "\n  0%       20%       40%       60%       80%      100%"
    << "\n  |    |    |    |    |    |    |    |    |    |    |  "
    << "\n  ^";

  //  divide and smoothdirection 3
  for(int i0=0;i0<nf_[0];i0++)
    for(int i1=0;i1<nf_[1];i1++)
      for(int i3=0;i3<nf_[3];i3++)
      {
        for(int i2=0;i2<nf_[2];i2++)
        {
          double divisor=std::max(minDivisor,priorDistribution_[2][i2]);
          rTemp[i2]=float(GetGridValue(tableInd,i0,i1,i2,i3)/divisor);

        }
        for(int i2=nf_[2];i2<nfp_;i2++)
          rTemp[i2]=0.0f;

        rfftwnd_one_real_to_complex(fftplan1_,rTemp,cTemp);

        for(int i2=0;i2<cnfp;i2++)
        {
          cTemp[i2].re=cTemp[i2].re*smoothingFilter[2][i2].re;
          cTemp[i2].im=cTemp[i2].im*smoothingFilter[2][i2].re;
        }

        rfftwnd_one_complex_to_real(fftplan2_,cTemp,rTemp);
        for(int i2=0;i2<nf_[2];i2++)
        {
          SetGridValue(tableInd,i0,i1,i2,i3, rTemp[i2]);
          if ( i0*nf_[1]*nf_[3]*nf_[2] +i1*nf_[3]*nf_[2]+ i3*nf_[2] + i2 + 1 >= static_cast<int>(nextMonitor)) {
            nextMonitor += monitorSize;
            std::cout << "^";
          }
        }
      }

  LogKit::LogFormatted(LogKit::Low,"\n Smoothing last direction \n");
  monitorSize = std::max(1.0f, static_cast<float>(nf_[0]*nf_[1]*nf_[2]*nf_[3])*0.02f);
  nextMonitor = monitorSize;
  std::cout
    << "\n  0%       20%       40%       60%       80%      100%"
    << "\n  |    |    |    |    |    |    |    |    |    |    |  "
    << "\n  ^";
 //  divide and smoothdirection 4
   for(int i0=0;i0<nf_[0];i0++)
    for(int i1=0;i1<nf_[1];i1++)
      for(int i2=0;i2<nf_[2];i2++)
      {
        for(int i3=0;i3<nf_[3];i3++)
        {
          double divisor=std::max(minDivisor,priorDistribution_[3][i3]);
          rTemp[i3]=float(GetGridValue(tableInd,i0,i1,i2,i3)/divisor);
        }
        for(int i3=nf_[3];i3<nfp_;i3++)
          rTemp[i3]=0.0f;

        rfftwnd_one_real_to_complex(fftplan1_,rTemp,cTemp);

        for(int i3=0;i3<cnfp;i3++)
        {
          cTemp[i3].re=cTemp[i3].re*smoothingFilter[3][i3].re;
          cTemp[i3].im=cTemp[i3].im*smoothingFilter[3][i3].re;
        }

        rfftwnd_one_complex_to_real(fftplan2_,cTemp,rTemp);
        for(int i3=0;i3<nf_[3];i3++)
        {
          SetGridValue(tableInd,i0,i1,i2,i3, rTemp[i3]);
          if ( i0*nf_[1]*nf_[2]*nf_[3] +i1*nf_[2]*nf_[3]+ i2*nf_[3] + i3 + 1 >= static_cast<int>(nextMonitor)) {
            nextMonitor += monitorSize;
            std::cout << "^";
          }
        }
      }

  for (int j=0; j<nf_[0]; j++){
      meanRockPrediction_(tableInd,j)->endAccess();
  }

  fftw_free(rTemp);

}
コード例 #25
0
ファイル: bump.cpp プロジェクト: dcoretti/bgfx
int _main_(int /*_argc*/, char** /*_argv*/)
{
	uint32_t width = 1280;
	uint32_t height = 720;
	uint32_t debug = BGFX_DEBUG_TEXT;
	uint32_t reset = BGFX_RESET_VSYNC;

	bgfx::init();
	bgfx::reset(width, height, reset);

	// Enable debug text.
	bgfx::setDebug(debug);

	// Set view 0 clear state.
	bgfx::setViewClear(0
		, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
		, 0x303030ff
		, 1.0f
		, 0
		);

	// Get renderer capabilities info.
	const bgfx::Caps* caps = bgfx::getCaps();
	bool instancingSupported = 0 != (caps->supported & BGFX_CAPS_INSTANCING);

	// Create vertex stream declaration.
	PosNormalTangentTexcoordVertex::init();

	calcTangents(s_cubeVertices
		, BX_COUNTOF(s_cubeVertices)
		, PosNormalTangentTexcoordVertex::ms_decl
		, s_cubeIndices
		, BX_COUNTOF(s_cubeIndices)
		);

	// Create static vertex buffer.
	bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(
		  bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
		, PosNormalTangentTexcoordVertex::ms_decl
		);

	// Create static index buffer.
	bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );

	// Create texture sampler uniforms.
	bgfx::UniformHandle u_texColor  = bgfx::createUniform("u_texColor",  bgfx::UniformType::Int1);
	bgfx::UniformHandle u_texNormal = bgfx::createUniform("u_texNormal", bgfx::UniformType::Int1);

	uint16_t numLights = 4;
	bgfx::UniformHandle u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Vec4, numLights);
	bgfx::UniformHandle u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Vec4, numLights);

	// Create program from shaders.
	bgfx::ProgramHandle program = loadProgram(instancingSupported ? "vs_bump_instanced" : "vs_bump", "fs_bump");

	// Load diffuse texture.
	bgfx::TextureHandle textureColor = loadTexture("fieldstone-rgba.dds");

	// Load normal texture.
	bgfx::TextureHandle textureNormal = loadTexture("fieldstone-n.dds");

	int64_t timeOffset = bx::getHPCounter();

	while (!entry::processEvents(width, height, debug, reset) )
	{
		// Set view 0 default viewport.
		bgfx::setViewRect(0, 0, 0, width, height);

		// This dummy draw call is here to make sure that view 0 is cleared
		// if no other draw calls are submitted to view 0.
		bgfx::submit(0);

		int64_t now = bx::getHPCounter();
		static int64_t last = now;
		const int64_t frameTime = now - last;
		last = now;
		const double freq = double(bx::getHPFrequency() );
		const double toMs = 1000.0/freq;

		float time = (float)( (now-timeOffset)/freq);

		// Use debug font to print information about this example.
		bgfx::dbgTextClear();
		bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/06-bump");
		bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Loading textures.");
		bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);

		float at[3]  = { 0.0f, 0.0f,  0.0f };
		float eye[3] = { 0.0f, 0.0f, -7.0f };

		// Set view and projection matrix for view 0.
		const bgfx::HMD* hmd = bgfx::getHMD();
		if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING))
		{
			float view[16];
			bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye);

			float proj[16];
			bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f);

			bgfx::setViewTransform(0, view, proj);

			// Set view 0 default viewport.
			//
			// Use HMD's width/height since HMD's internal frame buffer size
			// might be much larger than window size.
			bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
		}
		else
		{
			float view[16];
			bx::mtxLookAt(view, eye, at);

			float proj[16];
			bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);
			bgfx::setViewTransform(0, view, proj);

			// Set view 0 default viewport.
			bgfx::setViewRect(0, 0, 0, width, height);
		}

		float lightPosRadius[4][4];
		for (uint32_t ii = 0; ii < numLights; ++ii)
		{
			lightPosRadius[ii][0] = sinf( (time*(0.1f + ii*0.17f) + ii*bx::piHalf*1.37f ) )*3.0f;
			lightPosRadius[ii][1] = cosf( (time*(0.2f + ii*0.29f) + ii*bx::piHalf*1.49f ) )*3.0f;
			lightPosRadius[ii][2] = -2.5f;
			lightPosRadius[ii][3] = 3.0f;
		}

		bgfx::setUniform(u_lightPosRadius, lightPosRadius, numLights);

		float lightRgbInnerR[4][4] =
		{
			{ 1.0f, 0.7f, 0.2f, 0.8f },
			{ 0.7f, 0.2f, 1.0f, 0.8f },
			{ 0.2f, 1.0f, 0.7f, 0.8f },
			{ 1.0f, 0.4f, 0.2f, 0.8f },
		};

		bgfx::setUniform(u_lightRgbInnerR, lightRgbInnerR, numLights);

		const uint16_t instanceStride = 64;
		const uint16_t numInstances = 3;

		if (instancingSupported)
		{
			// Write instance data for 3x3 cubes.
			for (uint32_t yy = 0; yy < 3; ++yy)
			{
				const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(numInstances, instanceStride);
				if (NULL != idb)
				{
					uint8_t* data = idb->data;

					for (uint32_t xx = 0; xx < 3; ++xx)
					{
						float* mtx = (float*)data;
						bx::mtxRotateXY(mtx, time*0.023f + xx*0.21f, time*0.03f + yy*0.37f);
						mtx[12] = -3.0f + float(xx)*3.0f;
						mtx[13] = -3.0f + float(yy)*3.0f;
						mtx[14] = 0.0f;

						data += instanceStride;
					}

					// Set instance data buffer.
					bgfx::setInstanceDataBuffer(idb, numInstances);

					// Set vertex and fragment shaders.
					bgfx::setProgram(program);

					// Set vertex and index buffer.
					bgfx::setVertexBuffer(vbh);
					bgfx::setIndexBuffer(ibh);

					// Bind textures.
					bgfx::setTexture(0, u_texColor, textureColor);
					bgfx::setTexture(1, u_texNormal, textureNormal);

					// Set render states.
					bgfx::setState(0
						| BGFX_STATE_RGB_WRITE
						| BGFX_STATE_ALPHA_WRITE
						| BGFX_STATE_DEPTH_WRITE
						| BGFX_STATE_DEPTH_TEST_LESS
						| BGFX_STATE_MSAA
						);

					// Submit primitive for rendering to view 0.
					bgfx::submit(0);
				}
			}
		}
		else
		{
			for (uint32_t yy = 0; yy < 3; ++yy)
			{
				for (uint32_t xx = 0; xx < 3; ++xx)
				{
					float mtx[16];
					bx::mtxRotateXY(mtx, time*0.023f + xx*0.21f, time*0.03f + yy*0.37f);
					mtx[12] = -3.0f + float(xx)*3.0f;
					mtx[13] = -3.0f + float(yy)*3.0f;
					mtx[14] = 0.0f;

					// Set transform for draw call.
					bgfx::setTransform(mtx);

					// Set vertex and fragment shaders.
					bgfx::setProgram(program);

					// Set vertex and index buffer.
					bgfx::setVertexBuffer(vbh);
					bgfx::setIndexBuffer(ibh);

					// Bind textures.
					bgfx::setTexture(0, u_texColor, textureColor);
					bgfx::setTexture(1, u_texNormal, textureNormal);

					// Set render states.
					bgfx::setState(0
						| BGFX_STATE_RGB_WRITE
						| BGFX_STATE_ALPHA_WRITE
						| BGFX_STATE_DEPTH_WRITE
						| BGFX_STATE_DEPTH_TEST_LESS
						| BGFX_STATE_MSAA
						);

					// Submit primitive for rendering to view 0.
					bgfx::submit(0);
				}
			}
		}

		// Advance to next frame. Rendering thread will be kicked to
		// process submitted rendering primitives.
		bgfx::frame();
	}

	// Cleanup.
	bgfx::destroyIndexBuffer(ibh);
	bgfx::destroyVertexBuffer(vbh);
	bgfx::destroyProgram(program);
	bgfx::destroyTexture(textureColor);
	bgfx::destroyTexture(textureNormal);
	bgfx::destroyUniform(u_texColor);
	bgfx::destroyUniform(u_texNormal);
	bgfx::destroyUniform(u_lightPosRadius);
	bgfx::destroyUniform(u_lightRgbInnerR);

	// Shutdown bgfx.
	bgfx::shutdown();

	return 0;
}
コード例 #26
0
ファイル: reduce_on_gpu.hpp プロジェクト: BeauJoh/compute
inline void reduce_on_gpu(InputIterator first,
                          InputIterator last,
                          buffer_iterator<T> result,
                          Function function,
                          command_queue &queue)
{
    const device &device = queue.get_device();

    detail::meta_kernel k("reduce");
    k.add_arg<T*>("__global const","input");
    k.add_arg<const uint_>("offset");
    k.add_arg<const uint_>("count");
    k.add_arg<T*>("__global","output");
    k.add_arg<const uint_>("output_offset");

    k <<
        k.decl<const uint_>("block_offset") << " = get_group_id(0) * VPT * TPB;\n" <<
        "__global const " << type_name<T>() << " *block = input + offset + block_offset;\n" <<
        k.decl<const uint_>("lid") << " = get_local_id(0);\n" <<

        "__local " << type_name<T>() << " scratch[TPB];\n" <<
        // private reduction
        k.decl<T>("sum") << " = 0;\n" <<
        "for(uint i = 0; i < VPT; i++){\n" <<
        "    if(block_offset + lid + i*TPB < count){\n" <<
        "        sum = sum + block[lid+i*TPB]; \n" <<
        "    }\n" <<
        "}\n" <<

        "scratch[lid] = sum;\n";

    // discrimination on vendor name
    if(is_nvidia_device(device))
        k << ReduceBody<T,true>::body();
    else
        k << ReduceBody<T,false>::body();

    k <<
        // write sum to output
         "if(lid == 0){\n" <<
         "    output[output_offset + get_group_id(0)] = scratch[0];\n" <<
         "}\n";

    uint_ vpt = 8;
    uint_ tpb = 128;

    size_t count = std::distance(first, last);

    const context &context = queue.get_context();
    boost::shared_ptr<program_cache> cache = get_program_cache(context);
    std::string cache_key = std::string("boost_reduce_on_gpu_") + type_name<T>();
    program reduce_program = cache->get(cache_key);
    if(!reduce_program.get()){
        // create reduce program
        std::stringstream options;
        options << "-DT=" << type_name<T>()
                << " -DVPT=" << vpt
                << " -DTPB=" << tpb;
        reduce_program = program::build_with_source(k.source(), context, options.str());

        cache->insert(cache_key, reduce_program);
    }

    // create reduce kernel
    kernel reduce_kernel(reduce_program, "reduce");

    // first pass, reduce from input to ping
    buffer ping(context, std::ceil(float(count) / vpt / tpb) * sizeof(T));
    initial_reduce(first, last, ping, function, reduce_kernel, vpt, tpb, queue);

    // update count after initial reduce
    count = std::ceil(float(count) / vpt / tpb);

    // middle pass(es), reduce between ping and pong
    const buffer *input_buffer = &ping;
    buffer pong(context, count / vpt / tpb * sizeof(T));
    const buffer *output_buffer = &pong;
    if(count > vpt * tpb){
        while(count > vpt * tpb){
            reduce_kernel.set_arg(0, *input_buffer);
            reduce_kernel.set_arg(1, uint_(0));
            reduce_kernel.set_arg(2, uint_(count));
            reduce_kernel.set_arg(3, *output_buffer);
            reduce_kernel.set_arg(4, uint_(0));

            size_t work_size = std::ceil(float(count) / vpt);
            if(work_size % tpb != 0){
                work_size += tpb - work_size % tpb;
            }
            queue.enqueue_1d_range_kernel(reduce_kernel, 0, work_size, tpb);

            std::swap(input_buffer, output_buffer);
            count = std::ceil(float(count) / vpt / tpb);
        }
    }

    // final pass, reduce from ping/pong to result
    reduce_kernel.set_arg(0, *input_buffer);
    reduce_kernel.set_arg(1, uint_(0));
    reduce_kernel.set_arg(2, uint_(count));
    reduce_kernel.set_arg(3, result.get_buffer());
    reduce_kernel.set_arg(4, uint_(result.get_index()));

    queue.enqueue_1d_range_kernel(reduce_kernel, 0, tpb, tpb);
}
コード例 #27
0
void a_InitGL()
{
	glDisable(GL_LIGHT0);
	a_time=2.0;
	a_gets=0;a_timecyc=0;
	gendep=1.55;
	cameraray[0]=0;cameraray[1]=0;cameraray[2]=0;
	rray[0]=0;rray[1]=0;rray[2]=0;
	a_x=0;a_y=0;a_float_x=0;a_float_y=0;a_float_xb=0;a_float_yb=0;
	a_xrot=0;a_yrot=0;a_zrot=0;a_rad=0.0f;
	quantos=-1.0f;
	a_zeta=-1.0f;
	a_factor=10.0f;
	a_time=2.0f;
	a_waves=0;
	a_az=0;
	a_counter=0;
	a_mod=0;
	a_xa=0;a_ya=0;

	a_mod=0;
	a_xa=0;a_ya=0;
	a_diffuse[0]=0.2f;a_diffuse[1]=0.2f;a_diffuse[2]=0.2f;a_diffuse[3]=1.0f;
	a_ambient[0]=0.1f;a_ambient[1]=0.1f;a_ambient[2]=0.1f;a_ambient[3]=1.0f;
	a_specular[0]=.75f;a_specular[1]=.75f;a_specular[2]=.75f;a_specular[3]=1.0f;
	a_emission[0]=0.2f;a_emission[1]=0.2f;a_emission[2]=0.2f;a_emission[3]=1.0f;

	a_shininess = 10.0f;

	a_LightAmbient[0]=0.5f;a_LightAmbient[1]=0.5f;a_LightAmbient[2]=0.5f;a_LightAmbient[3]=1.0f;
	a_LightDiffuse[0]=0.5f;a_LightDiffuse[1]=0.5f;a_LightDiffuse[2]=0.5f;a_LightDiffuse[3]=1.0f;
	a_LightSpecular[0]=.5f;a_LightSpecular[1]=.5f;a_LightSpecular[2]=.5f;a_LightSpecular[3]=1.0f;
	a_LightPosition[0]=0.0f;a_LightPosition[1]=8.0f;a_LightPosition[2]=-20.0f;a_LightPosition[3]=1.0f;
	a_Sinus[0]=0;
	a_Sinus[1]=0;
	a_Sinus[2]=0;

	a_xrot=0;
	a_yrot=0;
	a_zrot=0;
	a_counter=0;

	a_rad=0.0f;
	quantos=-1.0f;
	a_zeta=-1.0f;
	a_factor=10.0f;

	a_waves=0;
	a_counter=0;
	coeff=7.1f;
	a_gets=0;
	switcher=false;
	gendep=1.55;

	camera[0]=-12.8;
	camera[1]=12.8;
	camera[2]=5;

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glShadeModel(GL_SMOOTH);
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
	glClearDepth(1.0f);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);


	a_Text=new Texture[numtexs];
	a_Text[1].Load("data/logoxs.raw");
	a_Text[2].Load("data/white.raw");
	a_Text[3].Load("data/sun2.raw");
	a_Text[4].Load("data/star.raw");

	glEnable (GL_LIGHTING);
	glEnable (GL_LIGHT1);

	glLightfv(GL_LIGHT1,GL_DIFFUSE,a_LightDiffuse);
	glLightfv(GL_LIGHT1,GL_AMBIENT,a_LightAmbient);
	glLightfv(GL_LIGHT1,GL_SPECULAR,a_LightSpecular);
	glLightfv(GL_LIGHT1,GL_POSITION,a_LightPosition);

	glMaterialfv(GL_FRONT,GL_DIFFUSE,a_diffuse);
	glMaterialfv(GL_FRONT,GL_AMBIENT,a_ambient);
	glMaterialfv(GL_FRONT,GL_SPECULAR,a_specular);
	glMaterialf(GL_FRONT,GL_SHININESS,10.0f);

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	glEnable(GL_TEXTURE_2D);
	for (a_x=0;a_x<size;a_x++)
	{
		for (a_y=0; a_y<size;a_y++)
		{
			a_points[a_x][a_y][0]=float(a_x/(1.25f*size/32));
			a_points[a_x][a_y][1]=float(a_y/(1.25f*size/32));
			a_points[a_x][a_y][2]=0.0;
		}
	}

	for (int p=0; p<a_num; p++)
	{
		parts[p].r=128+rand()%128;
		parts[p].g=128+rand()%128;
		parts[p].b=128+rand()%128;
		parts[p].a=-1;
		parts[p].angle=rand()%90;
		parts[p].a_mod=0.0f;
		parts[p].speedlim=.005+.0001*((GLfloat)(rand()%1000));
		parts[p].speed=parts[p].speedlim;
		parts[p].a_x=0.0f;
		parts[p].a_y=0.0f;
		parts[p].z=0.0f;
	}

	a_mod=1.0;
	glBlendFunc(GL_SRC_ALPHA,GL_ONE);
	glEnable(GL_BLEND);

	glDisable(GL_DEPTH_TEST);
	a_setpart();
}
コード例 #28
0
bool PFOperatorForceSpaceWarp::Proceed(IObject* pCont, 
									 PreciseTimeValue timeStart, 
									 PreciseTimeValue& timeEnd,
									 Object* pSystem,
									 INode* pNode,
									 INode* actionNode,
									 IPFIntegrator* integrator)
{
	// acquire all necessary channels, create additional if needed

	IChannelContainer* chCont;
	chCont = GetChannelContainerInterface(pCont);
	if (chCont == NULL) return false;

	IParticleChannelAmountR* chAmount = GetParticleChannelAmountRInterface(pCont);
	if(chAmount == NULL) return false;
	int iQuant = chAmount->Count();
	if (iQuant < 1) return true; // no particles to proceed

	IParticleChannelNewR* chNew = GetParticleChannelNewRInterface(pCont);
	if (chNew == NULL) return false; 

	IParticleChannelIDR* chID = GetParticleChannelIDRInterface(pCont);
	if (chID == NULL) return false;

	IParticleChannelPTVR* chTime = GetParticleChannelTimeRInterface(pCont);
	if(chTime == NULL) return false;

	IParticleChannelPTVR* chAge = GetParticleChannelBirthTimeRInterface(pCont);
	if(chAge == NULL) return false;

// the channel of interest speed
	bool initSpeed = false;
//channel does not exist so make it and note that we have to fill it out
	IParticleChannelPoint3W* chSpeedW = (IParticleChannelPoint3W*)chCont->EnsureInterface(PARTICLECHANNELSPEEDW_INTERFACE,
																			ParticleChannelPoint3_Class_ID,
																			true, PARTICLECHANNELSPEEDR_INTERFACE,
																			PARTICLECHANNELSPEEDW_INTERFACE, true,
																			actionNode, NULL, &initSpeed);
	IParticleChannelPoint3R* chSpeed = GetParticleChannelSpeedRInterface(pCont);
	if ((chSpeedW == NULL) || (chSpeed == NULL)) return false;

	bool initPosition = false;
	IParticleChannelPoint3W* chPosW = (IParticleChannelPoint3W*)chCont->EnsureInterface(PARTICLECHANNELPOSITIONW_INTERFACE,
																			ParticleChannelPoint3_Class_ID,
																			true, PARTICLECHANNELPOSITIONR_INTERFACE,
																			PARTICLECHANNELPOSITIONW_INTERFACE, true,
																			actionNode, NULL, &initPosition);
	IParticleChannelPoint3R* chPos = GetParticleChannelPositionRInterface(pCont);
	if ((chPosW == NULL) || (chPos == NULL)) return false;

	bool useScript = ((scriptPBlock()->GetInt(kForceSpaceWarp_useScriptWiring, 0) != 0)
						&& (scriptPBlock()->GetInt(kForceSpaceWarp_useFloat, 0) == kForceSpaceWarp_useFloat_influence));
	IParticleChannelFloatR* chFloat = NULL;
	if (useScript) {
		chFloat = GetParticleChannelMXSFloatRInterface(pCont);
		if (chFloat == NULL) return false;
	}

	int timeType = kAbsoluteTime;
	_pblock()->GetValue(kForceSpaceWarp_Sync,0, timeType, FOREVER);

	IParticleChannelPTVR* chEventStart = NULL;
	IParticleChannelPTVW* chEventStartW = NULL;
	bool initEventStart = false;
	if (timeType == kEventDuration)
	{
		chEventStartW = (IParticleChannelPTVW*) chCont->EnsureInterface(PARTICLECHANNELEVENTSTARTW_INTERFACE,
								  ParticleChannelPTV_Class_ID,
								  true, PARTICLECHANNELEVENTSTARTR_INTERFACE,
								  PARTICLECHANNELEVENTSTARTW_INTERFACE, false,
								  actionNode, NULL, &initEventStart);

		chEventStart = GetParticleChannelEventStartRInterface(pCont);
		if ((chEventStart == NULL) || (chEventStartW == NULL)) return false;
	}

	int overlapping = pblock()->GetInt(kForceSpaceWarp_Overlapping, 0);
	// collecting force fields
	Tab<ForceField*> ff;
	ForceField* curFF;
	int i, j;
	for(i=0; i<pblock()->Count(kForceSpaceWarp_ForceNodeList); i++) {
		INode* node = pblock()->GetINode(kForceSpaceWarp_ForceNodeList, 0, i);
		if (node == NULL) continue;
		Object* ob = GetPFObject(node->GetObjectRef());
		if (ob == NULL) continue;
		if (ob->SuperClassID() == WSM_OBJECT_CLASS_ID) {
			WSMObject* obref = (WSMObject*)ob;
			curFF = obref->GetForceField(node);
			if (curFF != NULL) {
				if (ob->ClassID() == CS_VFIELDOBJECT_CLASS_ID) {
					// CS VectorField SW doesn't init properly partobj on GetForceField
					// this is a quick fix for that (bayboro 3/6/2003)
					CS_VectorField* vf = (CS_VectorField*)curFF;
					vf->partobj = GetParticleInterface(pSystem);
				}
				ff.Append(1, &curFF);
			}
		}
	}
	if (ff.Count() == 0) return true; // no force fields

	// some calls for a reference node TM may initiate REFMSG_CHANGE notification
	// we have to ignore that while processing the particles
	bool wasIgnoring = IsIgnoringRefNodeChange();
	if (!wasIgnoring) SetIgnoreRefNodeChange();

	float influence = 0.0f;
	for(i = 0; i < iQuant; i++) 
	{
		TimeValue t = 0;
		if (timeType == kAbsoluteTime)
			t = chTime->GetValue(i).TimeValue();
		else if (timeType == kParticleAge)
			t = chTime->GetValue(i).TimeValue() - chAge->GetValue(i).TimeValue();
		else 
		{
			if (initEventStart && chNew->IsNew(i))
				chEventStartW->SetValue(i, chTime->GetValue(i));
			t = chTime->GetValue(i).TimeValue() - chEventStart->GetValue(i).TimeValue();
		}

		if (useScript) {
			influence = chFloat->GetValue(i);
		} else {
			influence = GetPFFloat(pblock(), kForceSpaceWarp_Influence, t);
		}

		Point3 v(0.0f,0.0f,0.0f);
		if (!initSpeed || !chNew->IsNew(i)) //if we created a speed channel the channel incoming is bogus so just use 0,0,0 ad default
			v = chSpeed->GetValue(i);

		Point3 p(0.0f,0.0f,0.0f);
		if (!initPosition || !chNew->IsNew(i)) //if we created a pos channel the channel incoming is bogus so just use 0,0,0 ad default
			p = chPos->GetValue(i);

		Point3 force = Point3::Origin;
		for(j=0; j<ff.Count(); j++) {
			// buffer vectors to guard true position and speed from malicious force
			Point3 pp = p;
			Point3 vv = v;
			Point3 nextForce = ff[j]->Force(t,pp,vv,chID->GetParticleBorn(i)) * influence;
			float lenSq = LengthSquared(nextForce);
			if (lenSq <= 0.0f) continue; // not a valid force
			if (overlapping == kForceSpaceWarp_Overlapping_additive) {
				force += nextForce;
			} else {
				if (lenSq > LengthSquared(force))
					force = nextForce;
			}
//			p = pp;
//			v = vv;
		}

		v += force * float(timeEnd - chTime->GetValue(i));
		chPosW->SetValue(i, p);
		chSpeedW->SetValue(i, v);
	}

	for(i=0; i<ff.Count(); i++)
		if (ff[i] != NULL) ff[i]->DeleteThis();

	if (!wasIgnoring) ClearIgnoreRefNodeChange();
	return true;
}
int main(int argc, char *argv[]){
    /**
     EXPLANATION:
     This function computes the average of the (projected) deltas as a function of redshift
     Note that this program should work with typical ini file developed to pass to correlation.run but that not all options are used here.
     This program should be run for each set of the paramenters z_min_interpolation, z_max_interpolation, num_points_interpolation, 
     or pixel_separation
          
     INPUTS:
     input_file[optional] - a file containing the input settings
     
     OUTPUTS:
     NONE
          
     CLASSES USED:
     AstroObjectDataset
     Input
     PlateNeighbours
     LyaSpectraDataset
     
     FUNCITONS USED:
     ComputePlateNeighbours
     */
    
    // load time control variables
    time_t start_time,end_time;
    time(&start_time);

    // load global variables and plot object
    std::cout << "Initializing variables" << std::endl;
    string input_filename = "";
    if (argc > 1){
        input_filename += argv[1];
    }
    Input input(input_filename);
    size_t flag_verbose_main = input.flag_verbose_main();
    const PlotsObject kPlots(input);

    // check whether or not this comuputation is necessary
    if (not input.flag_project_deltas()){
        std::cout << "Deltas are not projected, correction unnecessary" << std::endl;
        return 0;
    }
    
    // check whether or not the plate list needs to be computed
    if (input.flag_compute_plate_neighbours()){
        ComputePlateNeighbours(input);
    }
    // load plate list
    const PlateNeighbours kPlateNeighbours(input);
    
    // load spectra dataset
    std::auto_ptr<SpectraDataset> spectra_list;
    if (input.dataset2_type() == "lya"){
        spectra_list.reset(new LyaSpectraDataset(input));
    }
    else if (input.dataset2_type() == "civ"){
        spectra_list.reset(new CIVSpectraDataset(input));
    }
    else{
        std::cout << "Error : The selected type for dataset2 is not enabled. Current options are: " << input.dataset2_type_options() << std::endl;
        return 1;
    }
    if (input.flag_plot_catalog_info()){
        if (flag_verbose_main >= 2){
            std::cout << "Plotting spectra dataset information" << std::endl;
        }
        kPlots.PlotRADECDispersion(*spectra_list, true);
        kPlots.PlotZHistogram(*spectra_list, true);
        if (flag_verbose_main >= 2){
            std::cout << "done" << std::endl;
        }
    }
    
    // define vectors to store the average projected delta as a function of redshift
    size_t num_points_interpolation = input.num_points_interpolation();
    std::vector<double> z_mean_delta(num_points_interpolation, 0.0);
    double z_step = (input.z_max_interpolation() - input.z_min_interpolation())/float(z_mean_delta.size());
    for (size_t index = 0; index < z_mean_delta.size(); index++){
        z_mean_delta[index] = input.z_min_interpolation() + z_step*float(index);
    }
    std::vector<double> mean_delta(num_points_interpolation, 0.0);
    std::vector<double> total_weight(num_points_interpolation, 0.0);
    
    // define copies of mean_delta and total_weight for each of the threads
    int num_threads = atoi(std::getenv("OMP_NUM_THREADS"));
    std::vector<std::vector<double> > mean_delta_thread;
    mean_delta_thread.resize(num_threads, mean_delta);
    std::vector<std::vector<double> > total_weight_thread;
    total_weight_thread.resize(num_threads, total_weight);
    
    // load list of plates
    PlatesMapVector<LyaSpectrum>::map plates_list = (*spectra_list).list();
    
    // compute the average of projected deltas
    std::cout << "Computing the average of projected deltas" << std::endl;
    // loop over plates
    for (PlatesMapVector<LyaSpectrum>::map::iterator it = plates_list.begin(); it != plates_list.end(); it ++){
        
        std::vector<LyaSpectrum> spec_list = (*it).second;
        // loop over spectra
        #pragma omp parallel for schedule(dynamic)
        for (size_t spectrum_number = 0; spectrum_number < spec_list.size(); spectrum_number ++){
            // get the thread number
            int thread_num = omp_get_thread_num();
            double weight;
            
            std::vector<LyaPixel> spectrum = spec_list[spectrum_number].spectrum();
            // loop over pixel
            for (size_t pixel_number = 0; pixel_number < spectrum.size(); pixel_number++){
                // locate the bin in z the pixel belongs to
                int z_index = int((spectrum[pixel_number].z() - input.z_min_interpolation())/z_step);
                if ((z_index < 0) or (z_index > z_mean_delta.size())){
                    #pragma omp critical (cerr)
                    {
                        std::cerr << "Bad index, z_index = " << z_index << std::endl;
                    }
                }
                else{
                    weight = spectrum[pixel_number].weight();
                    mean_delta_thread[thread_num][z_index] += spectrum[pixel_number].delta()*weight;
                    total_weight_thread[thread_num][z_index] += weight;
                }
            }
        }
    }
    
    // combine the measurements from the different threads
    for (size_t index = 0; index < num_points_interpolation; index ++){
        for (size_t thread_num = 0; thread_num < mean_delta_thread.size(); thread_num ++){
            mean_delta[index] += mean_delta_thread[thread_num][index];
            total_weight[index] += total_weight_thread[thread_num][index];
        }
    }
    
    // normalize the correlation
    for (int index =  0; index < num_points_interpolation; index ++){
        // check that the weight is not zero
        if (total_weight[index] == 0.0){
            std::cerr << "Warning : In compute_projection_correction : Index " << index;
            std::cerr << " shows zero weight. Consider reducing num_points_interpolation." << std::endl;
        }
        else{
            mean_delta[index] /= total_weight[index];
        }
    }
    
    // save results
    std::string filename = input.lya_projection_correction();
    std::cout << "Saving results to " << filename << std::endl;
    std::ofstream file;
    file.open(filename.c_str(),std::ofstream::trunc); // opens the file erasing the previous contents
    if (file.is_open()){
        // print header
        file << "z mean_delta" << std::endl;
        // print results
        for (size_t index = 0; index < z_mean_delta.size(); index ++){
            file << z_mean_delta[index] << " " << mean_delta[index] <<  std::endl;
        }
        
        file.close();
    }
    else{
        std::cerr << "Error : In compute_projection_correction : Unable to open file:" << std::endl << filename << std::endl;
    }
    
    
    // display time required to run the program
    if (flag_verbose_main >= 1){
        std::cout << "End of program" << std::endl;
    }
    time(&end_time);
    double time_spent = difftime(end_time, start_time);
    if (flag_verbose_main >= 1){
        if (time_spent < 60.0){
            std::cout << "Program lasted " << time_spent << " seconds" << std::endl;
        }
        else if (time_spent < 3600.0){
            std::cout << "Program lasted " << time_spent/60.0 << " minutes" << std::endl;
        }
        else{
            std::cout << "Program lasted " << time_spent/3600.0 << " hours" << std::endl;
        }
    }
    return 0;
}
コード例 #30
0
ファイル: util.cpp プロジェクト: scottscaccianoce/LostRealms
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
float unifRand()
{
    return rand() / float(RAND_MAX);
}