Exemplo n.º 1
0
float Wind::fsin(float d) {
	float a = isin(d);
	float b = isin(d + 1);
	return a + (d - int(d)) * (b - a);
}
Exemplo n.º 2
0
// Call scotch with options from dictionary.
Foam::label Foam::ptscotchDecomp::decompose
(
    const fileName& meshPath,
    const label adjncySize,
    const label adjncy[],
    const label xadjSize,
    const label xadj[],
    const scalarField& cWeights,

    List<label>& finalDecomp
) const
{
    if (debug)
    {
        Pout<< "ptscotchDecomp : entering with xadj:" << xadjSize << endl;
    }

    // Dump graph
    if (decompositionDict_.found("scotchCoeffs"))
    {
        const dictionary& scotchCoeffs =
            decompositionDict_.subDict("scotchCoeffs");

        if (scotchCoeffs.lookupOrDefault("writeGraph", false))
        {
            OFstream str
            (
               meshPath + "_" + Foam::name(Pstream::myProcNo()) + ".dgr"
            );

            Pout<< "Dumping Scotch graph file to " << str.name() << endl
                << "Use this in combination with dgpart." << endl;

            globalIndex globalCells(xadjSize-1);

            // Distributed graph file (.grf)
            label version = 2;
            str << version << nl;
            // Number of files (procglbnbr)
            str << Pstream::nProcs();
            // My file number (procloc)
            str << ' ' << Pstream::myProcNo() << nl;

            // Total number of vertices (vertglbnbr)
            str << globalCells.size();
            // Total number of connections (edgeglbnbr)
            str << ' ' << returnReduce(xadj[xadjSize-1], sumOp<label>())
                << nl;
            // Local number of vertices (vertlocnbr)
            str << xadjSize-1;
            // Local number of connections (edgelocnbr)
            str << ' ' << xadj[xadjSize-1] << nl;
            // Numbering starts from 0
            label baseval = 0;
            // 100*hasVertlabels+10*hasEdgeWeights+1*hasVertWeighs
            str << baseval << ' ' << "000" << nl;
            for (label cellI = 0; cellI < xadjSize-1; cellI++)
            {
                label start = xadj[cellI];
                label end = xadj[cellI+1];
                str << end-start;

                for (label i = start; i < end; i++)
                {
                    str << ' ' << adjncy[i];
                }
                str << nl;
            }
        }
    }

    // Strategy
    // ~~~~~~~~

    // Default.
    SCOTCH_Strat stradat;
    check(SCOTCH_stratInit(&stradat), "SCOTCH_stratInit");

    if (decompositionDict_.found("scotchCoeffs"))
    {
        const dictionary& scotchCoeffs =
            decompositionDict_.subDict("scotchCoeffs");


        string strategy;
        if (scotchCoeffs.readIfPresent("strategy", strategy))
        {
            if (debug)
            {
                Info<< "ptscotchDecomp : Using strategy " << strategy << endl;
            }
            SCOTCH_stratDgraphMap(&stradat, strategy.c_str());
            //fprintf(stdout, "S\tStrat=");
            //SCOTCH_stratSave(&stradat, stdout);
            //fprintf(stdout, "\n");
        }
    }


    // Graph
    // ~~~~~

    List<label> velotab;


    // Check for externally provided cellweights and if so initialise weights

    scalar minWeights = gMin(cWeights);
    scalar maxWeights = gMax(cWeights);

    if (maxWeights > minWeights)
    {
        if (minWeights <= 0)
        {
            WarningIn
            (
                "ptscotchDecomp::decompose(..)"
            )   << "Illegal minimum weight " << minWeights
                << endl;
        }

        if (cWeights.size() != xadjSize-1)
        {
            FatalErrorIn
            (
                "ptscotchDecomp::decompose(..)"
            )   << "Number of cell weights " << cWeights.size()
                << " does not equal number of cells " << xadjSize-1
                << exit(FatalError);
        }
    }

    scalar velotabSum = gSum(cWeights)/minWeights;

    scalar rangeScale(1.0);

    if (Pstream::master())
    {
        if (velotabSum > scalar(labelMax - 1))
        {
            // 0.9 factor of safety to avoid floating point round-off in
            // rangeScale tipping the subsequent sum over the integer limit.
            rangeScale = 0.9*scalar(labelMax - 1)/velotabSum;

            WarningIn
            (
                "ptscotchDecomp::decompose(...)"
            )   << "Sum of weights has overflowed integer: " << velotabSum
                << ", compressing weight scale by a factor of " << rangeScale
                << endl;
        }
    }

    Pstream::scatter(rangeScale);

    if (maxWeights > minWeights)
    {
        if (cWeights.size())
        {
            // Convert to integers.
            velotab.setSize(cWeights.size());

            forAll(velotab, i)
            {
                velotab[i] = int((cWeights[i]/minWeights - 1)*rangeScale) + 1;
            }
        }
Exemplo n.º 3
0
void Settings::save() {
  QSettings cfg(QString("kstrc"));

  cfg.beginGroup("Kst");
  cfg.setValue("Plot Update Timer", qlonglong(plotUpdateTimer));
  cfg.setValue("Plot Font Size", qlonglong(plotFontSize));
  cfg.setValue("Plot Font Min Size", qlonglong(plotFontMinSize));
  cfg.setValue("Background Color", backgroundColor);
  cfg.setValue("Foreground Color", foregroundColor);
  cfg.setValue("Prompt on Window Close", promptWindowClose);
  cfg.setValue("Show QuickStart", showQuickStart);
  cfg.setValue("Tied-zoom Global", tiedZoomGlobal);
  cfg.setValue("Curve Color Sequence", curveColorSequencePalette);

  cfg.setValue("Timezone", timezone);
  cfg.setValue("OffsetSeconds", offsetSeconds);
  cfg.endGroup();

  cfg.beginGroup("Grid Lines");
  cfg.setValue("X Major", xMajor);
  cfg.setValue("Y Major", yMajor);
  cfg.setValue("X Minor", xMinor);
  cfg.setValue("Y Minor", yMinor);
  cfg.setValue("Major Color", majorColor);
  cfg.setValue("Minor Color", minorColor);
  cfg.setValue("Default Major Color", majorGridColorDefault);
  cfg.setValue("Default Minor Color", minorGridColorDefault);
  cfg.endGroup();

  cfg.beginGroup("X Axis");
  cfg.setValue("Interpret", xAxisInterpret);
  cfg.setValue("Interpretation", int(xAxisInterpretation));
  cfg.setValue("Display", int(xAxisDisplay));
  cfg.endGroup();

  cfg.beginGroup("Y Axis");
  cfg.setValue("Interpret", yAxisInterpret);
  cfg.setValue("Interpretation", int(yAxisInterpretation));
  cfg.setValue("Display", int(yAxisDisplay));
  cfg.endGroup();

  cfg.beginGroup("Curve");
  cfg.setValue("DefaultLineWeight", defaultLineWeight);
  cfg.endGroup();

  cfg.beginGroup("Printing");
  cfg.setValue("kde-pagesize", printing.pageSize);
  cfg.setValue("kde-orientation", printing.orientation);
  cfg.setValue("kst-plot-datetime-footer", printing.plotDateTimeFooter);
  cfg.setValue("kst-plot-maintain-aspect-ratio", printing.maintainAspect);
  cfg.setValue("kst-plot-curve-width-adjust", printing.curveWidthAdjust);
  cfg.setValue("kst-plot-monochrome", printing.monochrome);

  cfg.setValue("kst-plot-monochromesettings-enhancereadability",
                 printing.monochromeSettings.enhanceReadability);
  cfg.setValue("kst-plot-monochromesettings-pointstyleorder",
                 printing.monochromeSettings.pointStyleOrder);
  cfg.setValue("kst-plot-monochromesettings-linestyleorder",
                 printing.monochromeSettings.lineStyleOrder);
  cfg.setValue("kst-plot-monochromesettings-linewidthorder",
                 printing.monochromeSettings.lineWidthOrder);
  cfg.setValue("kst-plot-monochromesettings-maxlinewidth",
                 printing.monochromeSettings.maxLineWidth);
  cfg.setValue("kst-plot-monochromesettings-pointdensity",
                 printing.monochromeSettings.pointDensity);
  cfg.endGroup();

  cfg.sync();
}
Exemplo n.º 4
0
asmlinkage int solaris_brk(u32 brk)
{
	int (*sunos_brk)(u32) = (int (*)(u32))SUNOS(17);
	
	return sunos_brk(brk);
}
Exemplo n.º 5
0
 float  GetKey()  const { return mKeys[int(mIKey)];}
Exemplo n.º 6
0
int Character::levelForExp(int exp)
{
    return int(pow(float(exp) / EXPCURVE_FACTOR, 1.0f / EXPCURVE_EXPONENT));
}
Exemplo n.º 7
0
box2d<double> text_renderer<T>::prepare_glyphs(text_path *path)
{
    //clear glyphs
    glyphs_.clear();

    FT_Matrix matrix;
    FT_Vector pen;
    FT_Error  error;

    FT_BBox bbox;
    bbox.xMin = bbox.yMin = 32000;  // Initialize these so we can tell if we
    bbox.xMax = bbox.yMax = -32000; // properly grew the bbox later

    for (int i = 0; i < path->num_nodes(); i++)
    {
        char_info_ptr c;
        double x, y, angle;

        path->vertex(&c, &x, &y, &angle);

#ifdef MAPNIK_DEBUG
        // TODO Enable when we have support for setting verbosity
        //std::clog << "prepare_glyphs: " << c << "," << x <<
        //    "," << y << "," << angle << std::endl;
#endif

        FT_BBox glyph_bbox;
        FT_Glyph image;

        pen.x = int(x * 64);
        pen.y = int(y * 64);

        face_set_ptr faces = font_manager_.get_face_set(c->format->face_name, c->format->fontset);
        faces->set_character_sizes(c->format->text_size);

        glyph_ptr glyph = faces->get_glyph(unsigned(c->c));
        FT_Face face = glyph->get_face()->get_face();

        matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
        matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L );
        matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L );
        matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );

        FT_Set_Transform(face, &matrix, &pen);

        error = FT_Load_Glyph(face, glyph->get_index(), FT_LOAD_NO_HINTING);
        if ( error )
            continue;

        error = FT_Get_Glyph(face->glyph, &image);
        if ( error )
            continue;

        FT_Glyph_Get_CBox(image,ft_glyph_bbox_pixels, &glyph_bbox);
        if (glyph_bbox.xMin < bbox.xMin)
            bbox.xMin = glyph_bbox.xMin;
        if (glyph_bbox.yMin < bbox.yMin)
            bbox.yMin = glyph_bbox.yMin;
        if (glyph_bbox.xMax > bbox.xMax)
            bbox.xMax = glyph_bbox.xMax;
        if (glyph_bbox.yMax > bbox.yMax)
            bbox.yMax = glyph_bbox.yMax;

        // Check if we properly grew the bbox
        if ( bbox.xMin > bbox.xMax )
        {
            bbox.xMin = 0;
            bbox.yMin = 0;
            bbox.xMax = 0;
            bbox.yMax = 0;
        }

        // take ownership of the glyph
        glyphs_.push_back(new glyph_t(image, c->format));
    }

    return box2d<double>(bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax);
}
Exemplo n.º 8
0
BOOL CSkillReportDialog::OnInitDialog()
{
	CDialog::OnInitDialog();

	// TODO:  여기에 추가 초기화 작업을 추가합니다.

	// 리스트 컨트롤 초기화
	{
		const TCHAR* separator = _T( "................................................" );

		{
			const DWORD addStyle = LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT;
			CRect rect;

			{
				mReportListCtrl.GetWindowRect( rect );

				mReportListCtrl.InsertColumn( 0, _T( "" ),	LVCFMT_LEFT, int( rect.Width() * 0.4f ) );
				mReportListCtrl.InsertColumn( 1, _T( "" ),	LVCFMT_LEFT, int( rect.Width() * 0.13f ) );
				mReportListCtrl.InsertColumn( 2, _T( "" ),	LVCFMT_LEFT, int( rect.Width() * 0.17f ) );
				mReportListCtrl.InsertColumn( 3, _T( "" ),	LVCFMT_LEFT, int( rect.Width() * 0.3f ) );
				mReportListCtrl.SetExtendedStyle( mReportListCtrl.GetExtendedStyle() | addStyle );

				// 헤더
				{
					const DWORD row = mReportListCtrl.GetItemCount();

					CString textName;
					textName.LoadString( IDS_STRING20 );
					mReportListCtrl.InsertItem( row, textName, 0 );

					CString textLevel;
					textLevel.LoadString( IDS_STRING5 );
					mReportListCtrl.SetItemText( row, 1, textLevel );

					CString textSkillPoint;
					textSkillPoint.LoadString( IDS_STRING96 );
					mReportListCtrl.SetItemText( row, 2, textSkillPoint );

					CString textMoney;
					textMoney.LoadString( IDS_STRING199 );
					mReportListCtrl.SetItemText( row, 3, textMoney );
				}
				
				// 구분선
				{
					const DWORD row = mReportListCtrl.GetItemCount();

					mReportListCtrl.InsertItem( row, separator, 0 );
					mReportListCtrl.SetItemText( row, 1, separator );
					mReportListCtrl.SetItemText( row, 2, separator );
					mReportListCtrl.SetItemText( row, 3, separator );
				}
			}
		}

		const CSkillDialog* dialog = mApplication.GetSkillDialog();
		ASSERT( dialog );

		const CSkillDialog::SkillMap& skillMap = dialog->mSkillMap;

		
		DWORD usedMoney = 0;
		DWORD usedPoint = 0;

		for(
			CSkillDialog::SkillMap::const_iterator it = skillMap.begin();
			skillMap.end() != it;
			++it )
		{
			const SKILL_BASE& skill = it->second;

			for( int level = 1; level <= skill.Level; ++level )
			{
				const ActiveSkillScript* script = mApplication.GetActiveSkillScript( skill.wSkillIdx / 100 * 100 + level );

				if( ! script )
				{
					continue;
				}

				{
					const DWORD row = mReportListCtrl.GetItemCount();

					mReportListCtrl.InsertItem( row, script->mName, 0 );

					CString text;
					text.Format( _T( "%d" ), level );
					mReportListCtrl.SetItemText( row, 1, text );

					text.Format( _T( "%d" ), script->mPoint );
					mReportListCtrl.SetItemText( row, 2, text );

					text.Format( _T( "%d" ), script->mMoney );
					mReportListCtrl.SetItemText( row, 3, text );
				}

				{
					usedMoney += script->mMoney;
					usedPoint += script->mPoint;
				}
			}
		}

		if( skillMap.empty() )
		{
			const DWORD row = mReportListCtrl.GetItemCount();

			CString textEmpty;
			textEmpty.LoadString( IDS_STRING203 );

			mReportListCtrl.InsertItem( row, textEmpty, 0 );
		}

		// 구분선
		{
			const DWORD row = mReportListCtrl.GetItemCount();

			mReportListCtrl.InsertItem( row, separator, 0 );
			mReportListCtrl.SetItemText( row, 1, separator );
			mReportListCtrl.SetItemText( row, 2, separator );
			mReportListCtrl.SetItemText( row, 3, separator );
		}

		// 결과
		{
			const DWORD row = mReportListCtrl.GetItemCount();

			CString textSum;
			textSum.LoadString( IDS_STRING204 );

			mReportListCtrl.InsertItem( row, textSum, 0 );

			CString text;
			text.Format( _T( "%d" ), usedPoint );
			mReportListCtrl.SetItemText( row, 2, text );

			text.Format( _T( "%d" ), usedMoney );
			mReportListCtrl.SetItemText( row, 3, text );
		}
	}
	
	return TRUE;  // return TRUE unless you set the focus to a control
	// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}
Exemplo n.º 9
0
bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_value) {

	if (p_name=="filter_count") {
		filters.resize(p_value);
		_change_notify();
		ports_changed_notify();
		return true;
	}


	if (String(p_name).begins_with("filter_")) {

		int idx = String(p_name).replace_first("filters_","").get_slice("/",0).to_int();

		ERR_FAIL_INDEX_V(idx,filters.size(),false);

		String what = String(p_name).get_slice("/",1);


		if (what=="type") {
			filters[idx]=InputEvent();
			filters[idx].type=InputEvent::Type(int(p_value));
			if (filters[idx].type==InputEvent::JOYSTICK_MOTION) {
				filters[idx].joy_motion.axis_value=0.5; //for treshold
			} else if (filters[idx].type==InputEvent::KEY) {
				filters[idx].key.pressed=true; //put these as true to make it more user friendly
			} else if (filters[idx].type==InputEvent::MOUSE_BUTTON) {
				filters[idx].mouse_button.pressed=true;
			} else if (filters[idx].type==InputEvent::JOYSTICK_BUTTON) {
				filters[idx].joy_button.pressed=true;
			} else if (filters[idx].type==InputEvent::SCREEN_TOUCH) {
				filters[idx].screen_touch.pressed=true;
			} else if (filters[idx].type==InputEvent::ACTION) {
				filters[idx].action.pressed=true;
			}
			_change_notify();
			ports_changed_notify();

			return true;
		}
		if (what=="device") {
			filters[idx].device=p_value;
			ports_changed_notify();
			return true;
		}

		switch(filters[idx].type) {

			case InputEvent::KEY: {

				if (what=="scancode") {
					String sc = p_value;
					if (sc==String()) {
						filters[idx].key.scancode=0;
					} else {
						filters[idx].key.scancode=find_keycode(p_value);
					}

				} else if (what=="unicode") {

					String uc = p_value;

					if (uc==String()) {
						filters[idx].key.unicode=0;
					} else {
						filters[idx].key.unicode=uc[0];
					}

				} else if (what=="pressed") {

					filters[idx].key.pressed=p_value;
				} else if (what=="echo") {

					filters[idx].key.echo=p_value;

				} else if (what=="mod_alt") {
					filters[idx].key.mod.alt=p_value;

				} else if (what=="mod_shift") {
					filters[idx].key.mod.shift=p_value;

				} else if (what=="mod_ctrl") {
					filters[idx].key.mod.control=p_value;

				} else  if (what=="mod_meta") {
					filters[idx].key.mod.meta=p_value;
				} else {
					return false;
				}
				ports_changed_notify();

				return true;
			} break;
			case InputEvent::MOUSE_MOTION: {


				if (what=="button_mask") {
					filters[idx].mouse_motion.button_mask=p_value;

				} else if (what=="mod_alt") {
					filters[idx].mouse_motion.mod.alt=p_value;

				} else if (what=="mod_shift") {
					filters[idx].mouse_motion.mod.shift=p_value;

				} else if (what=="mod_ctrl") {
					filters[idx].mouse_motion.mod.control=p_value;

				} else  if (what=="mod_meta") {
					filters[idx].mouse_motion.mod.meta=p_value;
				} else {
					return false;
				}

				ports_changed_notify();
				return true;

			} break;
			case InputEvent::MOUSE_BUTTON: {

				if (what=="button_index") {
					filters[idx].mouse_button.button_index=p_value;
				} else if (what=="pressed") {
					filters[idx].mouse_button.pressed=p_value;
				} else if (what=="doubleclicked") {
					filters[idx].mouse_button.doubleclick=p_value;

				} else if (what=="mod_alt") {
					filters[idx].mouse_button.mod.alt=p_value;

				} else if (what=="mod_shift") {
					filters[idx].mouse_button.mod.shift=p_value;

				} else if (what=="mod_ctrl") {
					filters[idx].mouse_button.mod.control=p_value;

				} else  if (what=="mod_meta") {
					filters[idx].mouse_button.mod.meta=p_value;
				} else {
					return false;
				}
				ports_changed_notify();
				return true;

			} break;
			case InputEvent::JOYSTICK_MOTION: {

				if (what=="axis") {
					filters[idx].joy_motion.axis=int(p_value)<<1|filters[idx].joy_motion.axis;
				} else if (what=="mode") {
					filters[idx].joy_motion.axis|=int(p_value);
				} else if (what=="treshold") {
					filters[idx].joy_motion.axis_value=p_value;
				} else {
					return false;
				}
				ports_changed_notify();
				return true;


			} break;
			case InputEvent::JOYSTICK_BUTTON: {

				if (what=="button_index") {
					filters[idx].joy_button.button_index=p_value;
				} else if (what=="pressed") {
					filters[idx].joy_button.pressed=p_value;
				} else {
					return false;
				}
				ports_changed_notify();
				return true;

			} break;
			case InputEvent::SCREEN_TOUCH: {

				if (what=="finger_index") {
					filters[idx].screen_touch.index=p_value;
				} else if (what=="pressed") {
					filters[idx].screen_touch.pressed=p_value;
				} else {
					return false;
				}
				ports_changed_notify();
				return true;
			} break;
			case InputEvent::SCREEN_DRAG: {
				if (what=="finger_index") {
					filters[idx].screen_drag.index=p_value;
				} else {
					return false;
				}
				ports_changed_notify();
				return true;
			} break;
			case InputEvent::ACTION: {


				if (what=="action_name") {

					List<PropertyInfo> pinfo;
					Globals::get_singleton()->get_property_list(&pinfo);
					int index=1;

					for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
						const PropertyInfo &pi=E->get();

						if (!pi.name.begins_with("input/"))
							continue;

						String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
						if (name==String(p_value)) {

							filters[idx].action.action=index;
							ports_changed_notify();
							return true;
						}

						index++;
					}

					filters[idx].action.action=0;
					ports_changed_notify();

					return false;

				} else if (what=="pressed") {

					filters[idx].action.pressed=p_value;
					ports_changed_notify();
					return true;
				}


			} break;

		}
	}
	return false;
}
Exemplo n.º 10
0
WPoint ImageUtils::getSize(const std::vector<unsigned char>& header)
{
  /*
   * Contributed by Daniel Derr @ ArrowHead Electronics Health-Care
   */
  std::string mimeType = identifyMimeType(header);

  if (mimeType == "image/png") {
    int width = ( ( ( int(header[16]) << 8
		      | int(header[17])) << 8
		    | int(header[18])) << 8
		  | int(header[19]));
    int height = ( ( ( int(header[20]) << 8
		       | int(header[21])) << 8
		     | int(header[22])) << 8
		   | int(header[23]));
    return WPoint(width, height);
  } else if (mimeType == "image/gif") {
    int width = int(header[7]) << 8 | int(header[6]);
    int height = int(header[9]) << 8 | int(header[8]);
    return WPoint(width, height);
  } else
    return WPoint();
}
Exemplo n.º 11
0
void ComponentManager<T>::createComponent(id entity)
{
    assert(entitiesComponentsIndex.size() > entity && "ComponentManager: entity out of range");
    entitiesComponentsIndex[entity] = int(components.size());
    components.push_back(T());
}
Exemplo n.º 12
0
static void write_opengl_info(std::ostream &out)
{
	out << "OpenGL version " << glGetString(GL_VERSION);
	out << ", running on " << glGetString(GL_VENDOR);
	out << " " << glGetString(GL_RENDERER) << "\n";

	out << "GLEW version " << glewGetString(GLEW_VERSION) << "\n";

	out << "Available extensions:" << "\n";
	if (glewIsSupported("GL_VERSION_3_0")) {
		out << "Shading language version: " <<  glGetString(GL_SHADING_LANGUAGE_VERSION) << "\n";
		GLint numext = 0;
		glGetIntegerv(GL_NUM_EXTENSIONS, &numext);
		for (int i = 0; i < numext; ++i) {
			out << "  " << glGetStringi(GL_EXTENSIONS, i) << "\n";
		}
	}
	else {
		out << "  ";
		std::istringstream ext(reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)));
		std::copy(
			std::istream_iterator<std::string>(ext),
			std::istream_iterator<std::string>(),
			std::ostream_iterator<std::string>(out, "\n  "));
	}

	out << "\nImplementation Limits:\n";

	// first, clear all OpenGL error flags
	dump_and_clear_opengl_errors(out);

#define DUMP_GL_VALUE(name) dump_opengl_value(out, #name, name, 1)
#define DUMP_GL_VALUE2(name) dump_opengl_value(out, #name, name, 2)

	DUMP_GL_VALUE(GL_MAX_COLOR_ATTACHMENTS_EXT);
	DUMP_GL_VALUE(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
	DUMP_GL_VALUE(GL_MAX_CUBE_MAP_TEXTURE_SIZE);
	DUMP_GL_VALUE(GL_MAX_DRAW_BUFFERS);
	DUMP_GL_VALUE(GL_MAX_ELEMENTS_INDICES);
	DUMP_GL_VALUE(GL_MAX_ELEMENTS_VERTICES);
	DUMP_GL_VALUE(GL_MAX_EVAL_ORDER);
	DUMP_GL_VALUE(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS);
	DUMP_GL_VALUE(GL_MAX_RENDERBUFFER_SIZE_EXT);
	DUMP_GL_VALUE(GL_MAX_SAMPLES_EXT);
	DUMP_GL_VALUE(GL_MAX_TEXTURE_IMAGE_UNITS);
	DUMP_GL_VALUE(GL_MAX_TEXTURE_LOD_BIAS);
	DUMP_GL_VALUE(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT);
	DUMP_GL_VALUE(GL_MAX_TEXTURE_SIZE);
	DUMP_GL_VALUE(GL_MAX_VERTEX_ATTRIBS);
	DUMP_GL_VALUE(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
	DUMP_GL_VALUE(GL_MAX_VERTEX_UNIFORM_COMPONENTS);
	DUMP_GL_VALUE(GL_NUM_COMPRESSED_TEXTURE_FORMATS);
	DUMP_GL_VALUE(GL_SAMPLE_BUFFERS);
	DUMP_GL_VALUE(GL_SAMPLES);
	DUMP_GL_VALUE2(GL_ALIASED_LINE_WIDTH_RANGE);
	DUMP_GL_VALUE2(GL_MAX_VIEWPORT_DIMS);
	DUMP_GL_VALUE2(GL_SMOOTH_LINE_WIDTH_RANGE);
	DUMP_GL_VALUE2(GL_SMOOTH_POINT_SIZE_RANGE);

#undef DUMP_GL_VALUE
#undef DUMP_GL_VALUE2

	// enumerate compressed texture formats
	{
		dump_and_clear_opengl_errors(out);
		out << "\nCompressed texture formats:\n";

		GLint nformats;
		GLint formats[128]; // XXX 128 should be enough, right?

		glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &nformats);
		GLenum err = glGetError();
		if (err != GL_NO_ERROR) {
			out << "Get NUM_COMPRESSED_TEXTURE_FORMATS failed\n";
			dump_and_clear_opengl_errors(out, err);
		} else {
			assert(nformats >= 0 && nformats < int(COUNTOF(formats)));
			glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats);
			err = glGetError();
			if (err != GL_NO_ERROR) {
				out << "Get COMPRESSED_TEXTURE_FORMATS failed\n";
				dump_and_clear_opengl_errors(out, err);
			} else {
				for (int i = 0; i < nformats; ++i) {
					out << stringf("  %0{x#}\n", unsigned(formats[i]));
				}
			}
		}
	}
	// one last time
	dump_and_clear_opengl_errors(out);
}
Exemplo n.º 13
0
extern "C" magma_int_t
magma_smslice(
    magma_int_t num_slices,
    magma_int_t slice,
    magma_s_matrix A, 
    magma_s_matrix *B,
    magma_s_matrix *ALOC,
    magma_s_matrix *ANLOC,
    magma_index_t *comm_i,
    float *comm_v,
    magma_int_t *start,
    magma_int_t *end,
    magma_queue_t queue )
{
    magma_int_t info = 0;
    
    if( A.num_rows != A.num_cols ){
        printf("%%  error: only supported for square matrices.\n");
        info = MAGMA_ERR_NOT_SUPPORTED;
        goto cleanup;
    }
    
    if ( A.memory_location == Magma_CPU
            && A.storage_type == Magma_CSR ){
        CHECK( magma_smconvert( A, B, Magma_CSR, Magma_CSR, queue ) );
        magma_free_cpu( B->col );
        magma_free_cpu( B->val );
        CHECK( magma_smconvert( A, ALOC, Magma_CSR, Magma_CSR, queue ) );
        magma_free_cpu( ALOC->col );
        magma_free_cpu( ALOC->row );
        magma_free_cpu( ALOC->val );
        CHECK( magma_smconvert( A, ANLOC, Magma_CSR, Magma_CSR, queue ) );
        magma_free_cpu( ANLOC->col );
        magma_free_cpu( ANLOC->row );
        magma_free_cpu( ANLOC->val );
        
        magma_int_t i,j,k, nnz, nnz_loc=0, loc_row = 0, nnz_nloc = 0;
        magma_index_t col;
        magma_int_t size = magma_ceildiv( A.num_rows, num_slices ); 
        magma_int_t lstart = slice*size;
        magma_int_t lend = min( (slice+1)*size, A.num_rows );
        // correct size for last slice
        size = lend-lstart;
        CHECK( magma_index_malloc_cpu( &ALOC->row, size+1 ) );
        CHECK( magma_index_malloc_cpu( &ANLOC->row, size+1 ) );
        
        // count elements for slice - identity for rest
        nnz = A.row[ lend ] - A.row[ lstart ] + ( A.num_rows - size );
        CHECK( magma_index_malloc_cpu( &B->col, nnz ) );
        CHECK( magma_smalloc_cpu( &B->val, nnz ) );         
        
        // for the communication plan
        for( i=0; i<A.num_rows; i++ ) {
            comm_i[i] = 0;
            comm_v[i] = MAGMA_S_ZERO;
        }
        
        k=0;
        B->row[i] = 0;
        ALOC->row[0] = 0;
        ANLOC->row[0] = 0;
        // identity above slice
        for( i=0; i<lstart; i++ ) {
            B->row[i+1]   = B->row[i]+1;
            B->val[k] = MAGMA_S_ONE;
            B->col[k] = i;
            k++;
        }
        
        // slice        
        for( i=lstart; i<lend; i++ ) {
            B->row[i+1]   = B->row[i] + (A.row[i+1]-A.row[i]);
            for( j=A.row[i]; j<A.row[i+1]; j++ ){
                B->val[k] = A.val[j];
                col = A.col[j];
                B->col[k] = col;
                // communication plan
                if( col<lstart || col>=lend ){
                    comm_i[ col ] = 1;
                    comm_v[ col ] = comm_v[ col ] 
                            + MAGMA_S_MAKE( MAGMA_S_ABS( A.val[j] ), 0.0 );
                    nnz_nloc++;
                } else {
                    nnz_loc++;   
                }
                k++;
            }
            loc_row++;
            ALOC->row[ loc_row ] = nnz_loc;
            ANLOC->row[ loc_row ] = nnz_nloc;
        }
        CHECK( magma_index_malloc_cpu( &ALOC->col, nnz_loc ) );
        CHECK( magma_smalloc_cpu( &ALOC->val, nnz_loc ) ); 
        ALOC->num_rows = size;
        ALOC->num_cols = size;
        ALOC->nnz = nnz_loc;
        
        CHECK( magma_index_malloc_cpu( &ANLOC->col, nnz_nloc ) );
        CHECK( magma_smalloc_cpu( &ANLOC->val, nnz_nloc ) ); 
        ANLOC->num_rows = size;
        ANLOC->num_cols = A.num_cols;
        ANLOC->nnz = nnz_nloc;
        
        nnz_loc = 0;
        nnz_nloc = 0;
        // local/nonlocal matrix        
        for( i=lstart; i<lend; i++ ) {
            for( j=A.row[i]; j<A.row[i+1]; j++ ){
                col = A.col[j];
                // insert only in local part in ALOC, nonlocal in ANLOC
                if( col<lstart || col>=lend ){
                    ANLOC->val[ nnz_nloc ] = A.val[j];
                    ANLOC->col[ nnz_nloc ] = col;  
                    nnz_nloc++;
                } else {
                    ALOC->val[ nnz_loc ] = A.val[j];
                    ALOC->col[ nnz_loc ] = col-lstart;  
                    nnz_loc++;
                }
            }
        }
        
        // identity below slice
        for( i=lend; i<A.num_rows; i++ ) {
            B->row[i+1] = B->row[i]+1;
            B->val[k] = MAGMA_S_ONE;
            B->col[k] = i;
            k++;
        }
        B->nnz = k;
        *start = lstart;
        *end = lend;
        
    }
    else {
        printf("error: mslice only supported for CSR matrices on the CPU: %d %d.\n", 
                int(A.memory_location), int(A.storage_type) );
        info = MAGMA_ERR_NOT_SUPPORTED;
    }
cleanup:
    return info;
}
Exemplo n.º 14
0
bool player::create(game *g, character_type type, std::string tempname)
{
 weapon = item(g->itypes["null"], 0);

 g->u.prof = profession::generic();

 WINDOW* w = newwin(FULL_SCREEN_HEIGHT, FULL_SCREEN_WIDTH,
                    (TERMY > FULL_SCREEN_HEIGHT) ? (TERMY-FULL_SCREEN_HEIGHT)/2 : 0,
                    (TERMX > FULL_SCREEN_WIDTH) ? (TERMX-FULL_SCREEN_WIDTH)/2 : 0);

 int tab = 0, points = 38, max_trait_points = 12;
 if (type != PLTYPE_CUSTOM) {
  switch (type) {
   case PLTYPE_NOW:
    g->u.male = (rng(1,100)>50);
    g->u.pick_name();
   case PLTYPE_RANDOM:
   {
    str_max = rng(6, 12);
    dex_max = rng(6, 12);
    int_max = rng(6, 12);
    per_max = rng(6, 12);
    points = points - str_max - dex_max - int_max - per_max;
    if (str_max > HIGH_STAT)
     points -= (str_max - HIGH_STAT);
    if (dex_max > HIGH_STAT)
     points -= (dex_max - HIGH_STAT);
    if (int_max > HIGH_STAT)
     points -= (int_max - HIGH_STAT);
    if (per_max > HIGH_STAT)
     points -= (per_max - HIGH_STAT);

    int num_gtraits = 0, num_btraits = 0, rn, tries;
    while (points < 0 || rng(-3, 20) > points) {
     if (num_btraits < max_trait_points && one_in(3)) {
      tries = 0;
      do {
       rn = random_bad_trait();
       tries++;
      } while ((has_trait(rn) ||
              num_btraits - traits[rn].points > max_trait_points) && tries < 5);
      if (tries < 5) {
       toggle_trait(rn);
       points -= traits[rn].points;
       num_btraits -= traits[rn].points;
      }
     } else {
      switch (rng(1, 4)) {
       case 1: if (str_max > 5) { str_max--; points++; } break;
       case 2: if (dex_max > 5) { dex_max--; points++; } break;
       case 3: if (int_max > 5) { int_max--; points++; } break;
       case 4: if (per_max > 5) { per_max--; points++; } break;
      }
     }
    }
    while (points > 0) {
     switch (rng((num_gtraits < max_trait_points ? 1 : 5), 9)) {
     case 1:
     case 2:
     case 3:
     case 4:
      rn = random_good_trait();
      if (!has_trait(rn) && points >= traits[rn].points &&
          num_gtraits + traits[rn].points <= max_trait_points) {
       toggle_trait(rn);
       points -= traits[rn].points;
       num_gtraits += traits[rn].points;
      }
      break;
     case 5:
      switch (rng(1, 4)) {
       case 1: if (str_max < HIGH_STAT) { str_max++; points--; } break;
       case 2: if (dex_max < HIGH_STAT) { dex_max++; points--; } break;
       case 3: if (int_max < HIGH_STAT) { int_max++; points--; } break;
       case 4: if (per_max < HIGH_STAT) { per_max++; points--; } break;
      }
      break;
     case 6:
     case 7:
     case 8:
     case 9:
      rn = random_skill();

      Skill *aSkill = Skill::skill(rn);
      int level = skillLevel(aSkill);

      if (level < points) {
        points -= level + 1;
        skillLevel(aSkill).level(level + 2);
      }
      break;
     }
    }
   } break;
   case PLTYPE_TEMPLATE: {
    std::ifstream fin;
    std::stringstream filename;
    filename << "data/" << tempname << ".template";
    fin.open(filename.str().c_str());
    if (!fin.is_open()) {
     debugmsg("Couldn't open %s!", filename.str().c_str());
     return false;
    }
    std::string(data);
    getline(fin, data);
    load_info(g, data);
    points = 0;
   } break;
  }
  tab = NEWCHAR_TAB_MAX;
 } else
  points = OPTIONS[OPT_INITIAL_POINTS];
  max_trait_points = OPTIONS[OPT_MAX_TRAIT_POINTS];

 do {
  werase(w);
  wrefresh(w);
  switch (tab) {
   case 0: tab += set_stats      (w, g, this, type, points); break;
   case 1: tab += set_traits     (w, g, this, type, points, max_trait_points); break;
   case 2: tab += set_profession (w, g, this, type, points); break;
   case 3: tab += set_skills     (w, g, this, type, points); break;
   case 4: tab += set_description(w, g, this, type, points); break;
  }
 } while (tab >= 0 && tab <= NEWCHAR_TAB_MAX);
 delwin(w);

 if (tab < 0)
  return false;

 // Character is finalized.  Now just set up HP, &c
 for (int i = 0; i < num_hp_parts; i++) {
  hp_max[i] = calc_HP(str_max, has_trait(PF_TOUGH));
  hp_cur[i] = hp_max[i];
 }
 if (has_trait(PF_HARDCORE)) {
  for (int i = 0; i < num_hp_parts; i++) {
   hp_max[i] = int(hp_max[i] * .25);
   hp_cur[i] = hp_max[i];
  }
 } if (has_trait(PF_GLASSJAW)) {
  hp_max[hp_head] = int(hp_max[hp_head] * .80);
  hp_cur[hp_head] = hp_max[hp_head];
 }
 if (has_trait(PF_SMELLY))
  scent = 800;
 if (has_trait(PF_ANDROID)) {
  bionic_id first_bio;
  do {
   first_bio = g->random_good_bionic();
  } while (bionics[first_bio]->power_cost > 10);
  add_bionic(first_bio);
  add_bionic(bionic_id(power_source_bionics[rng(0,power_source_bionics.size()-1)]));	// Power Source
  max_power_level = 10;
  power_level = 10;
 }

 if (has_trait(PF_MARTIAL_ARTS)) {
  itype_id ma_type;
  do {
   int choice = (PLTYPE_NOW==type)? rng(1, 5) : menu(false, _("Pick your style:"),
                     _("Karate"), _("Judo"), _("Aikido"), _("Tai Chi"),
                     _("Taekwondo"), NULL);
   if (choice == 1)
    ma_type = "style_karate";
   if (choice == 2)
    ma_type = "style_judo";
   if (choice == 3)
    ma_type = "style_aikido";
   if (choice == 4)
    ma_type = "style_tai_chi";
   if (choice == 5)
    ma_type = "style_taekwondo";
   item tmpitem = item(g->itypes[ma_type], 0);
   if(PLTYPE_NOW!=type) {
       full_screen_popup(tmpitem.info(true).c_str());
   }
  } while (PLTYPE_NOW!=type && !query_yn(_("Use this style?")));
  styles.push_back(ma_type);
  style_selected=ma_type;
 }

    if (has_trait(PF_MARTIAL_ARTS2)) {
  itype_id ma_type;
  do {
   int choice = (PLTYPE_NOW==type)? rng(1, 5) : menu(false, _("Pick your style:"),
                     _("Capoeira"), _("Krav Maga"), _("Muay Thai"),
                     _("Ninjutsu"), _("Zui Quan"), NULL);
   if (choice == 1)
    ma_type = "style_capoeira";
   if (choice == 2)
    ma_type = "style_krav_maga";
   if (choice == 3)
    ma_type = "style_muay_thai";
   if (choice == 4)
    ma_type = "style_ninjutsu";
   if (choice == 5)
    ma_type = "style_zui_quan";
   item tmpitem = item(g->itypes[ma_type], 0);
   if(PLTYPE_NOW!=type) {
     full_screen_popup(tmpitem.info(true).c_str());
   }
  } while (PLTYPE_NOW!=type && !query_yn(_("Use this style?")));
  styles.push_back(ma_type);
  style_selected=ma_type;
 }
 if (has_trait(PF_MARTIAL_ARTS3)) {
  itype_id ma_type;
  do {
   int choice = (PLTYPE_NOW==type)? rng(1, 5) : menu(false, _("Pick your style:"),
                     _("Tiger"), _("Crane"), _("Leopard"), _("Snake"),
                     _("Dragon"), NULL);
   if (choice == 1)
    ma_type = "style_tiger";
   if (choice == 2)
    ma_type = "style_crane";
   if (choice == 3)
    ma_type = "style_leopard";
   if (choice == 4)
    ma_type = "style_snake";
   if (choice == 5)
    ma_type = "style_dragon";
   item tmpitem = item(g->itypes[ma_type], 0);
   if(PLTYPE_NOW!=type) {
     full_screen_popup(tmpitem.info(true).c_str());
   }
  } while (PLTYPE_NOW!=type && !query_yn(_("Use this style?")));
  styles.push_back(ma_type);
  style_selected=ma_type;
 }
 if (has_trait(PF_MARTIAL_ARTS4)) {
  itype_id ma_type;
  do {
   int choice = (PLTYPE_NOW==type)? rng(1, 5) : menu(false, _("Pick your style:"),
                     _("Centipede"), _("Viper"), _("Scorpion"), _("Lizard"),
                     _("Toad"), NULL);
   if (choice == 1)
    ma_type = "style_centipede";
   if (choice == 2)
    ma_type = "style_venom_snake";
   if (choice == 3)
    ma_type = "style_scorpion";
   if (choice == 4)
    ma_type = "style_lizard";
   if (choice == 5)
    ma_type = "style_toad";
   item tmpitem = item(g->itypes[ma_type], 0);
   if(PLTYPE_NOW!=type) {
     full_screen_popup(tmpitem.info(true).c_str());
   }
  } while (PLTYPE_NOW!=type && !query_yn(_("Use this style?")));
  styles.push_back(ma_type);
  style_selected=ma_type;
 }
 ret_null = item(g->itypes["null"], 0);
 weapon = get_combat_style();


 item tmp; //gets used several times

 std::vector<std::string> prof_items = g->u.prof->items();
 for (std::vector<std::string>::const_iterator iter = prof_items.begin(); iter != prof_items.end(); ++iter)
 {
    tmp = item(item_controller->find_template(*iter), 0);
    inv.push_back(tmp);
 }

 std::vector<addiction> prof_addictions = g->u.prof->addictions();
 for (std::vector<addiction>::const_iterator iter = prof_addictions.begin(); iter != prof_addictions.end(); ++iter)
 {
     g->u.addictions.push_back(*iter);
 }

 // Grab the skills from the profession, if there are any
 profession::StartingSkillList prof_skills = g->u.prof->skills();
 for (profession::StartingSkillList::const_iterator iter = prof_skills.begin();
      iter != prof_skills.end(); ++iter)
 {
     assert(Skill::skill(iter->first));
     if (Skill::skill(iter->first))
     {
        g->u.boost_skill_level(iter->first, iter->second);
     }
 }

 // Those who are both near-sighted and far-sighted start with bifocal glasses.
 if (has_trait(PF_HYPEROPIC) && has_trait(PF_MYOPIC))
 {
    tmp = item(g->itypes["glasses_bifocal"], 0);
    inv.push_back(tmp);
 }
 // The near-sighted start with eyeglasses.
 else if (has_trait(PF_MYOPIC))
 {
    tmp = item(g->itypes["glasses_eye"], 0);
    inv.push_back(tmp);
 }
 // The far-sighted start with reading glasses.
 else if (has_trait(PF_HYPEROPIC))
 {
    tmp = item(g->itypes["glasses_reading"], 0);
    inv.push_back(tmp);
 }

// Likewise, the asthmatic start with their medication.
 if (has_trait(PF_ASTHMA)) {
  tmp = item(g->itypes["inhaler"], 0);
  inv.push_back(tmp);
 }
// Basic starter gear, added independently of profession.
 tmp = item(g->itypes["pockknife"], 0);
  inv.push_back(tmp);
 tmp = item(g->itypes["matches"], 0);
  inv.push_back(tmp);
// make sure we have no mutations
 for (int i = 0; i < PF_MAX2; i++)
  if (!has_base_trait(i))
	my_mutations[i] = false;

	// Equip any armor from our inventory. If we are unable to wear some of it due to encumberance, it will silently fail.
    std::vector<item*> tmp_inv;
    inv.dump(tmp_inv);

    for(std::vector<item*>::iterator i = tmp_inv.begin(); i != tmp_inv.end(); ++i)
    {
        if( (*i)->is_armor())
        {
            if( (*i)->has_flag("VARSIZE"))
            {
                (*i)->item_tags.insert("FIT");
            }
            // It might be more elegant to use player::wear_item, but then we have to implement our own inventory removal.
            wear(g, (*i)->invlet, false);
        }
    }

 // Ensure that persistent morale effects (e.g. Optimist) are present at the start.
 apply_persistent_morale();
 return true;
}
Exemplo n.º 15
0
/*!
    Returns the maximum number of parameter bytes that can be passed
    to a kernel.
*/
int QCLDevice::maximumParameterBytes() const
{
    return int(qt_cl_paramSize(m_id, CL_DEVICE_MAX_PARAMETER_SIZE));
}
Exemplo n.º 16
0
int gcore::Thread::GetProcessorCount() {
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  return int(info.dwNumberOfProcessors);
}
Exemplo n.º 17
0
int Character::expForLevel(int level)
{
    return int(pow(level, EXPCURVE_EXPONENT) * EXPCURVE_FACTOR);
}
Exemplo n.º 18
0
void QGLFramebufferObjectPrivate::init(QGLFramebufferObject *q, const QSize &sz,
                                       QGLFramebufferObject::Attachment attachment,
                                       GLenum texture_target, GLenum internal_format,
                                       GLint samples, bool mipmap)
{
    QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext());
    fbo_guard.setContext(ctx);

    bool ext_detected = (QGLExtensions::glExtensions() & QGLExtensions::FramebufferObject);
    if (!ext_detected || (ext_detected && !qt_resolve_framebufferobject_extensions(ctx)))
        return;

    size = sz;
    target = texture_target;
    // texture dimensions

    QT_RESET_GLERROR(); // reset error state
    GLuint fbo = 0;
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER_EXT, fbo);
    fbo_guard.setId(fbo);

    glDevice.setFBO(q, attachment);

    QT_CHECK_GLERROR();
    // init texture
    if (samples == 0) {
        glGenTextures(1, &texture);
        glBindTexture(target, texture);
        glTexImage2D(target, 0, internal_format, size.width(), size.height(), 0,
                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
        if (mipmap)
            glGenerateMipmap(GL_TEXTURE_2D);
#ifndef QT_OPENGL_ES
        glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#else
        glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#endif
        glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                target, texture, 0);

        QT_CHECK_GLERROR();
        valid = checkFramebufferStatus();
        glBindTexture(target, 0);

        color_buffer = 0;
    } else {
        mipmap = false;
        GLint maxSamples;
        glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples);

        samples = qBound(0, int(samples), int(maxSamples));

        glGenRenderbuffers(1, &color_buffer);
        glBindRenderbuffer(GL_RENDERBUFFER_EXT, color_buffer);
        if (glRenderbufferStorageMultisampleEXT && samples > 0) {
            glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples,
                internal_format, size.width(), size.height());
        } else {
            samples = 0;
            glRenderbufferStorage(GL_RENDERBUFFER_EXT, internal_format,
                size.width(), size.height());
        }

        glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                                     GL_RENDERBUFFER_EXT, color_buffer);

        QT_CHECK_GLERROR();
        valid = checkFramebufferStatus();

        if (valid)
            glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &samples);
    }

    // In practice, a combined depth-stencil buffer is supported by all desktop platforms, while a
    // separate stencil buffer is not. On embedded devices however, a combined depth-stencil buffer
    // might not be supported while separate buffers are, according to QTBUG-12861.

    if (attachment == QGLFramebufferObject::CombinedDepthStencil
        && (QGLExtensions::glExtensions() & QGLExtensions::PackedDepthStencil)) {
        // depth and stencil buffer needs another extension
        glGenRenderbuffers(1, &depth_buffer);
        Q_ASSERT(!glIsRenderbuffer(depth_buffer));
        glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_buffer);
        Q_ASSERT(glIsRenderbuffer(depth_buffer));
        if (samples != 0 && glRenderbufferStorageMultisampleEXT)
            glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples,
                GL_DEPTH24_STENCIL8_EXT, size.width(), size.height());
        else
            glRenderbufferStorage(GL_RENDERBUFFER_EXT,
                GL_DEPTH24_STENCIL8_EXT, size.width(), size.height());

        stencil_buffer = depth_buffer;
        glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
                                     GL_RENDERBUFFER_EXT, depth_buffer);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
                                     GL_RENDERBUFFER_EXT, stencil_buffer);

        valid = checkFramebufferStatus();
        if (!valid) {
            glDeleteRenderbuffers(1, &depth_buffer);
            stencil_buffer = depth_buffer = 0;
        }
    }

    if (depth_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil
        || (attachment == QGLFramebufferObject::Depth)))
    {
        glGenRenderbuffers(1, &depth_buffer);
        Q_ASSERT(!glIsRenderbuffer(depth_buffer));
        glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_buffer);
        Q_ASSERT(glIsRenderbuffer(depth_buffer));
        if (samples != 0 && glRenderbufferStorageMultisampleEXT) {
#ifdef QT_OPENGL_ES
            if (QGLExtensions::glExtensions() & QGLExtensions::Depth24) {
                glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples,
                    GL_DEPTH_COMPONENT24_OES, size.width(), size.height());
            } else {
                glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples,
                    GL_DEPTH_COMPONENT16, size.width(), size.height());
            }
#else
            glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples,
                GL_DEPTH_COMPONENT, size.width(), size.height());
#endif
        } else {
#ifdef QT_OPENGL_ES
            if (QGLExtensions::glExtensions() & QGLExtensions::Depth24) {
                glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_OES, 
                                        size.width(), size.height());
            } else {
                glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, 
                                        size.width(), size.height());
            }
#else
            glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, size.width(), size.height());
#endif
        }
        glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
                                     GL_RENDERBUFFER_EXT, depth_buffer);
        valid = checkFramebufferStatus();
        if (!valid) {
            glDeleteRenderbuffers(1, &depth_buffer);
            depth_buffer = 0;
        }
    }

    if (stencil_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil)) {
        glGenRenderbuffers(1, &stencil_buffer);
        Q_ASSERT(!glIsRenderbuffer(stencil_buffer));
        glBindRenderbuffer(GL_RENDERBUFFER_EXT, stencil_buffer);
        Q_ASSERT(glIsRenderbuffer(stencil_buffer));
        if (samples != 0 && glRenderbufferStorageMultisampleEXT) {
#ifdef QT_OPENGL_ES
            glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples,
                GL_STENCIL_INDEX8_EXT, size.width(), size.height());
#else
            glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples,
                GL_STENCIL_INDEX, size.width(), size.height());
#endif
        } else {
#ifdef QT_OPENGL_ES
            glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX8_EXT,
                                  size.width(), size.height());
#else
            glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX,
                                  size.width(), size.height());
#endif
        }
        glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
                                  GL_RENDERBUFFER_EXT, stencil_buffer);
        valid = checkFramebufferStatus();
        if (!valid) {
            glDeleteRenderbuffers(1, &stencil_buffer);
            stencil_buffer = 0;
        }
    }

    // The FBO might have become valid after removing the depth or stencil buffer.
    valid = checkFramebufferStatus();

    if (depth_buffer && stencil_buffer) {
        fbo_attachment = QGLFramebufferObject::CombinedDepthStencil;
    } else if (depth_buffer) {
        fbo_attachment = QGLFramebufferObject::Depth;
    } else {
        fbo_attachment = QGLFramebufferObject::NoAttachment;
    }

    glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo);
    if (!valid) {
        if (color_buffer)
            glDeleteRenderbuffers(1, &color_buffer);
        else
            glDeleteTextures(1, &texture);
        if (depth_buffer)
            glDeleteRenderbuffers(1, &depth_buffer);
        if (stencil_buffer && depth_buffer != stencil_buffer)
            glDeleteRenderbuffers(1, &stencil_buffer);
        glDeleteFramebuffers(1, &fbo);
        fbo_guard.setId(0);
    }
    QT_CHECK_GLERROR();

    format.setTextureTarget(target);
    format.setSamples(int(samples));
    format.setAttachment(fbo_attachment);
    format.setInternalTextureFormat(internal_format);
    format.setMipmap(mipmap);
}
Exemplo n.º 19
0
void AActor::Die (AActor *source, AActor *inflictor, int dmgflags)
{
	// Handle possible unmorph on death
	bool wasgibbed = (health < GibHealth());

	AActor *realthis = NULL;
	int realstyle = 0;
	int realhealth = 0;
	if (P_MorphedDeath(this, &realthis, &realstyle, &realhealth))
	{
		if (!(realstyle & MORPH_UNDOBYDEATHSAVES))
		{
			if (wasgibbed)
			{
				int realgibhealth = realthis->GibHealth();
				if (realthis->health >= realgibhealth)
				{
					realthis->health = realgibhealth -1; // if morphed was gibbed, so must original be (where allowed)l
				}
			}
			realthis->Die(source, inflictor, dmgflags);
		}
		return;
	}

	// [SO] 9/2/02 -- It's rather funny to see an exploded player body with the invuln sparkle active :) 
	effects &= ~FX_RESPAWNINVUL;
	//flags &= ~MF_INVINCIBLE;

	if (debugfile && this->player)
	{
		static int dieticks[MAXPLAYERS];
		int pnum = int(this->player-players);
		dieticks[pnum] = gametic;
		fprintf (debugfile, "died (%d) on tic %d (%s)\n", pnum, gametic,
		this->player->cheats&CF_PREDICTING?"predicting":"real");
	}

	// [RH] Notify this actor's items.
	for (AInventory *item = Inventory; item != NULL; )
	{
		AInventory *next = item->Inventory;
		item->OwnerDied();
		item = next;
	}

	if (flags & MF_MISSILE)
	{ // [RH] When missiles die, they just explode
		P_ExplodeMissile (this, NULL, NULL);
		return;
	}
	// [RH] Set the target to the thing that killed it. Strife apparently does this.
	if (source != NULL)
	{
		target = source;
	}

	flags &= ~(MF_SHOOTABLE|MF_FLOAT|MF_SKULLFLY);
	if (!(flags4 & MF4_DONTFALL)) flags&=~MF_NOGRAVITY;
	flags |= MF_DROPOFF;
	if ((flags3 & MF3_ISMONSTER) || FindState(NAME_Raise) != NULL || IsKindOf(RUNTIME_CLASS(APlayerPawn)))
	{	// [RH] Only monsters get to be corpses.
		// Objects with a raise state should get the flag as well so they can
		// be revived by an Arch-Vile. Batman Doom needs this.
		// [RC] And disable this if DONTCORPSE is set, of course.
		if(!(flags6 & MF6_DONTCORPSE)) flags |= MF_CORPSE;
	}
	flags6 |= MF6_KILLED;

	// [RH] Allow the death height to be overridden using metadata.
	fixed_t metaheight = 0;
	if (DamageType == NAME_Fire)
	{
		metaheight = GetClass()->Meta.GetMetaFixed (AMETA_BurnHeight);
	}
	if (metaheight == 0)
	{
		metaheight = GetClass()->Meta.GetMetaFixed (AMETA_DeathHeight);
	}
	if (metaheight != 0)
	{
		height = MAX<fixed_t> (metaheight, 0);
	}
	else
	{
		height >>= 2;
	}

	// [RH] If the thing has a special, execute and remove it
	//		Note that the thing that killed it is considered
	//		the activator of the script.
	// New: In Hexen, the thing that died is the activator,
	//		so now a level flag selects who the activator gets to be.
	// Everything is now moved to P_ActivateThingSpecial().
	if (special && (!(flags & MF_SPECIAL) || (flags3 & MF3_ISMONSTER))
		&& !(activationtype & THINGSPEC_NoDeathSpecial))
	{
		P_ActivateThingSpecial(this, source, true); 
	}

	if (CountsAsKill())
		level.killed_monsters++;
		
	if (source && source->player)
	{
		if (CountsAsKill())
		{ // count for intermission
			source->player->killcount++;
		}

		// Don't count any frags at level start, because they're just telefrags
		// resulting from insufficient deathmatch starts, and it wouldn't be
		// fair to count them toward a player's score.
		if (player && level.maptime)
		{
			source->player->frags[player - players]++;
			if (player == source->player)	// [RH] Cumulative frag count
			{
				char buff[256];

				player->fragcount--;
				if (deathmatch && player->spreecount >= 5 && cl_showsprees)
				{
					SexMessage (GStrings("SPREEKILLSELF"), buff,
						player->userinfo.GetGender(), player->userinfo.GetName(),
						player->userinfo.GetName());
					StatusBar->AttachMessage (new DHUDMessageFadeOut (SmallFont, buff,
							1.5f, 0.2f, 0, 0, CR_WHITE, 3.f, 0.5f), MAKE_ID('K','S','P','R'));
				}
			}
			else
			{
				if ((dmflags2 & DF2_YES_LOSEFRAG) && deathmatch)
					player->fragcount--;

				++source->player->fragcount;
				++source->player->spreecount;
				if (source->player->morphTics)
				{ // Make a super chicken
					source->GiveInventoryType (RUNTIME_CLASS(APowerWeaponLevel2));
				}
				if (deathmatch && cl_showsprees)
				{
					const char *spreemsg;
					char buff[256];

					switch (source->player->spreecount)
					{
					case 5:
						spreemsg = GStrings("SPREE5");
						break;
					case 10:
						spreemsg = GStrings("SPREE10");
						break;
					case 15:
						spreemsg = GStrings("SPREE15");
						break;
					case 20:
						spreemsg = GStrings("SPREE20");
						break;
					case 25:
						spreemsg = GStrings("SPREE25");
						break;
					default:
						spreemsg = NULL;
						break;
					}

					if (spreemsg == NULL && player->spreecount >= 5)
					{
						if (!AnnounceSpreeLoss (this))
						{
							SexMessage (GStrings("SPREEOVER"), buff, player->userinfo.GetGender(),
								player->userinfo.GetName(), source->player->userinfo.GetName());
							StatusBar->AttachMessage (new DHUDMessageFadeOut (SmallFont, buff,
								1.5f, 0.2f, 0, 0, CR_WHITE, 3.f, 0.5f), MAKE_ID('K','S','P','R'));
						}
					}
					else if (spreemsg != NULL)
					{
						if (!AnnounceSpree (source))
						{
							SexMessage (spreemsg, buff, player->userinfo.GetGender(),
								player->userinfo.GetName(), source->player->userinfo.GetName());
							StatusBar->AttachMessage (new DHUDMessageFadeOut (SmallFont, buff,
								1.5f, 0.2f, 0, 0, CR_WHITE, 3.f, 0.5f), MAKE_ID('K','S','P','R'));
						}
					}
				}
			}

			// [RH] Multikills
			if (player != source->player)
			{
				source->player->multicount++;
				if (source->player->lastkilltime > 0)
				{
					if (source->player->lastkilltime < level.time - 3*TICRATE)
					{
						source->player->multicount = 1;
					}

					if (deathmatch &&
						source->CheckLocalView (consoleplayer) &&
						cl_showmultikills)
					{
						const char *multimsg;

						switch (source->player->multicount)
						{
						case 1:
							multimsg = NULL;
							break;
						case 2:
							multimsg = GStrings("MULTI2");
							break;
						case 3:
							multimsg = GStrings("MULTI3");
							break;
						case 4:
							multimsg = GStrings("MULTI4");
							break;
						default:
							multimsg = GStrings("MULTI5");
							break;
						}
						if (multimsg != NULL)
						{
							char buff[256];

							if (!AnnounceMultikill (source))
							{
								SexMessage (multimsg, buff, player->userinfo.GetGender(),
									player->userinfo.GetName(), source->player->userinfo.GetName());
								StatusBar->AttachMessage (new DHUDMessageFadeOut (SmallFont, buff,
									1.5f, 0.8f, 0, 0, CR_RED, 3.f, 0.5f), MAKE_ID('M','K','I','L'));
							}
						}
					}
				}
				source->player->lastkilltime = level.time;
			}

			// [RH] Implement fraglimit
			if (deathmatch && fraglimit &&
				fraglimit <= D_GetFragCount (source->player))
			{
				Printf ("%s\n", GStrings("TXT_FRAGLIMIT"));
				G_ExitLevel (0, false);
			}
		}
	}
	else if (!multiplayer && CountsAsKill())
	{
		// count all monster deaths,
		// even those caused by other monsters
		players[0].killcount++;
	}
	
	if (player)
	{
		// [RH] Death messages
		ClientObituary (this, inflictor, source, dmgflags);

		// Death script execution, care of Skull Tag
		FBehavior::StaticStartTypedScripts (SCRIPT_Death, this, true);

		// [RH] Force a delay between death and respawn
		player->respawn_time = level.time + TICRATE;

		//Added by MC: Respawn bots
		if (bglobal.botnum && consoleplayer == Net_Arbitrator && !demoplayback)
		{
			if (player->isbot)
				player->t_respawn = (pr_botrespawn()%15)+((bglobal.botnum-1)*2)+TICRATE+1;

			//Added by MC: Discard enemies.
			for (int i = 0; i < MAXPLAYERS; i++)
			{
				if (players[i].isbot && this == players[i].enemy)
				{
					if (players[i].dest ==  players[i].enemy)
						players[i].dest = NULL;
					players[i].enemy = NULL;
				}
			}

			player->spreecount = 0;
			player->multicount = 0;
		}

		// count environment kills against you
		if (!source)
		{
			player->frags[player - players]++;
			player->fragcount--;	// [RH] Cumulative frag count
		}
						
		flags &= ~MF_SOLID;
		player->playerstate = PST_DEAD;
		P_DropWeapon (player);
		if (this == players[consoleplayer].camera && automapactive)
		{
			// don't die in auto map, switch view prior to dying
			AM_Stop ();
		}

		// [GRB] Clear extralight. When you killed yourself with weapon that
		// called A_Light1/2 before it called A_Light0, extraligh remained.
		player->extralight = 0;
	}

	// [RH] If this is the unmorphed version of another monster, destroy this
	// actor, because the morphed version is the one that will stick around in
	// the level.
	if (flags & MF_UNMORPHED)
	{
		Destroy ();
		return;
	}



	FState *diestate = NULL;
	int gibhealth = GibHealth();
	int iflags4 = inflictor == NULL ? 0 : inflictor->flags4;
	bool extremelydead = ((health < gibhealth || iflags4 & MF4_EXTREMEDEATH) && !(iflags4 & MF4_NOEXTREMEDEATH));

	// Special check for 'extreme' damage type to ensure that it gets recorded properly as an extreme death for subsequent checks.
	if (DamageType == NAME_Extreme)
	{
		extremelydead = true;
		DamageType = NAME_None;
	}

	// find the appropriate death state. The order is:
	//
	// 1. If damagetype is not 'none' and death is extreme, try a damage type specific extreme death state
	// 2. If no such state is found or death is not extreme try a damage type specific normal death state
	// 3. If damagetype is 'ice' and actor is a monster or player, try the generic freeze death (unless prohibited)
	// 4. If no state has been found and death is extreme, try the extreme death state
	// 5. If no such state is found or death is not extreme try the regular death state.
	// 6. If still no state has been found, destroy the actor immediately.

	if (DamageType != NAME_None)
	{
		if (extremelydead)
		{
			FName labels[] = { NAME_Death, NAME_Extreme, DamageType };
			diestate = FindState(3, labels, true);
		}
		if (diestate == NULL)
		{
			diestate = FindState (NAME_Death, DamageType, true);
			if (diestate != NULL) extremelydead = false;
		}
		if (diestate == NULL)
		{
			if (DamageType == NAME_Ice)
			{ // If an actor doesn't have an ice death, we can still give them a generic one.

				if (!deh.NoAutofreeze && !(flags4 & MF4_NOICEDEATH) && (player || (flags3 & MF3_ISMONSTER)))
				{
					diestate = FindState(NAME_GenericFreezeDeath);
					extremelydead = false;
				}
			}
		}
	}
	if (diestate == NULL)
	{
		
		// Don't pass on a damage type this actor cannot handle.
		// (most importantly, prevent barrels from passing on ice damage.)
		// Massacre must be preserved though.
		if (DamageType != NAME_Massacre)
		{
			DamageType = NAME_None;	
		}

		if (extremelydead)
		{ // Extreme death
			diestate = FindState (NAME_Death, NAME_Extreme, true);
		}
		if (diestate == NULL)
		{ // Normal death
			extremelydead = false;
			diestate = FindState (NAME_Death);
		}
	}

	if (extremelydead)
	{ 
		// We'll only get here if an actual extreme death state was used.

		// For players, mark the appropriate flag.
		if (player != NULL)
		{
			player->cheats |= CF_EXTREMELYDEAD;
		}
		// If a non-player, mark as extremely dead for the crash state.
		else if (health >= gibhealth)
		{
			health = gibhealth - 1;
		}
	}

	if (diestate != NULL)
	{
		SetState (diestate);

		if (tics > 1)
		{
			tics -= pr_killmobj() & 3;
			if (tics < 1)
				tics = 1;
		}
	}
	else
	{
		Destroy();
	}
}
void	btMultiBodyDynamicsWorld::calculateSimulationIslands()
{
	BT_PROFILE("calculateSimulationIslands");

	getSimulationIslandManager()->updateActivationState(getCollisionWorld(),getCollisionWorld()->getDispatcher());

    {
        //merge islands based on speculative contact manifolds too
        for (int i=0;i<this->m_predictiveManifolds.size();i++)
        {
            btPersistentManifold* manifold = m_predictiveManifolds[i];
            
            const btCollisionObject* colObj0 = manifold->getBody0();
            const btCollisionObject* colObj1 = manifold->getBody1();
            
            if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
                ((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
            {
				getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag());
            }
        }
    }
    
	{
		int i;
		int numConstraints = int(m_constraints.size());
		for (i=0;i< numConstraints ; i++ )
		{
			btTypedConstraint* constraint = m_constraints[i];
			if (constraint->isEnabled())
			{
				const btRigidBody* colObj0 = &constraint->getRigidBodyA();
				const btRigidBody* colObj1 = &constraint->getRigidBodyB();

				if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
					((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
				{
					getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag());
				}
			}
		}
	}

	//merge islands linked by Featherstone link colliders
	for (int i=0;i<m_multiBodies.size();i++)
	{
		btMultiBody* body = m_multiBodies[i];
		{
			btMultiBodyLinkCollider* prev = body->getBaseCollider();

			for (int b=0;b<body->getNumLinks();b++)
			{
				btMultiBodyLinkCollider* cur = body->getLink(b).m_collider;
				
				if (((cur) && (!(cur)->isStaticOrKinematicObject())) &&
					((prev) && (!(prev)->isStaticOrKinematicObject())))
				{
					int tagPrev = prev->getIslandTag();
					int tagCur = cur->getIslandTag();
					getSimulationIslandManager()->getUnionFind().unite(tagPrev, tagCur);
				}
				if (cur && !cur->isStaticOrKinematicObject())
					prev = cur;
				
			}
		}
	}

	//merge islands linked by multibody constraints
	{
		for (int i=0;i<this->m_multiBodyConstraints.size();i++)
		{
			btMultiBodyConstraint* c = m_multiBodyConstraints[i];
			int tagA = c->getIslandIdA();
			int tagB = c->getIslandIdB();
			if (tagA>=0 && tagB>=0)
				getSimulationIslandManager()->getUnionFind().unite(tagA, tagB);
		}
	}

	//Store the island id in each body
	getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld());

}
Exemplo n.º 21
0
int jdk_http_do_request(
  const char *http_request_type, // "GET" or "POST"
  const char *url,
  jdk_buf *response,
  long max_response_size,
  jdk_http_response_header *response_header,
  const char *proxy,
  const char *additional_headers, // additional headers, 0 or blank for none
  const jdk_buf *send_content,  // data for POST or PUT, null for none
  const char *send_content_type, // POST or PUT content type, null or blank for none
  const char *http_version,
  bool use_ssl,
  const char *proxy_basic_auth_username,
  const char *proxy_basic_auth_password
  )
{
  int content_length=-1;
  // do we have content?
  if( send_content )
  {
    // yes! find out the length
    content_length = int(send_content->get_data_length());
  }
  
  jdk_str<256> connect_host;
  int connect_port;
  jdk_dynbuf request_buf;
  
  if( 		
    !jdk_http_form_request(
      connect_host, 
      connect_port,
      request_buf,
      url,
      http_request_type,
      proxy,
      content_length, 
      send_content_type,  
      additional_headers, 
      http_version,
      proxy_basic_auth_username,
      proxy_basic_auth_password
      ))
  {
    // error forming request! return failure
    jdk_log_debug2( "http_do_request: error forming request for %s", url );
    return -1;
  }
  
  jdk_inet_client_socket s;
  if( !s.make_connection( connect_host.c_str(), connect_port, 0, use_ssl ) )
  {
    // error connecting! return failure
    jdk_log_debug2( "http_do_request: connect error to %s:%d", connect_host.c_str(), connect_port );		
    return -1;
  }
  
  // send request		
  if( s.write_data_block( request_buf ) != (int)request_buf.get_data_length() )
  {
    // error sending request. return failure
    jdk_log_debug2( "http_do_request: error sending request to %s:%d", connect_host.c_str(), connect_port );			
    return -1;
  }
  
  if( content_length>0 && send_content )
  {
    if( s.write_data_block( *send_content ) != (int)send_content->get_data_length() )
    {
      jdk_log_debug2( "http_do_request: error sending request content to %s:%d", connect_host.c_str(), connect_port );			
      return -1;
    }
  }
  
  // now grab entire response
  jdk_dynbuf full_response;
  
  if( jdk_http_receive_buf( s, full_response, max_response_size )<0 )
  {
    // error receiving response. return failure
    jdk_log_debug2( "http_do_request: error receiving response from %s:%d", connect_host.c_str(), connect_port );  	   
    return -1;
  }
  
  // parse the response header
  if( !response_header->parse_buffer( full_response ) )
  {
    // error parsing the response. return failure
    jdk_log_debug2( "http_do_request: error parsing response for %s from %s:%d", url, connect_host.c_str(), connect_port );  	   		
    return -1;
  }
  
  // is it valid?
  if( !response_header->is_valid() )
  {
    // not valid. return failure
    jdk_log_debug2( "http_do_request: response header not valid for %s from %s:%d", url, connect_host.c_str(), connect_port );  	   			   
    return -1;
  }
  
  // we have a valid response, as far as the header goes.
  
  // store any response data after the header in the supplied buffer
  response->clear();
  response->append_from_buf( full_response, int(response_header->get_buf_pos()) );
  
  // TODO: double check content-length if it exists and double check the actual length   
  
  jdk_log_debug3( "http_do_request: response code %d for %s from %s:%d", 
                  response_header->get_http_response_code(), 
                  url, 
                  connect_host.c_str(), 
                  connect_port 
    );
  
  return response_header->get_http_response_code();	
}
Exemplo n.º 22
0
// ######################################################################
Image<float> ContourBoundaryDetector::getRidge
(std::vector<Image<float> > gradImg, int r)
{
  Image<float> gradImgX = gradImg[0];
  Image<float> gradImgY = gradImg[1];

  int w = gradImg[0].getWidth();
  int h = gradImg[0].getHeight();
  Image<float> ridgeImg(w,h,NO_INIT);

  std::vector<float> dx(NUM_GRADIENT_DIRECTIONS);
  std::vector<float> dy(NUM_GRADIENT_DIRECTIONS);    
  for(uint k = 0; k < NUM_GRADIENT_DIRECTIONS; k++)
    {
      dx[k] = cos(k*2*M_PI/NUM_GRADIENT_DIRECTIONS); 
      dy[k] = sin(k*2*M_PI/NUM_GRADIENT_DIRECTIONS);
    }

  // threshold the gradient image
  std::vector<std::vector<Image<float> > > dVin(NUM_GRADIENT_DIRECTIONS); 
  for(uint k = 0; k < NUM_GRADIENT_DIRECTIONS; k++)
    dVin[k] = std::vector<Image<float> >(2);

  for(uint k = 0; k < NUM_GRADIENT_DIRECTIONS; k++)
    {
      dVin[k][0] = Image<float>(w,h,NO_INIT);
      dVin[k][1] = Image<float>(w,h,NO_INIT);

      for(int i = 0; i < w; i++)
	{
	  for(int j = 0; j < h; j++)
	    {
	      float x = 0.0;
	      float y = 0.0;

	      int ii = int(i + r*dx[k]);
	      int jj = int(j + r*dy[k]); 

	      if(ii <  0) ii = -ii;
	      if(jj <  0) jj = -jj;
	      if(ii >= w) ii = 2*w - 2 - ii;
	      if(jj >= h) jj = 2*h - 2 - jj;
	      
	      float vX = gradImgX.getVal(ii,jj); 
	      float vY = gradImgY.getVal(ii,jj);
	      if((vX*dx[k] + vY*dy[k]) < 0.0)
		{
		  x = vX;
		  y = vY;
		}
	      
	      dVin[k][0].setVal(i,j, x);
	      dVin[k][1].setVal(i,j, y);	      
	    }
	}
    }
  itsDVin = dVin;

  std::vector<Image<float> > rDir (NUM_GRADIENT_DIRECTIONS); 
  Image<float> rDirIndex(w,h,NO_INIT);

  // calculate the geometric and arithmetic ridge direction
  // and sum the two together
  for(uint k = 0; k < NUM_GRADIENT_DIRECTIONS; k++)
    {
      rDir[k] = Image<float>(w,h,NO_INIT);

      for(int i = 0; i < w; i++)
	{
	  for(int j = 0; j < h; j++)
	    {
	      float x1 = dVin[k][0].getVal(i,j);
	      float y1 = dVin[k][1].getVal(i,j);

	      uint k2 = k + NUM_RIDGE_DIRECTIONS;
	      if(k >= NUM_RIDGE_DIRECTIONS) 
		k2 = k - NUM_RIDGE_DIRECTIONS/2;

	      float x2 = dVin[k2][0].getVal(i,j);
	      float y2 = dVin[k2][1].getVal(i,j);

	      float gVal = -(x1*x2 + y1*y2);	     	      
	      if(gVal < 0.0) 
		gVal = 0.0;
	      else 
		gVal = pow(gVal, 0.5);

	      // float ax = x2 - x1;
	      // float ay = y2 - y1;
	      // float aVal =  pow(ax*ax + ay*ay, 0.5)/ 2.0;	      
	      // rDir[k].setVal(i,j, gVal + aVal);

	      rDir[k].setVal(i,j, gVal);
	    }
	}
    }

  itsRidgeDirection = rDir;

  std::vector<Image<float> > rDirMax(NUM_RIDGE_DIRECTIONS); 
  for(uint k = 0; k < NUM_RIDGE_DIRECTIONS; k++)    
    rDirMax[k] = Image<float>(w,h,ZEROS);

  // get the maximum among the directions
  for(int i = 0; i < w; i++)
    {
      for(int j = 0; j < h; j++)
	{
	  float max = 0.0; int maxk = -1;
	  for(uint k = 0; k < NUM_RIDGE_DIRECTIONS; k++)
	    {
	      float val = rDir[k].getVal(i,j);
	      if(val > max) { max = val; maxk = k; }
	    }
	  ridgeImg.setVal(i,j, max);
	  rDirIndex.setVal(i,j, maxk);
	  if(maxk != -1)
	    rDirMax[maxk].setVal(i,j, max);
	}
    }

  itsRidgeDirectionIndex = rDirIndex;
  itsRidgeDirectionMax   = rDirMax;

  return ridgeImg;
}
Exemplo n.º 23
0
bool IMGUI::doSelectbox(int id, const Vector2& pos1, const Vector2& pos2, const std::vector<std::string>& entries, int& selected, unsigned int flags)
{
	int FontSize = (flags & TF_SMALL_FONT ? (FONT_WIDTH_SMALL+LINE_SPACER_SMALL) : (FONT_WIDTH_NORMAL+LINE_SPACER_NORMAL));
	bool changed = false;
	QueueObject obj;
	obj.id = id;
	obj.pos1 = pos1;
	obj.pos2 = pos2;
	obj.type = SELECTBOX;
	obj.flags = flags;

	const int itemsPerPage = int(pos2.y - pos1.y - 10) / FontSize;
	int first = (int)(selected / itemsPerPage)*itemsPerPage; //the first visible element in the list

	if (!mInactive)
	{
		// M.W. : Activate cursorless object-highlighting once the up or down key is pressed.
		if (mActiveButton == -1)
		{
			switch (mLastKeyAction)
			{
				case DOWN:
					mActiveButton = 0;
					mLastKeyAction = NONE;
					break;
				case UP:
					mActiveButton = mLastWidget;
					mLastKeyAction = NONE;
					break;
				default:
					break;
			}
		}
		
		// Highlight first menu object for arrow key navigation.
		if (mActiveButton == 0 && !mButtonReset)
			mActiveButton = id;
		
		// React to keyboard input.
		if (id == mActiveButton)
		{
			obj.type = ACTIVESELECTBOX;
			switch (mLastKeyAction)
			{
				case DOWN:
					mActiveButton = 0;
					mLastKeyAction = NONE;
					break;
				case UP:
					mActiveButton = mLastWidget;
					mLastKeyAction = NONE;
					break;
				case LEFT:
					if (selected > 0)
					{
						selected--;
						changed = true;
					}
					mLastKeyAction = NONE;
					break;
				case RIGHT:
					if (selected < entries.size()-1)
					{
						selected++;
						changed = true;
					}
					mLastKeyAction = NONE;
					break;
				default:
					break;
			}
		}
		
		// React to mouse input.
		Vector2 mousepos = InputManager::getSingleton()->position();
		if (mousepos.x > pos1.x && mousepos.y > pos1.y && mousepos.x < pos2.x && mousepos.y < pos2.y)
		{
			obj.type = ACTIVESELECTBOX;
			if (InputManager::getSingleton()->click())
				mActiveButton = id;
		}
		//entries mouseclick:
		if (mousepos.x > pos1.x &&
			mousepos.y > pos1.y+5 &&
			mousepos.x < pos2.x-35 &&
			mousepos.y < pos1.y+5+FontSize*itemsPerPage)
		{
			if (InputManager::getSingleton()->click())
			{
				int tmp = (int)((mousepos.y-pos1.y-5) / FontSize)+first;
				if (tmp < entries.size())
					selected = tmp;
				mActiveButton = id;
			}
			if ((InputManager::getSingleton()->mouseWheelUp()) && (selected > 0))
			{
				selected--;
				changed = true;
			}
			if ((InputManager::getSingleton()->mouseWheelDown()) && (selected < entries.size()-1))
			{
				selected++;
				changed = true;
			}
		}
		//arrows mouseclick:
		if (mousepos.x > pos2.x-30 && mousepos.x < pos2.x-30+24 && InputManager::getSingleton()->click())
		{
			if (mousepos.y > pos1.y+3 && mousepos.y < pos1.y+3+24 && selected > 0)
			{
				selected--;
				changed = true;
			}
			if (mousepos.y > pos2.y-27 && mousepos.y < pos2.y-27+24 && selected < entries.size()-1)
			{
				selected++;
				changed = true;
			}
		}
	}
	doImage(GEN_ID, Vector2(pos2.x-15, pos1.y+15), "gfx/pfeil_oben.bmp");
	doImage(GEN_ID, Vector2(pos2.x-15, pos2.y-15), "gfx/pfeil_unten.bmp");

	first = (selected / itemsPerPage)*itemsPerPage; //recalc first
	if (entries.size() != 0)
	{
		int last = first + itemsPerPage;
		if (last > entries.size())
			last = entries.size();
		obj.entries = std::vector<std::string>(entries.begin()+first, entries.begin()+last);
	}
	else
		obj.entries = std::vector<std::string>();
	obj.selected = selected-first;

	mLastWidget = id;
	mQueue->push(obj);

	return changed;
}
Exemplo n.º 24
0
// ######################################################################
Image<float> ContourBoundaryDetector::getContourBoundaryEdgels()
{
  // NOTE: FIXXXX: TENSOR-VOTING IS PROBABLY A BETTER IDEA

  int w = itsImage.getWidth();
  int h = itsImage.getHeight();
  Image<float> edgelBoundaryImage(w,h,ZEROS);

  int step  = BOUNDARY_STEP_SIZE;
  int hstep = step/2;
  //int wSize = BOUNDARY_STEP_SIZE+1;

  // set up the center and surround opponency locations
  std::vector<std::vector<Point2D<int> > > cCoords(NUM_RIDGE_DIRECTIONS);
  std::vector<std::vector<Point2D<int> > > sCoords(NUM_RIDGE_DIRECTIONS);
  std::vector<float> angles;

  for(uint k = 0; k < NUM_RIDGE_DIRECTIONS; k++)
    {
      cCoords[k] = std::vector<Point2D<int> >();  
      sCoords[k] = std::vector<Point2D<int> >();  

      angles.push_back(k*2.0*M_PI/float(NUM_RIDGE_DIRECTIONS));
    }

  // fill the center coordinates
  for(int i = -step/2; i < step/2; i++)
    {
      cCoords[0].push_back(Point2D<int>( i, 0));
      cCoords[1].push_back(Point2D<int>( i, i));
      cCoords[2].push_back(Point2D<int>( 0, i));
      cCoords[3].push_back(Point2D<int>( i,-i));
    }

  // fill the surround coordinates (bottom or right)
  for(int i = 0; i < hstep; i++)
    {
      sCoords[0].push_back(Point2D<int>( i+hstep,       0));
      sCoords[0].push_back(Point2D<int>( i+hstep,   hstep));
      sCoords[0].push_back(Point2D<int>( i+hstep,  -hstep));

      sCoords[1].push_back(Point2D<int>( i+hstep, i+hstep));
      sCoords[1].push_back(Point2D<int>( i+step , i      ));
      sCoords[1].push_back(Point2D<int>( i      ,-i-step ));

      sCoords[2].push_back(Point2D<int>(       0, i+hstep));
      sCoords[2].push_back(Point2D<int>(   hstep, i+hstep));
      sCoords[2].push_back(Point2D<int>(  -hstep, i+hstep));

      sCoords[3].push_back(Point2D<int>( i+hstep,-i-hstep));
      sCoords[3].push_back(Point2D<int>( i      ,-i-step ));
      sCoords[3].push_back(Point2D<int>( i+step ,-i      ));
    }

  // fill the surround coordinates (top or left)
  for(int i = -hstep; i < 0; i++)
    {
      sCoords[0].push_back(Point2D<int>( i-hstep,       0));
      sCoords[0].push_back(Point2D<int>( i-hstep,   hstep));
      sCoords[0].push_back(Point2D<int>( i-hstep,  -hstep));

      sCoords[1].push_back(Point2D<int>( i-hstep, i-hstep));
      sCoords[1].push_back(Point2D<int>( i-step , i      ));
      sCoords[1].push_back(Point2D<int>( i      , i-step ));

      sCoords[2].push_back(Point2D<int>(       0, i-hstep));
      sCoords[2].push_back(Point2D<int>(   hstep, i-hstep));
      sCoords[2].push_back(Point2D<int>(  -hstep, i-hstep));

      sCoords[3].push_back(Point2D<int>( i-hstep,-i+hstep));
      sCoords[3].push_back(Point2D<int>( i      ,-i+step ));
      sCoords[3].push_back(Point2D<int>( i-step ,-i      ));
    }

  // reset the edgel storage
  // NOTE: we will keep edgel at index 0 empty
  int wEdgel = (w+hstep)/step; 
  int hEdgel = (h+hstep)/step;
  itsCompleteEdgels = 
    Image<std::vector<rutz::shared_ptr<Edgel> > >(wEdgel, hEdgel, ZEROS);
  itsEdgels = Image<rutz::shared_ptr<Edgel> >(wEdgel, hEdgel, ZEROS);

  // go through each point
  // with the specified step size
  int wLimit = (w/step)*step;
  int hLimit = (h/step)*step;
  for(int j = step; j < hLimit; j+= step)
    {
      for(int i = step; i < wLimit; i+= step)
        {
	  Point2D<int> cpt(i,j);
	  
	  int maxk = -1;
	  Point2D<int> maxPt(-1,-1);
	  float maxVal = -1.0F;

          uint iEdgel = i/step;
          uint jEdgel = j/step;

	  // for each direction
	  for(uint k = 0; k < NUM_RIDGE_DIRECTIONS; k++)
	    {
	      Point2D<int> maxCKpt(-1,-1);
	      float maxCKval = 0.0;

	      // get maximum contour value for the center size
	      // to make the contour detector phase invariant
	      for(uint ci = 0; ci < cCoords[k].size(); ci++)
		{
		  Point2D<int> pt = cCoords[k][ci] + cpt;  
		  if(edgelBoundaryImage.coordsOk(pt)) 
		    {
		      float val = itsRidgeDirectionNMS[k].getVal(pt); 
		      if(maxCKval < val) 
			{
			  maxCKval = val; maxCKpt = pt;
			}
		    }
		}

	      float maxSKval = 0.0;

	      // get the maximum value for the surround 
	      for(uint si = 0; si < sCoords[k].size(); si++)
		{
		  Point2D<int> pt = sCoords[k][si] + cpt;  
		  if(edgelBoundaryImage.coordsOk(pt)) 
		    {
		      float val = itsRidgeDirectionNMS[k].getVal(pt); 
		      if(maxSKval < val) maxSKval = val;
		    }
		}
	      
	      // if center > 0 and wins
	      if(maxCKval > 0.0F && maxCKval > maxSKval)
		{
		  if(maxCKval > maxVal) 
		    {
		      maxPt  = maxCKpt;
		      maxVal = maxCKval;
		      maxk   = k;
		    }
                  
                  // put the new edgel in the right position
                  rutz::shared_ptr<Edgel> 
                    edgel(new Edgel(maxCKpt, angles[k], k, maxCKval)); 
                  
                  std::vector<rutz::shared_ptr<Edgel> >
                    cEdgelList = itsCompleteEdgels.getVal(iEdgel,jEdgel);

                  uint eNum = cEdgelList.size();
                  uint place = 0;
                  for(uint ce = 0; ce < eNum; ce++)
                    {
                      if(cEdgelList[ce]->val < maxCKval)
                        {
                          place = ce; ce = eNum;
                        }
                      else place = ce+1;
                    }
                  //LINFO("place: %d  | eNum: %d", place, eNum);
                  
                  cEdgelList.push_back(edgel);
                  
                  // for(uint ce = 0; ce < cEdgelList.size(); ce++)
                  //   LINFO("%12.5f %3d", cEdgelList[ce]->val,  
                  //         cEdgelList[ce]->angleIndex);

                  if(place != eNum)
                    {
                      // LINFO("move one");
                  
                      for(int ce = int(eNum-1); ce >= int(place); ce--)
                        {
                          cEdgelList[ce+1] = cEdgelList[ce];
                        }
                      
                      // for(uint ce = 0; ce < cEdgelList.size(); ce++)
                      //   LINFO("%12.5f %3d", cEdgelList[ce]->val,  
                      //         cEdgelList[ce]->angleIndex);
                      
                      cEdgelList[place] = edgel;                  
                      
                      // LINFO("place the new one properly");

                      // for(uint ce = 0; ce < cEdgelList.size(); ce++)
                      //   LINFO("%12.5f %3d", cEdgelList[ce]->val,  
                      //         cEdgelList[ce]->angleIndex);
                    }
                  // else LINFO("last place");

                  itsCompleteEdgels.setVal(iEdgel,jEdgel, cEdgelList);


                  // LINFO("%d %d: size: %d ", i,j, 
                  //       int(itsCompleteEdgels.getVal(iEdgel,jEdgel).size()));

                  // for(uint ce = 0; ce < cEdgelList.size(); ce++)
                  //   LINFO("%12.5f %3d", cEdgelList[ce]->val,  
                  //         cEdgelList[ce]->angleIndex);
		}
	    }

	  // if there is a winner
	  if(maxk != -1)
	    {
              itsEdgels.setVal
                (iEdgel,jEdgel, itsCompleteEdgels.getVal(iEdgel,jEdgel)[0]);

	      float borderK = 
		fmod((maxk+(NUM_RIDGE_DIRECTIONS/2)),NUM_RIDGE_DIRECTIONS);

	      float dx = cos(borderK * M_PI/4.0) * hstep; 
	      float dy = sin(borderK * M_PI/4.0) * hstep;

	      Point2D<int> pt = maxPt;
	      Point2D<int> p1 = pt + Point2D<int>( dx+.5,  dy+.5); 
	      Point2D<int> p2 = pt + Point2D<int>(-dx-.5, -dy-.5);

              //uint iEdgel = i/step;
              //uint jEdgel = j/step;
              //if(iEdgel >= 10 && iEdgel <= 25 && jEdgel >= 1 && jEdgel <= 14)
              //   {
              //     LINFO("maxk: %d -> %d  -> %f  %f (%f %f %f %f)  |%f %f", 
              //           maxk, (maxk+(NUM_RIDGE_DIRECTIONS/2)), 
              //           (borderK*M_PI)/float(NUM_RIDGE_DIRECTIONS), borderK, 
              //           cos(0), cos(M_PI/4.0), cos(M_PI/2.0), cos(M_PI*.75),
              //           dx, dy);
	      


              //LINFO("%d %d | %d %d | %d %d::::: %d %d  %d", 
              //         pt.i, pt.j, p1.i, p1.j, p2.i, p2.j, iEdgel, jEdgel, maxk);
                  
              // draw the straightline contour in the image 
              // for visualization
              drawLine(edgelBoundaryImage, p1, p2, 255.0F);
              //drawDisk(edgelBoundaryImage, pt, 2,  255.0F);
              // }      
              
	    }
	}
    }

  return edgelBoundaryImage;
}
Exemplo n.º 25
0
int CEditor::PopupQuad(CEditor *pEditor, CUIRect View)
{
    CQuad *pQuad = pEditor->GetSelectedQuad();

    CUIRect Button;

    // delete button
    View.HSplitBottom(12.0f, &View, &Button);
    static int s_DeleteButton = 0;
    if(pEditor->DoButton_Editor(&s_DeleteButton, "Delete", 0, &Button, 0, "Deletes the current quad"))
    {
        CLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS);
        if(pLayer)
        {
            pEditor->m_Map.m_Modified = true;
            pLayer->m_lQuads.remove_index(pEditor->m_SelectedQuad);
            pEditor->m_SelectedQuad--;
        }
        return 1;
    }

    // aspect ratio button
    View.HSplitBottom(10.0f, &View, &Button);
    View.HSplitBottom(12.0f, &View, &Button);
    CLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS);
    if(pLayer && pLayer->m_Image >= 0 && pLayer->m_Image < pEditor->m_Map.m_lImages.size())
    {
        static int s_AspectRatioButton = 0;
        if(pEditor->DoButton_Editor(&s_AspectRatioButton, "Aspect ratio", 0, &Button, 0, "Resizes the current Quad based on the aspect ratio of the image"))
        {
            int Top = pQuad->m_aPoints[0].y;
            int Left = pQuad->m_aPoints[0].x;
            int Right = pQuad->m_aPoints[0].x;

            for(int k = 1; k < 4; k++)
            {
                if(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y;
                if(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x;
                if(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x;
            }

            int Height = (Right-Left)*pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Height/pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Width;

            pQuad->m_aPoints[0].x = Left;
            pQuad->m_aPoints[0].y = Top;
            pQuad->m_aPoints[1].x = Right;
            pQuad->m_aPoints[1].y = Top;
            pQuad->m_aPoints[2].x = Left;
            pQuad->m_aPoints[2].y = Top+Height;
            pQuad->m_aPoints[3].x = Right;
            pQuad->m_aPoints[3].y = Top+Height;
            pEditor->m_Map.m_Modified = true;
            return 1;
        }
    }

    // align button
    View.HSplitBottom(6.0f, &View, &Button);
    View.HSplitBottom(12.0f, &View, &Button);
    static int s_AlignButton = 0;
    if(pEditor->DoButton_Editor(&s_AlignButton, "Align", 0, &Button, 0, "Aligns coordinates of the quad points"))
    {
        for(int k = 1; k < 4; k++)
        {
            pQuad->m_aPoints[k].x = 1000.0f * (int(pQuad->m_aPoints[k].x) / 1000);
            pQuad->m_aPoints[k].y = 1000.0f * (int(pQuad->m_aPoints[k].y) / 1000);
        }
        pEditor->m_Map.m_Modified = true;
        return 1;
    }

    // square button
    View.HSplitBottom(6.0f, &View, &Button);
    View.HSplitBottom(12.0f, &View, &Button);
    static int s_Button = 0;
    if(pEditor->DoButton_Editor(&s_Button, "Square", 0, &Button, 0, "Squares the current quad"))
    {
        int Top = pQuad->m_aPoints[0].y;
        int Left = pQuad->m_aPoints[0].x;
        int Bottom = pQuad->m_aPoints[0].y;
        int Right = pQuad->m_aPoints[0].x;

        for(int k = 1; k < 4; k++)
        {
            if(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y;
            if(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x;
            if(pQuad->m_aPoints[k].y > Bottom) Bottom = pQuad->m_aPoints[k].y;
            if(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x;
        }

        pQuad->m_aPoints[0].x = Left;
        pQuad->m_aPoints[0].y = Top;
        pQuad->m_aPoints[1].x = Right;
        pQuad->m_aPoints[1].y = Top;
        pQuad->m_aPoints[2].x = Left;
        pQuad->m_aPoints[2].y = Bottom;
        pQuad->m_aPoints[3].x = Right;
        pQuad->m_aPoints[3].y = Bottom;
        pEditor->m_Map.m_Modified = true;
        return 1;
    }


    enum
    {
        PROP_POS_X=0,
        PROP_POS_Y,
        PROP_POS_ENV,
        PROP_POS_ENV_OFFSET,
        PROP_COLOR_ENV,
        PROP_COLOR_ENV_OFFSET,
        NUM_PROPS,
    };

    CProperty aProps[] = {
        {"Pos X", pQuad->m_aPoints[4].x/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000},
        {"Pos Y", pQuad->m_aPoints[4].y/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000},
        {"Pos. Env", pQuad->m_PosEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1},
        {"Pos. TO", pQuad->m_PosEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000},
        {"Color Env", pQuad->m_ColorEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1},
        {"Color TO", pQuad->m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000},

        {0},
    };

    static int s_aIds[NUM_PROPS] = {0};
    int NewVal = 0;
    int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal);
    if(Prop != -1)
        pEditor->m_Map.m_Modified = true;

    if(Prop == PROP_POS_X)
    {
        float Offset = NewVal*1000-pQuad->m_aPoints[4].x;
        for(int k = 0; k < 5; ++k)
            pQuad->m_aPoints[k].x += Offset;
    }
    if(Prop == PROP_POS_Y)
    {
        float Offset = NewVal*1000-pQuad->m_aPoints[4].y;
        for(int k = 0; k < 5; ++k)
            pQuad->m_aPoints[k].y += Offset;
    }
    if(Prop == PROP_POS_ENV) pQuad->m_PosEnv = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);
    if(Prop == PROP_POS_ENV_OFFSET) pQuad->m_PosEnvOffset = NewVal;
    if(Prop == PROP_COLOR_ENV) pQuad->m_ColorEnv = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);
    if(Prop == PROP_COLOR_ENV_OFFSET) pQuad->m_ColorEnvOffset = NewVal;

    return 0;
}
Exemplo n.º 26
0
  void cvRenderBlob(const IplImage *imgLabel, CvBlob *blob, IplImage *imgSource, IplImage *imgDest, unsigned short mode, CvScalar const &color, double alpha)
  {
    CV_FUNCNAME("cvRenderBlob");
    __CV_BEGIN__;

    CV_ASSERT(imgLabel&&(imgLabel->depth==IPL_DEPTH_LABEL)&&(imgLabel->nChannels==1));
    CV_ASSERT(imgDest&&(imgDest->depth==IPL_DEPTH_8U)&&(imgDest->nChannels==3));

    if (mode&CV_BLOB_RENDER_COLOR)
    {
      int stepLbl = imgLabel->widthStep/(imgLabel->depth/8);
      int stepSrc = imgSource->widthStep/(imgSource->depth/8);
      int stepDst = imgDest->widthStep/(imgDest->depth/8);
      int imgLabel_width = imgLabel->width;
      int imgLabel_height = imgLabel->height;
      int imgLabel_offset = 0;
      int imgSource_width = imgSource->width;
      int imgSource_height = imgSource->height;
      int imgSource_offset = 0;
      int imgDest_width = imgDest->width;
      int imgDest_height = imgDest->height;
      int imgDest_offset = 0;
      if(imgLabel->roi)
      {
	imgLabel_width = imgLabel->roi->width;
	imgLabel_height = imgLabel->roi->height;
	imgLabel_offset = (imgLabel->nChannels * imgLabel->roi->xOffset) + (imgLabel->roi->yOffset * stepLbl);
      }
      if(imgSource->roi)
      {
	imgSource_width = imgSource->roi->width;
	imgSource_height = imgSource->roi->height;
	imgSource_offset = (imgSource->nChannels * imgSource->roi->xOffset) + (imgSource->roi->yOffset * stepSrc);
      }
      if(imgDest->roi)
      {
	imgDest_width = imgDest->roi->width;
	imgDest_height = imgDest->roi->height;
	imgDest_offset = (imgDest->nChannels * imgDest->roi->xOffset) + (imgDest->roi->yOffset * stepDst);
      }

      CvLabel *labels = (CvLabel *)imgLabel->imageData + imgLabel_offset + (blob->miny * stepLbl);
      unsigned char *source = (unsigned char *)imgSource->imageData + imgSource_offset + (blob->miny * stepSrc);
      unsigned char *imgData = (unsigned char *)imgDest->imageData + imgDest_offset + (blob->miny * stepDst);

      for (unsigned int r=blob->miny; r<blob->maxy; r++, labels+=stepLbl, source+=stepSrc, imgData+=stepDst)
	for (unsigned int c=blob->minx; c<blob->maxx; c++)
	{
	  if (labels[c]==blob->label)
	  {
	    imgData[imgDest->nChannels*c+0] = (unsigned char)((1.-alpha)*source[imgSource->nChannels*c+0]+alpha*color.val[0]);
	    imgData[imgDest->nChannels*c+1] = (unsigned char)((1.-alpha)*source[imgSource->nChannels*c+1]+alpha*color.val[1]);
	    imgData[imgDest->nChannels*c+2] = (unsigned char)((1.-alpha)*source[imgSource->nChannels*c+2]+alpha*color.val[2]);
	  }
	}
    }

    if (mode)
    {
      if (mode&CV_BLOB_RENDER_TO_LOG)
      {
	std::clog << "Blob " << blob->label << std::endl;
	std::clog << " - Bounding box: (" << blob->minx << ", " << blob->miny << ") - (" << blob->maxx << ", " << blob->maxy << ")" << std::endl;
	std::clog << " - Bounding box area: " << (1 + blob->maxx - blob->minx) * (1 + blob->maxy - blob->miny) << std::endl;
	std::clog << " - Area: " << blob->area << std::endl;
	std::clog << " - Centroid: (" << blob->centroid.x << ", " << blob->centroid.y << ")" << std::endl;
	std::clog << std::endl;
      }

      if (mode&CV_BLOB_RENDER_TO_STD)
      {
	std::cout << "Blob " << blob->label << std::endl;
	std::cout << " - Bounding box: (" << blob->minx << ", " << blob->miny << ") - (" << blob->maxx << ", " << blob->maxy << ")" << std::endl;
	std::cout << " - Bounding box area: " << (1 + blob->maxx - blob->minx) * (1 + blob->maxy - blob->miny) << std::endl;
	std::cout << " - Area: " << blob->area << std::endl;
	std::cout << " - Centroid: (" << blob->centroid.x << ", " << blob->centroid.y << ")" << std::endl;
	std::cout << std::endl;
      }

      if (mode&CV_BLOB_RENDER_BOUNDING_BOX)
	cvRectangle(imgDest,cvPoint(blob->minx,blob->miny),cvPoint(blob->maxx,blob->maxy),CV_RGB(255.,0.,0.));

      if (mode&CV_BLOB_RENDER_ANGLE)
      {
	cvCentralMoments(blob, imgLabel);
	double angle = cvAngle(blob);

	double x1,y1,x2,y2;
	double lengthLine = MAX(blob->maxx-blob->minx, blob->maxy-blob->miny)/2.;

	x1=blob->centroid.x-lengthLine*cos(angle);
	y1=blob->centroid.y-lengthLine*sin(angle);
	x2=blob->centroid.x+lengthLine*cos(angle);
	y2=blob->centroid.y+lengthLine*sin(angle);
	cvLine(imgDest,cvPoint(int(x1),int(y1)),cvPoint(int(x2),int(y2)),CV_RGB(0.,255.,0.));
      }

      if (mode&CV_BLOB_RENDER_CENTROID)
      {
	cvLine(imgDest,cvPoint(int(blob->centroid.x)-3,int(blob->centroid.y)),cvPoint(int(blob->centroid.x)+3,int(blob->centroid.y)),CV_RGB(0.,0.,255.));
	cvLine(imgDest,cvPoint(int(blob->centroid.x),int(blob->centroid.y)-3),cvPoint(int(blob->centroid.x),int(blob->centroid.y)+3),CV_RGB(0.,0.,255.));
      }
    }

    __CV_END__;
  }
Exemplo n.º 27
0
int TimingPool::GiveIDFor(const std::string& name)
{	
	m_names.push_back(ReplaceAnonymousNamespace(name));
	return int(m_names.size() - 1);
}
Exemplo n.º 28
0
SbVec3f RayTracer::calculate_texture(SbVec3f poi, Object* obj){
    SbVec3f color;
    float width = 0.1;
    float pie = 3.1432;
    color.setValue(1.0,1.0,1.0);
    if(obj->texture == 0)
        return color;
    SbVec3f poi_in_object_space;
    poi_in_object_space = obj->multiply_with_inverse(poi);

    if(obj->texture == TEXTURE_SMOOTH_COLORS){
        color[0] = 1 - fabs((2 * fract(poi_in_object_space[0]) -1));
        color[1] = 1 - fabs((2 * fract(poi_in_object_space[1]) -1));
        color[2] = 1 - fabs((2 * fract(poi_in_object_space[2]) -1));
    }
    else if(obj->texture == TEXTURE_STRIPS)
    {
        float sine = 0;
        sine = sin(pie* poi_in_object_space[2] / width);
        if(sine > 0)
            color.setValue(0.8,0.8,0.8);
    }
    else if(obj->texture == TEXTURE_CONCENTRIC_CIRCLES){
        float r;
        r = sqrtf(pow(poi_in_object_space[0],2) + pow(poi_in_object_space[1],2));
        if(int(r/width) % 2 == 0)
            color.setValue(0.0,0.0,0.0);
    }
    else if(obj->texture == TEXTURE_CHECKERBOARD){
        float r;
        float width = 0.2;
        r = ((int) (poi[0]/width) +
            (int) (poi[1]/width) +
            (int) (poi[2]/width) )
                % 2;
        if(r== 0)
            color.setValue(0.5,0.5,0.5);
    }else if(obj->texture == TEXTURE_WOOD_GRAIN){
            float retNoise1;
            retNoise1 = noise(poi[0],poi[1],poi[2]);
            color.setValue(retNoise1, retNoise1, retNoise1);

    }
    else if(obj->texture == TEXTURE_RANDOM_SURFACE){
            float retNoise1, retNoise2, retNoise3;
            retNoise1 = noise(poi[0],poi[1],poi[2]);
            retNoise2 = noise(poi[1],poi[2],poi[0]);
            retNoise3 = noise(poi[2],poi[0],poi[1]);

            color.setValue(retNoise1, retNoise2, retNoise3);
    }

    else if(obj->texture == TEXTURE_CUSTOM1){
        int r;
        float width = 0.4;
        r = abs(((int) (poi_in_object_space[0]/width) +
            (int) (poi_in_object_space[1]/width) +
            (int) (poi_in_object_space[2]/width) )
                % 10);
                //std::cout<<r<<std::endl;
                float val = (float) r/ 10.0;
        color.setValue(val,val,val);
    }
    //color = poi_in_object_space;
    return color;

}
Exemplo n.º 29
0
	inline ostream & operator<<(ostream & o, Cmd const& cmd) {
		o << format("(%|| %||)", get_ins_name(cmd.ins), int(cmd.arg));
		return o;
	}
Exemplo n.º 30
0
void SoundRecorder::init(const char* audioSource,const SoundDataFormat& sFormat,const char* outputFileName)
	{
	/* Store and sanify the sound data format: */
	format.mSampleRate=double(sFormat.framesPerSecond);
	format.mFormatID=kAudioFormatLinearPCM;
	format.mFormatFlags=0x0;
	format.mBitsPerChannel=sFormat.bitsPerSample>8?(sFormat.bitsPerSample+7)&~0x7:8;
	format.mChannelsPerFrame=sFormat.samplesPerFrame>=1?sFormat.samplesPerFrame:1;
	format.mBytesPerFrame=format.mChannelsPerFrame*(format.mBitsPerChannel/8);
	format.mFramesPerPacket=1;
	format.mBytesPerPacket=format.mFramesPerPacket*format.mBytesPerFrame;
	
	/* Determine the output file format from the file name extension: */
	AudioFileTypeID audioFileType=kAudioFileWAVEType; // Not really a default; just to make compiler happy
	const char* ext=Misc::getExtension(outputFileName);
	if(*ext=='\0'||strcasecmp(ext,".aiff")==0)
		{
		/* Adjust the sound data format for AIFF files: */
		audioFileType=kAudioFileAIFFType;
		format.mFormatFlags=kLinearPCMFormatFlagIsBigEndian|kLinearPCMFormatFlagIsSignedInteger|kLinearPCMFormatFlagIsPacked;
		}
	else if(strcasecmp(ext,".wav")==0)
		{
		/* Adjust the sound data format for WAV files: */
		audioFileType=kAudioFileWAVEType;
		format.mFormatFlags=kLinearPCMFormatFlagIsPacked;
		if(format.mBitsPerChannel>8)
			format.mFormatFlags|=kLinearPCMFormatFlagIsSignedInteger;
		}
	else
		Misc::throwStdErr("SoundRecorder::SoundRecorder: Output file name %s has unrecognized extension",outputFileName);
	
	/* Create the recording audio queue: */
	if(AudioQueueNewInput(&format,handleInputBufferWrapper,this,0,kCFRunLoopCommonModes,0,&queue)!=noErr)
		Misc::throwStdErr("SoundRecorder::SoundRecorder: Error while creating audio queue");
	
	/* Retrieve the fully specified audio data format from the audio queue: */
	UInt32 formatSize=sizeof(format);
	if(AudioQueueGetProperty(queue,kAudioConverterCurrentOutputStreamDescription,&format,&formatSize)!=noErr)
		{
		AudioQueueDispose(queue,true);
		Misc::throwStdErr("SoundRecorder::SoundRecorder: Error while retrieving audio queue sound format");
		}
	
	/* Open the target audio file: */
	CFURLRef audioFileURL=CFURLCreateFromFileSystemRepresentation(0,reinterpret_cast<const UInt8*>(outputFileName),strlen(outputFileName),false);
	if(AudioFileCreateWithURL(audioFileURL,audioFileType,&format,kAudioFileFlags_EraseFile,&audioFile)!=noErr)
		{
		AudioQueueDispose(queue,true);
		CFRelease(audioFileURL);
		Misc::throwStdErr("SoundRecorder::SoundRecorder: Error while opening output file %s",outputFileName);
		}
	CFRelease(audioFileURL);
	
	/* Calculate an appropriate buffer size and allocate the sound buffers: */
	int maxPacketSize=format.mBytesPerPacket;
	if(maxPacketSize==0) // Must be a variable bit rate sound format
		{
		/* Query the expected maximum packet size from the audio queue: */
		UInt32 maxVBRPacketSize=sizeof(maxPacketSize);
		if(AudioQueueGetProperty(queue,kAudioConverterPropertyMaximumOutputPacketSize,&maxPacketSize,&maxVBRPacketSize)!=noErr)
			{
			AudioQueueDispose(queue,true);
			AudioFileClose(audioFile);
			Misc::throwStdErr("SoundRecorder::SoundRecorder: Error while calcuating sample buffer size");
			}
		}
	
	/* Calculate an appropriate buffer size based on the given duration: */
	int numPackets=int(floor(double(format.mSampleRate)*0.25+0.5));
	bufferSize=UInt32(numPackets*maxPacketSize);
	
	/* Create the sample buffers: */
	for(int i=0;i<2;++i)
		{
		/* Create the sound buffer: */
		if(AudioQueueAllocateBuffer(queue,bufferSize,&buffers[i])!=noErr)
			{
			AudioQueueDispose(queue,true);
			AudioFileClose(audioFile);
			Misc::throwStdErr("SoundRecorder::SoundRecorder: Error while allocating sample buffer %d",i);
			}
		
		/* Add the buffer to the queue: */
		if(AudioQueueEnqueueBuffer(queue,buffers[i],0,0)!=noErr)
			{
			AudioQueueDispose(queue,true);
			AudioFileClose(audioFile);
			Misc::throwStdErr("SoundRecorder::SoundRecorder: Error while enqueuing sample buffer %d",i);
			}
		}
	}