void init(unsigned w, unsigned h) { ResourceMap resource; resource.addPath("Fonts",""); std::string fontPath = resource.getPath("Fonts")+"monaco11"; font.load(fontPath.c_str()); console.reserve(height/font.lineHeight()); width=w;height=h; objs.clear(); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 2000.0); glEnable(GL_DEPTH_TEST); glutIdleFunc (idle); glutDisplayFunc (draw); glutKeyboardFunc (keyboard); //adding here the mouse processing callbacks glutMotionFunc(processMouseActiveMotion); glutPassiveMotionFunc(processMousePassiveMotion); GLfloat mat_specular[] = { .5, .5, .5, 1.0 }; GLfloat mat_shininess[] = { 5.0 }; GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_SMOOTH); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position); Color3 colors [] = { Color3(255,0,0), Color3(0,255,0), Color3(0,0,255), Color3(255,255,0), Color3(0,255,255), Color3(255,0,255), Color3(255,255,255), }; int n = 1; for (unsigned i=0;i<n;i++) { size_t size; // size = objs.size(); // objs.push_back(Object()); // objs[size].p_ = DReal3(randnorm<dreal>(),randnorm<dreal>(),randnorm<dreal>()); // initModel(objs[objs.size()-1], icosa_vertex, icosa_indices,icosa_vertex_size,icosa_indices_size, colors[(i+5)%7],(7./n)); size = objs.size(); objs.push_back(Object()); // objs[size].p_ =0.8*DReal3(0.1+randnorm<dreal>(),0.1+randnorm<dreal>(),randnorm<dreal>()); //objs[size].p_ =0.5*DReal3(randnorm<dreal>(),randnorm<dreal>(),randnorm<dreal>()); objs[size].p_=Real3(0.5,0.,0.5)+0.1*Real3(randnorm<real>(),randnorm<real>(),randnorm<real>()); initModel(objs[objs.size()-1], bunny_vertex, bunny_indices,bunny_vertex_size,bunny_indices_size, colors[(i)%7],5/*(1./n)*/); // initModel(objs[objs.size()-1], bunnyh_vertex, bunnyh_indices,bunnyh_vertex_size,bunnyh_indices_size, colors[(i)%7],5/*(1./n)*/); } gettimeofday(&idleold, 0); transformCoords(); buildTree(objs,coltrees); colres.resize(coltrees.size()); for (unsigned i=0;i<coltrees.size();i++) { coltrees[i]->collideWithSegment(seg[0], seg[1], colres[i]); } }
float GraphicsContext::drawBidiText(const Font& font, const TextRun& run, const FloatPoint& point, Font::CustomFontNotReadyAction customFontNotReadyAction, BidiStatus* status, int length) #endif { if (paintingDisabled()) #if !PLATFORM(IOS) return; #else return 0; #endif BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver; #if !PLATFORM(IOS) bidiResolver.setStatus(BidiStatus(run.direction(), run.directionalOverride())); #else bidiResolver.setStatus(status ? *status : BidiStatus(run.direction(), run.directionalOverride())); #endif bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0)); // FIXME: This ownership should be reversed. We should pass BidiRunList // to BidiResolver in createBidiRunsForLine. BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs(); #if !PLATFORM(IOS) bidiResolver.createBidiRunsForLine(TextRunIterator(&run, run.length())); #else bidiResolver.createBidiRunsForLine(TextRunIterator(&run, length < 0 ? run.length() : length)); #endif if (!bidiRuns.runCount()) #if !PLATFORM(IOS) return; #else return 0; #endif FloatPoint currPoint = point; BidiCharacterRun* bidiRun = bidiRuns.firstRun(); while (bidiRun) { TextRun subrun = run.subRun(bidiRun->start(), bidiRun->stop() - bidiRun->start()); bool isRTL = bidiRun->level() % 2; subrun.setDirection(isRTL ? RTL : LTR); subrun.setDirectionalOverride(bidiRun->dirOverride(false)); #if !PLATFORM(IOS) font.drawText(this, subrun, currPoint, 0, -1, customFontNotReadyAction); bidiRun = bidiRun->next(); // FIXME: Have Font::drawText return the width of what it drew so that we don't have to re-measure here. if (bidiRun) currPoint.move(font.width(subrun), 0); #else float width = font.drawText(this, subrun, currPoint, 0, -1, customFontNotReadyAction); currPoint.move(width, 0); bidiRun = bidiRun->next(); #endif } #if PLATFORM(IOS) if (status) *status = bidiResolver.status(); #endif bidiRuns.deleteRuns(); #if PLATFORM(IOS) return currPoint.x() - static_cast<float>(point.x()); #endif }
void menu(RenderWindow &window) { Texture menuText1, menuText2, menuText3, menuBackground; menuBackground.loadFromFile("images/menu1.jpg"); menuText2.loadFromFile("images/cat.jpg"); Sprite menuLoad(menuText2); Sprite menuBg(menuBackground); bool isMenu = 1; int menuNum = 0; menuBg.setPosition(0,0); Font font; font.loadFromFile("Hamurz.ttf"); Text text("", font, 48); Text text2("", font, 48); Text text3("", font, 48); text.setString("New Game"); text2.setString("Load"); text3.setString("Exit"); text.setPosition(500,410); text2.setPosition(550,488); text3.setPosition(550,564); while(isMenu) { text.setColor(Color(254,150,121)); text2.setColor(Color(254,150,121)); text3.setColor(Color(254,150,121)); menuNum = 0; window.clear(Color(129,181,221)); if(IntRect(500,410,200,60).contains(Mouse::getPosition(window))) { text.setColor(Color(98,198,223)); menuNum = 1; } if(IntRect(550,488,200,60).contains(Mouse::getPosition(window))) { text2.setColor(Color(98,198,223)); menuNum = 2; } if(IntRect(500,564,200,60).contains(Mouse::getPosition(window))) { text3.setColor(Color(98,198,223)); menuNum = 3; } if(Mouse::isButtonPressed(Mouse::Left)) { if(menuNum == 2) { window.draw(menuLoad); window.display(); while(!Keyboard::isKeyPressed(Keyboard::Escape)) {;} } if(menuNum == 3) { window.close(); isMenu = false; } } window.draw(menuBg); window.draw(text); window.draw(text2); window.draw(text3); window.display(); } }
GlyphData SVGTextRunRenderingContext::glyphDataForCharacter(const Font& font, WidthIterator& iterator, UChar32 character, bool mirror, int currentCharacter, unsigned& advanceLength) { const SimpleFontData* primaryFont = font.primaryFont(); ASSERT(primaryFont); pair<GlyphData, GlyphPage*> pair = font.glyphDataAndPageForCharacter(character, mirror, AutoVariant); GlyphData glyphData = pair.first; // Check if we have the missing glyph data, in which case we can just return. GlyphData missingGlyphData = primaryFont->missingGlyphData(); if (glyphData.glyph == missingGlyphData.glyph && glyphData.fontData == missingGlyphData.fontData) { ASSERT(glyphData.fontData); return glyphData; } // Save data fromt he font fallback list because we may modify it later. Do this before the // potential change to glyphData.fontData below. FontGlyphs* glyph = font.glyphs(); ASSERT(glyph); FontGlyphs::GlyphPagesStateSaver glyphPagesSaver(*glyph); // Characters enclosed by an <altGlyph> element, may not be registered in the GlyphPage. const SimpleFontData* originalFontData = glyphData.fontData; if (glyphData.fontData && !glyphData.fontData->isSVGFont()) { auto& elementRenderer = renderer().isRenderElement() ? toRenderElement(renderer()) : *renderer().parent(); if (Element* parentRendererElement = elementRenderer.element()) { if (parentRendererElement->hasTagName(SVGNames::altGlyphTag)) glyphData.fontData = primaryFont; } } const SimpleFontData* fontData = glyphData.fontData; if (fontData) { if (!fontData->isSVGFont()) return glyphData; SVGFontElement* fontElement = 0; SVGFontFaceElement* fontFaceElement = 0; const SVGFontData* svgFontData = svgFontAndFontFaceElementForFontData(fontData, fontFaceElement, fontElement); if (!fontElement || !fontFaceElement) return glyphData; // If we got here, we're dealing with a glyph defined in a SVG Font. // The returned glyph by glyphDataAndPageForCharacter() is a glyph stored in the SVG Font glyph table. // This doesn't necessarily mean the glyph is suitable for rendering/measuring in this context, its // arabic-form/orientation/... may not match, we have to apply SVG Glyph selection to discover that. if (svgFontData->applySVGGlyphSelection(iterator, glyphData, mirror, currentCharacter, advanceLength)) return glyphData; } GlyphPage* page = pair.second; ASSERT(page); // No suitable glyph found that is compatible with the requirments (same language, arabic-form, orientation etc.) // Even though our GlyphPage contains an entry for eg. glyph "a", it's not compatible. So we have to temporarily // remove the glyph data information from the GlyphPage, and retry the lookup, which handles font fallbacks correctly. page->setGlyphDataForCharacter(character, 0, 0); // Assure that the font fallback glyph selection worked, aka. the fallbackGlyphData font data is not the same as before. GlyphData fallbackGlyphData = font.glyphDataForCharacter(character, mirror); ASSERT(fallbackGlyphData.fontData != fontData); // Restore original state of the SVG Font glyph table and the current font fallback list, // to assure the next lookup of the same glyph won't immediately return the fallback glyph. page->setGlyphDataForCharacter(character, glyphData.glyph, originalFontData); ASSERT(fallbackGlyphData.fontData); return fallbackGlyphData; }
static int generateComponents(TextRunComponents* components, const Font &font, const TextRun &run) { int letterSpacing = font.letterSpacing(); int wordSpacing = font.wordSpacing(); int padding = run.padding(); int numSpaces = 0; if (padding) { for (int i = 0; i < run.length(); i++) if (Font::treatAsSpace(run[i])) ++numSpaces; } int offset = 0; if (letterSpacing) { // need to draw every letter on it's own int start = 0; if (Font::treatAsSpace(run[0])) { int add = 0; if (numSpaces) { add = padding/numSpaces; padding -= add; --numSpaces; } components->append(TextRunComponent(1, font, offset)); offset += add + letterSpacing + components->last().m_width; start = 1; } for (int i = 1; i < run.length(); ++i) { uint ch = run[i]; if (isHighSurrogate(ch) && isLowSurrogate(run[i-1])) ch = surrogateToUcs4(ch, run[i-1]); if (isLowSurrogate(ch) || category(ch) == Mark_NonSpacing) continue; if (Font::treatAsSpace(run[i])) { int add = 0; if (i - start > 0) { components->append(TextRunComponent(run.characters() + start, i - start, run, font, offset)); offset += components->last().m_width + letterSpacing; } if (numSpaces) { add = padding/numSpaces; padding -= add; --numSpaces; } components->append(TextRunComponent(1, font, offset)); offset += wordSpacing + add + components->last().m_width + letterSpacing; start = i + 1; continue; } if (i - start > 0) { components->append(TextRunComponent(run.characters() + start, i - start, run, font, offset)); offset += components->last().m_width + letterSpacing; } start = i; } if (run.length() - start > 0) { components->append(TextRunComponent(run.characters() + start, run.length() - start, run, font, offset)); offset += components->last().m_width; } offset += letterSpacing; } else { int start = 0; for (int i = 0; i < run.length(); ++i) { if (Font::treatAsSpace(run[i])) { if (i - start > 0) { components->append(TextRunComponent(run.characters() + start, i - start, run, font, offset)); offset += components->last().m_width; } int add = 0; if (numSpaces) { add = padding/numSpaces; padding -= add; --numSpaces; } components->append(TextRunComponent(1, font, offset)); offset += add + components->last().m_width; if (i) offset += wordSpacing; start = i + 1; } } if (run.length() - start > 0) { components->append(TextRunComponent(run.characters() + start, run.length() - start, run, font, offset)); offset += components->last().m_width; } } return offset; }
static inline float thicknessForDecoration(TextDecoration, const Font& font) { // FIXME: For SVG Fonts we need to use the attributes defined in the <font-face> if specified. // Compatible with Batik/Opera return font.size() / 20.0f; }
bool Application::RenderScene() { GT.NewFrame(); glClear(GL_DEPTH_BUFFER_BIT); // Очистка буфера глубины Cam.Look(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // РИСОВАНИЕ glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); rm.SELECT_Mesh("someMesh")->Render(); glTranslated(0,0,-2); //rm.SELECT_Mesh("someMesh")->Render(); glTranslated(0,0,-2); //rm.SELECT_Mesh("someMesh")->Render(); //rm.SELECT_Mesh(0)->Render(); //PS.DRAW(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // Рисование осей координат :) // Ось X glPushAttrib(GL_DEPTH_BUFFER_BIT|GL_ENABLE_BIT|GL_CURRENT_BIT); // Сохранение настроек glDisable(GL_DEPTH_TEST); glPushMatrix(); glScaled(0.2,0.2,0.2); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glLineWidth(4.0); glColor3d(0.0,1.0,0.0); glBegin(GL_LINES); { glVertex3d( 0.00, 0.00, 0.00); glVertex3d( 4.00, 0.00, 0.00); glVertex3d( 4.00, 0.00, 0.00); glVertex3d( 3.50, 0.00, 0.25); glVertex3d( 3.50, 0.00, -0.25); glVertex3d( 4.00, 0.00, 0.00); glVertex3d( 4.00, 0.00, 0.00); glVertex3d( 3.50, 0.25, 0.00); glVertex3d( 3.50,-0.25, 0.00); glVertex3d( 4.00, 0.00, 0.00); } glEnd(); // Ось Y glColor3d(0.0,0.0,1.0); glBegin(GL_LINES); { glVertex3d( 0.00, 0.00, 0.00); glVertex3d( 0.00, 4.00, 0.00); glVertex3d( 0.00, 4.00, 0.00); glVertex3d( 0.00, 3.50, 0.25); glVertex3d( 0.00, 3.50,-0.25); glVertex3d( 0.00, 4.00, 0.00); glVertex3d( 0.00, 4.00, 0.00); glVertex3d( 0.25, 3.50, 0.00); glVertex3d(-0.25, 3.50, 0.00); glVertex3d( 0.00, 4.00, 0.00); } glEnd(); glColor3d(1.0,0.0,0.0); glBegin(GL_LINES); { glVertex3d( 0.00, 0.00, 0.00); glVertex3d( 0.00, 0.00, 4.00); glVertex3d( 0.00, 0.00, 4.00); glVertex3d( 0.00, 0.25, 3.50); glVertex3d( 0.00,-0.25, 3.50); glVertex3d( 0.00, 0.00, 4.00); glVertex3d( 0.00, 0.00, 4.00); glVertex3d( 0.25, 0.00, 3.50); glVertex3d(-0.25, 0.00, 3.50); glVertex3d( 0.00, 0.00, 4.00); } glEnd(); glPopMatrix(); glPopAttrib(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // ТЕКСТ // TODO: удалить енто после полной отладки текста if (TextBenchmark) { Font * Cour = rm.SELECT_Font("Courier"); rm.SELECT_Font("Console")->SetStyle(Text::left,Text::top,1.0); rm.SELECT_Font("Console")->SetColor(0.0f,0.0f,0.0f,1.0f); for (int i = 0 ; i < 40 ; i++ ) { for (int j = 0 ; j < 8 ; j++ ) { Cour->Print((j)/8.0,i/40.0,"FPS:%4.1f",GT.GetFPS()); } } } else { if (Globals.EFl.show_stat) { PFont uif = rm.SELECT_Font("Console"); uif->SetStyle(Text::left,Text::top,1.0); uif->SetColor(0.0f,0.0f,0.0f,1.0f); uif->Print(0.0,0.0, "Current position is (%5.1f,%5.1f,%5.1f)",Cam.Position.d.c.x,Cam.Position.d.c.y,Cam.Position.d.c.z); uif->Print(0.0f,0.025,"FPS: %5.1f",GT.GetFPS()); uif->Print(0.0f,0.05,"CPU speed is %d",SysInfo.cpu.speed); // rm.SELECT_Font("Console")->Print(0.0f,0.075,"Cursor at %d",CCons.cursor); // rm.SELECT_Font("Console")->Print(0.0f,0.1,"Chars in string %d",CCons.chars); char str[512] = "Buttons pressed : "; for (WPARAM i=0;i<256;i++) { if (Input::I->get(i)) sprintf(str,"%s %s",str,Input::I->getSN(i));} uif->Print(0.0f,0.975,"%s ",str); memset(str,0,sizeof(str)); strcpy(str,"Buttons pressed : "); for (WPARAM i=0;i<256;i++) { if (Input::I->get(i)) sprintf(str,"%s %d",str,i);} uif->Print(0.0f,0.95,"%s ",str); uif->Print(0.0f,0.925,"Wheel shift: %d ",Input::I->wheel); /*uif->SetStyle(Text::left,Text::top,1.0); uif->SetColor(0.0f,0.0f,0.0f,1.0f); uif->Print(0.0,0.075,"Состояние ветра - %d",PS.windActive); uif->Print(0.0,0.1, "Скорость ветра - %5.1f,%5.1f,%5.1f",PS.wind.d.c.x,PS.wind.d.c.y,PS.wind.d.c.z); uif->Print(0.0,0.125, "Гравитация - %5.1f,%5.1f,%5.1f",PS.grav.d.c.x,PS.grav.d.c.y,PS.grav.d.c.z);*/ uif->SetStyle(Text::right,Text::top,1.0); uif->Print(0.95,0.0,"Количество материалов - %d",rm.SELECT_Mesh("someMesh")->iSurfaces); meshPointer sm =rm.SELECT_Mesh("someMesh"); for (WORD i = 0 ; i < rm.SELECT_Mesh("someMesh")->iSurfaces ; i++ ) uif->Print(1.0,0.025*(i+1), "#%02d \"% 20s\" - (%3.2f,%3.2f,%3.2f) %3.2f",i, sm->SurfList[i].name.c_str(), sm->SurfList[i].Diffuse.d.c.r, sm->SurfList[i].Diffuse.d.c.g, sm->SurfList[i].Diffuse.d.c.b, sm->SurfList[i].color.d.c.a); //uif->Print(0.95,0.5,"Информация о модели:"); //uif->Print(0.95,0.5,"",sm->); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // Интерфейс пользователя // NVLogo.render_logo(); #ifdef ENABLE_TEXTURE_RENDERING if (Input::I->process('T')) { RendTex.CopyBackbufferToTexture(); RendTex.Save(); } #endif return FJC_NO_ERROR; };
/// Writes ending block of LaTeX needed to close use of this font // Returns number of chars written // This one corresponds to latexWriteStartChanges(). (Asger) int Font::latexWriteEndChanges(otexstream & os, BufferParams const & bparams, OutputParams const & runparams, Font const & base, Font const & next, bool const & closeLanguage) const { int count = 0; bool env = false; // reduce the current font to changes against the base // font (of the layout). We use a temporary for this to // avoid changing this font instance, as that would break FontInfo f = bits_; f.reduce(base.bits_); if (f.family() != INHERIT_FAMILY) { os << '}'; ++count; env = true; // Size change need not bother about closing env. } if (f.series() != INHERIT_SERIES) { os << '}'; ++count; env = true; // Size change need not bother about closing env. } if (f.shape() != INHERIT_SHAPE) { os << '}'; ++count; env = true; // Size change need not bother about closing env. } if (f.color() != Color_inherit && f.color() != Color_ignore) { os << '}'; ++count; env = true; // Size change need not bother about closing env. } if (f.emph() == FONT_ON) { os << '}'; ++count; env = true; // Size change need not bother about closing env. } if (f.underbar() == FONT_ON) { os << '}'; ++count; runparams.inulemcmd = false; env = true; // Size change need not bother about closing env. } if (f.strikeout() == FONT_ON) { os << '}'; ++count; runparams.inulemcmd = false; env = true; // Size change need not bother about closing env. } if (f.uuline() == FONT_ON) { os << '}'; ++count; runparams.inulemcmd = false; env = true; // Size change need not bother about closing env. } if (f.uwave() == FONT_ON) { os << '}'; ++count; runparams.inulemcmd = false; env = true; // Size change need not bother about closing env. } if (f.noun() == FONT_ON) { os << '}'; ++count; env = true; // Size change need not bother about closing env. } if (f.size() != FONT_SIZE_INHERIT) { // We only have to close if only size changed if (!env) { os << '}'; ++count; } os << '}'; ++count; } // When the current language is Hebrew, Arabic, or Farsi // the numbers are written Left-to-Right. ArabTeX package // reorders the number automatically but the packages used // for Hebrew and Farsi (Arabi) do not. if (bits_.number() == FONT_ON && next.fontInfo().number() != FONT_ON && (language()->lang() == "hebrew" || language()->lang() == "farsi" || language()->lang() == "arabic_arabi")) { os << "\\endL}"; count += 6; } if (open_encoding_) { // We need to close the encoding even if it does not change // to do correct environment nesting Encoding const * const ascii = encodings.fromLyXName("ascii"); pair<bool, int> const c = switchEncoding(os.os(), bparams, runparams, *ascii); LASSERT(c.first, /**/); count += c.second; runparams.encoding = ascii; open_encoding_ = false; } if (closeLanguage && language() != base.language() && language() != next.language() && language()->encoding()->package() != Encoding::CJK) { os << '}'; ++count; } return count; }
void FullscreenVideoController::draw() { OwnPtr<HDC> bitmapDC = adoptPtr(CreateCompatibleDC(HWndDC(m_hudWindow))); HGDIOBJ oldBitmap = SelectObject(bitmapDC.get(), m_bitmap.get()); GraphicsContext context(bitmapDC.get(), true); context.save(); // Draw the background IntSize outerRadius(borderRadius, borderRadius); IntRect outerRect(0, 0, windowWidth, windowHeight); IntSize innerRadius(borderRadius - borderThickness, borderRadius - borderThickness); IntRect innerRect(borderThickness, borderThickness, windowWidth - borderThickness * 2, windowHeight - borderThickness * 2); context.fillRoundedRect(outerRect, outerRadius, outerRadius, outerRadius, outerRadius, Color(borderColor), ColorSpaceDeviceRGB); context.setCompositeOperation(CompositeCopy); context.fillRoundedRect(innerRect, innerRadius, innerRadius, innerRadius, innerRadius, Color(backgroundColor), ColorSpaceDeviceRGB); // Draw the widgets m_playPauseButton.draw(context); m_volumeUpButton.draw(context); m_volumeSliderButton.draw(context); m_volumeDownButton.draw(context); m_timeSliderButton.draw(context); m_exitFullscreenButton.draw(context); m_volumeSlider.draw(context); m_timeSlider.draw(context); // Draw the text strings FontDescription desc; NONCLIENTMETRICS metrics; metrics.cbSize = sizeof(metrics); SystemParametersInfo(SPI_GETNONCLIENTMETRICS, metrics.cbSize, &metrics, 0); FontFamily family; family.setFamily(metrics.lfSmCaptionFont.lfFaceName); desc.setFamily(family); desc.setComputedSize(textSize); Font font = Font(desc, 0, 0); font.update(0); String s; // The y positioning of these two text strings is tricky because they are so small. They // are currently positioned relative to the center of the slider and then down the font // height / 4 (which is actually half of font height /2), which positions the center of // the text at the center of the slider. // Left string s = timeToString(currentTime()); int fontHeight = font.fontMetrics().height(); TextRun leftText(s); context.setFillColor(Color(textColor), ColorSpaceDeviceRGB); context.drawText(font, leftText, IntPoint(windowWidth / 2 - timeSliderWidth / 2 - margin - font.width(leftText), windowHeight - margin - sliderHeight / 2 + fontHeight / 4)); // Right string s = timeToString(currentTime() - duration()); TextRun rightText(s); context.setFillColor(Color(textColor), ColorSpaceDeviceRGB); context.drawText(font, rightText, IntPoint(windowWidth / 2 + timeSliderWidth / 2 + margin, windowHeight - margin - sliderHeight / 2 + fontHeight / 4)); // Copy to the window BLENDFUNCTION blendFunction = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA}; SIZE size = { windowWidth, windowHeight }; POINT sourcePoint = {0, 0}; POINT destPoint = { m_hudPosition.x(), m_hudPosition.y() }; BOOL result = UpdateLayeredWindow(m_hudWindow, 0, &destPoint, &size, bitmapDC.get(), &sourcePoint, 0, &blendFunction, ULW_ALPHA); context.restore(); ::SelectObject(bitmapDC.get(), oldBitmap); }
/// Writes the changes from this font to orgfont in .lyx format in file void Font::lyxWriteChanges(Font const & orgfont, ostream & os) const { os << "\n"; if (orgfont.fontInfo().family() != bits_.family()) os << "\\family " << LyXFamilyNames[bits_.family()] << "\n"; if (orgfont.fontInfo().series() != bits_.series()) os << "\\series " << LyXSeriesNames[bits_.series()] << "\n"; if (orgfont.fontInfo().shape() != bits_.shape()) os << "\\shape " << LyXShapeNames[bits_.shape()] << "\n"; if (orgfont.fontInfo().size() != bits_.size()) os << "\\size " << LyXSizeNames[bits_.size()] << "\n"; if (orgfont.fontInfo().emph() != bits_.emph()) os << "\\emph " << LyXMiscNames[bits_.emph()] << "\n"; if (orgfont.fontInfo().number() != bits_.number()) os << "\\numeric " << LyXMiscNames[bits_.number()] << "\n"; if (orgfont.fontInfo().underbar() != bits_.underbar()) { // This is only for backwards compatibility switch (bits_.underbar()) { case FONT_OFF: os << "\\bar no\n"; break; case FONT_ON: os << "\\bar under\n"; break; case FONT_TOGGLE: lyxerr << "Font::lyxWriteFontChanges: " "FONT_TOGGLE should not appear here!" << endl; break; case FONT_INHERIT: os << "\\bar default\n"; break; case FONT_IGNORE: lyxerr << "Font::lyxWriteFontChanges: " "IGNORE should not appear here!" << endl; break; } } if (orgfont.fontInfo().strikeout() != bits_.strikeout()) { os << "\\strikeout " << LyXMiscNames[bits_.strikeout()] << "\n"; } if (orgfont.fontInfo().uuline() != bits_.uuline()) { os << "\\uuline " << LyXMiscNames[bits_.uuline()] << "\n"; } if (orgfont.fontInfo().uwave() != bits_.uwave()) { os << "\\uwave " << LyXMiscNames[bits_.uwave()] << "\n"; } if (orgfont.fontInfo().noun() != bits_.noun()) { os << "\\noun " << LyXMiscNames[bits_.noun()] << "\n"; } if (orgfont.fontInfo().color() != bits_.color()) os << "\\color " << lcolor.getLyXName(bits_.color()) << '\n'; // FIXME: uncomment this when we support background. //if (orgfont.fontInfo().background() != bits_.background()) // os << "\\color " << lcolor.getLyXName(bits_.background()) << '\n'; if (orgfont.language() != language() && language() != latex_language) { if (language()) os << "\\lang " << language()->lang() << "\n"; else os << "\\lang unknown\n"; } }
/// Writes the head of the LaTeX needed to impose this font // Returns number of chars written. int Font::latexWriteStartChanges(odocstream & os, BufferParams const & bparams, OutputParams const & runparams, Font const & base, Font const & prev) const { bool env = false; int count = 0; // polyglossia or babel? if (runparams.use_polyglossia && language()->lang() != base.language()->lang() && language() != prev.language()) { if (!language()->polyglossia().empty()) { string tmp = "\\text" + language()->polyglossia(); if (!language()->polyglossiaOpts().empty()) tmp += "[" + language()->polyglossiaOpts() + "]"; tmp += "{"; os << from_ascii(tmp); count += tmp.length(); } } else if (language()->babel() != base.language()->babel() && language() != prev.language()) { if (language()->lang() == "farsi") { os << "\\textFR{"; count += 8; } else if (!isRightToLeft() && base.language()->lang() == "farsi") { os << "\\textLR{"; count += 8; } else if (language()->lang() == "arabic_arabi") { os << "\\textAR{"; count += 8; } else if (!isRightToLeft() && base.language()->lang() == "arabic_arabi") { os << "\\textLR{"; count += 8; // currently the remaining RTL languages are arabic_arabtex and hebrew } else if (isRightToLeft() != prev.isRightToLeft()) { if (isRightToLeft()) { os << "\\R{"; count += 3; } else { os << "\\L{"; count += 3; } } else if (!language()->babel().empty()) { string const tmp = subst(lyxrc.language_command_local, "$$lang", language()->babel()); os << from_ascii(tmp); count += tmp.length(); } else { os << '{'; count += 1; } } if (language()->encoding()->package() == Encoding::CJK) { pair<bool, int> const c = switchEncoding(os, bparams, runparams, *(language()->encoding())); if (c.first) { open_encoding_ = true; count += c.second; runparams.encoding = language()->encoding(); } } // If the current language is Hebrew, Arabic, or Farsi // the numbers are written Left-to-Right. ArabTeX package // reorders the number automatically but the packages used // for Hebrew and Farsi (Arabi) do not. if (bits_.number() == FONT_ON && prev.fontInfo().number() != FONT_ON && (language()->lang() == "hebrew" || language()->lang() == "farsi" || language()->lang() == "arabic_arabi")) { os << "{\\beginL "; count += 9; } FontInfo f = bits_; f.reduce(base.bits_); if (f.family() != INHERIT_FAMILY) { os << '\\' << LaTeXFamilyNames[f.family()] << '{'; count += strlen(LaTeXFamilyNames[f.family()]) + 2; env = true; //We have opened a new environment } if (f.series() != INHERIT_SERIES) { os << '\\' << LaTeXSeriesNames[f.series()] << '{'; count += strlen(LaTeXSeriesNames[f.series()]) + 2; env = true; //We have opened a new environment } if (f.shape() != INHERIT_SHAPE) { os << '\\' << LaTeXShapeNames[f.shape()] << '{'; count += strlen(LaTeXShapeNames[f.shape()]) + 2; env = true; //We have opened a new environment } if (f.color() != Color_inherit && f.color() != Color_ignore) { os << "\\textcolor{" << from_ascii(lcolor.getLaTeXName(f.color())) << "}{"; count += lcolor.getLaTeXName(f.color()).length() + 13; env = true; //We have opened a new environment } // FIXME: uncomment this when we support background. /* if (f.background() != Color_inherit && f.background() != Color_ignore) { os << "\\textcolor{" << from_ascii(lcolor.getLaTeXName(f.background())) << "}{"; count += lcolor.getLaTeXName(f.background()).length() + 13; env = true; //We have opened a new environment } */ if (f.emph() == FONT_ON) { os << "\\emph{"; count += 6; env = true; //We have opened a new environment } if (f.underbar() == FONT_ON) { os << "\\uline{"; count += 10; runparams.inulemcmd = true; env = true; //We have opened a new environment } if (f.strikeout() == FONT_ON) { os << "\\sout{"; count += 9; runparams.inulemcmd = true; env = true; //We have opened a new environment } if (f.uuline() == FONT_ON) { os << "\\uuline{"; count += 11; runparams.inulemcmd = true; env = true; //We have opened a new environment } if (f.uwave() == FONT_ON) { os << "\\uwave{"; count += 10; runparams.inulemcmd = true; env = true; //We have opened a new environment } // \noun{} is a LyX special macro if (f.noun() == FONT_ON) { os << "\\noun{"; count += 6; env = true; //We have opened a new environment } if (f.size() != FONT_SIZE_INHERIT) { // If we didn't open an environment above, we open one here if (!env) { os << '{'; ++count; } os << '\\' << LaTeXSizeNames[f.size()] << '{'; count += strlen(LaTeXSizeNames[f.size()]) + 2; } return count; }
int main() { RenderWindow window(VideoMode(500, 500), "Tetris"); srand(time(NULL)); if(!cube.loadFromFile("cube.png")) return EXIT_FAILURE; if(!frame.loadFromFile("frame.png")) return EXIT_FAILURE; s_frame.setTexture(frame); init_cube(); generate_cube(getrand()); bool pause = false; bool over = false; while (window.isOpen()) { int condition = check(over); if(!pause && !over){ if(cube_clock.getElapsedTime().asSeconds() > 0.9f) { if(condition == 0){ drop(); cout<< "sstart: " << start.first << " " << start.second << endl; for(int i=0; i<4; i++) printf("cube:%d %d \n",current[i].first,current[i].second); for(int i=3 ; i<=22; i++){ for(int j=0; j<10; j++){ // if(data[j][i] == -1) // printf("%d",random); // else printf("%d",data[j][i]); } printf("\n"); } puts("==========="); cube_clock.restart(); } else if(condition == 1){ end_line(); } } } //Get Event。 Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if(event.type == Event::KeyPressed) { if(Keyboard::isKeyPressed(Keyboard::Left)){ operate_cube(LEFT); } else if(Keyboard::isKeyPressed(Keyboard::Right)){ operate_cube(RIGHT); } else if(Keyboard::isKeyPressed(Keyboard::Up)){ if(random != 3) operate_cube(RR); } else if(Keyboard::isKeyPressed(Keyboard::Down)){ if(condition == 0) drop(); } else if(Keyboard::isKeyPressed(Keyboard::Space)){ movebase(); end_line(); } else if(Keyboard::isKeyPressed(Keyboard::C)){ printf("%d\n",holden); if(!holden){ makehold(); holden = true; } } if(Keyboard::isKeyPressed(Keyboard::P)) pause = !pause; } } update_cube(); Font font; if (!font.loadFromFile("brightfuture.ttf")) return EXIT_FAILURE; score[0] = Text("Line:",font, 40); score[0].setPosition(20,350); score[0].setColor(Color(255,88,0,255)); stringstream ss; ss << line; string convert_str; ss >> convert_str; score[1] = Text(convert_str,font, 40); score[1].setPosition(40,385); score[1].setColor(Color(255,88,0,255)); showNext(); window.clear(); window.draw(s_frame); for(int i=0; i<8; i++) for(int j=0; j<4; j++) window.draw(show[i][j]); window.draw(score[0]); window.draw(score[1]); for(int i=0; i<200; i++) window.draw(s_cube[i]); window.display(); } return 0; }
void Graphics::Uninitialize() { if (s_moduleReferenceCounter != 1) { // The module is still in use, or can not be uninitialized if (s_moduleReferenceCounter > 1) s_moduleReferenceCounter--; return; } // Free of module s_moduleReferenceCounter = 0; // Free of atlas if it is ours std::shared_ptr<AbstractAtlas> defaultAtlas = Font::GetDefaultAtlas(); if (defaultAtlas && defaultAtlas->GetStorage() == DataStorage_Hardware) { Font::SetDefaultAtlas(nullptr); // The default police can make live one hardware atlas after the free of a module (which could be problematic) // So, if the default police use a hardware atlas, we stole it. // I don't like this solution, but I don't have any better if (!defaultAtlas.unique()) { // Still at least one police use the atlas Font* defaultFont = Font::GetDefault(); defaultFont->SetAtlas(nullptr); if (!defaultAtlas.unique()) { // Still not the only one to own it ? Then crap. NazaraWarning("Default font atlas uses hardware storage and is still used"); } } } defaultAtlas.reset(); // Textures TextureLibrary::Unregister("White2D"); TextureLibrary::Unregister("WhiteCubemap"); // Loaders Loaders::UnregisterMesh(); Loaders::UnregisterTexture(); // Renderables ParticleRenderer::Uninitialize(); ParticleGenerator::Uninitialize(); ParticleDeclaration::Uninitialize(); ParticleController::Uninitialize(); SkyboxBackground::Uninitialize(); Sprite::Uninitialize(); TileMap::Uninitialize(); // Render techniques DeferredRenderTechnique::Uninitialize(); DepthRenderTechnique::Uninitialize(); ForwardRenderTechnique::Uninitialize(); SkinningManager::Uninitialize(); // Materials Material::Uninitialize(); MaterialPipeline::Uninitialize(); NazaraNotice("Uninitialized: Graphics module"); // Free of dependances Renderer::Uninitialize(); }
namespace Collide { std::vector<string> console; int width,height; Font font; std::vector<Object> objs; std::vector<AABBTreePoly*> coltrees; Vec3f seg[2] = { Vec3f(0,0,0) , Vec3f(1,1,1) }; std::vector<ozcollide::AABBTreePoly::SegmentColResult> colres; int rotateX=0; int rotateY=0; dreal rotModelX = 0; dreal level = 0.1; dreal offY= 0; dreal scale=1.; bool multiple = true; Int2 deltaMousePos; Int2 oldMousePos; bool showGeom = true; bool showWire = true; bool showNormals = false; struct timeval start, end, idleold, idlenew; float lapse; float average0,average1,average2; void initModel(Object& obj, float data[][3], unsigned indices[][3], unsigned vsize, unsigned fsize, const Color3& color,real scale) { obj.colors_.reserve(vsize); for (unsigned i=0;i<vsize;i++) { obj.colors_.push_back(color); } obj.tvx_.resize(vsize); obj.vx_.reserve(vsize); for (unsigned i=0;i<vsize;i++) { obj.vx_.push_back(scale*Real3(data[i][0],data[i][1],data[i][2])); } obj.faces_.reserve(fsize); for (unsigned i=0;i<fsize;++i) { obj.faces_.push_back(Int3(indices[i][0],indices[i][1],indices[i][2])); } obj.tnormals_.resize(vsize); obj.normals_.reserve(vsize); for (unsigned i = 0; i < vsize; i++) { obj.normals_[i]+=Real3(0.); } for (unsigned i = 0; i < fsize; i++) { unsigned ia=indices[i][0]; unsigned ib=indices[i][1]; unsigned ic=indices[i][2]; Real3 a = obj.vx_[ia]; Real3 b = obj.vx_[ib]; Real3 c = obj.vx_[ic]; Real3 n = normalize( crossProd( b-a, c-a) ); obj.normals_[ia]+=n; obj.normals_[ib]+=n; obj.normals_[ic]+=n; } for (unsigned i = 0; i < vsize; i++) { obj.normals_[i]=normalize( obj.normals_[i] ); } } void transformCoords() { //rotModelX += lapse*0.001; for (unsigned i=0;i<objs.size();++i) { objs[i].rot_ = Rotation(rotModelX, Real3(0,1,0)); } for (unsigned i=0;i<objs.size();++i) { Matrix4 rmx = objs[i].rot_; SetTranslation(rmx,objs[i].p_+Real3(0,offY,0)); for (unsigned j=0;j<objs[i].vx_.size();++j) { objs[i].tvx_[j] =Matrix4Affine (rmx, objs[i].vx_[j]); objs[i].tnormals_[j] = Matrix4Rotate(rmx,objs[i].normals_[j]); } } } void buildTree(const std::vector<Object>& objs, std::vector<AABBTreePoly*>& coltrees) { AABBTreePolyBuilder builder; for (unsigned i=0;i<objs.size();i++) { std::vector<Polygon> polys; polys.resize(objs[i].faces_.size()); for (unsigned j=0;j<objs[i].faces_.size();j++) { polys[j].setIndicesMemory(3, const_cast<int*> (&objs[i].faces_[j][0])); } AABBTreePoly* coltree = builder.buildFromPolys( &polys[0], polys.size(), reinterpret_cast<const Vec3f *> (&objs[i].tvx_[0]), objs[i].tvx_.size()); coltrees.push_back(coltree); } } void testTextOverlay() { // text overlay glColor3ub(220,220,220); setOrthographicProjection(width,height); glPushMatrix(); glLoadIdentity(); glScalef(1,-1,1); font.preDrawString(); real lineFeed = 0; for (unsigned i=0;i<console.size();i++) { font.drawString(console[i],0,lineFeed-=font.lineHeight()); } font.posDrawString(); glPopMatrix(); resetPerspectiveProjection(); } void draw(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // glEnable(GL_DEPTH_TEST); //setOrthographicCubeProjection(1.f); glPushMatrix(); glLoadIdentity(); glRotatef(rotateX,1,0,0); glRotatef(-rotateY,0,1,0); glScalef(scale,scale,scale); glTranslatef(-0.5,-0.5,-0.5); console.push_back("Hello collisions"); glColor3ub(155,155,155); if (showWire) { //const size_t size = tris.size(); glBegin(GL_LINES); for (unsigned i=0;i<objs.size();i++) { for (unsigned j=0;j<objs[i].faces_.size();j++) { const Real3& a = objs[i].tvx_[objs[i].faces_[j][0]]; const Real3& b = objs[i].tvx_[objs[i].faces_[j][1]]; const Real3& c = objs[i].tvx_[objs[i].faces_[j][2]]; glVertex3fv(&a[0]); glVertex3fv(&b[0]); glVertex3fv(&b[0]); glVertex3fv(&c[0]); glVertex3fv(&c[0]); glVertex3fv(&a[0]); } if (showNormals) { glColor3ub(0,255,0); for (unsigned j=0;j<objs[i].tnormals_.size();j++) { const Real3& n = objs[i].tnormals_[j]; const Real3& v = objs[i].tvx_[j]; glVertex3fv(&v[0]); glVertex3fv(&(v+0.01*n)[0]); } } } glEnd(); } glColor3ub(255,0,0); // glBegin(GL_LINES); // if (true) { // glVertex3f(seg[0].x,seg[0].y,seg[0].z); // glVertex3f(seg[1].x,seg[1].y,seg[1].z); // // } // glEnd(); // // public: // Vector<const Polygon *> polys_; // Vector<int> users_; // Vec3f segmentPt0_; // Vec3f segmentPt1_; // }; glColor3ub(255,0,0); if (showGeom) { glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); // glEnable(GL_DEPTH_TEST); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); for(unsigned i=0;i<objs.size();i++) { glVertexPointer(3, GL_FLOAT, 0, &objs[i].tvx_[0]); glNormalPointer(GL_FLOAT, 0, &objs[i].tnormals_[0]); glColorPointer(3,GL_UNSIGNED_BYTE, 0, &objs[i].colors_[0]); glDrawElements( GL_TRIANGLES, objs[i].faces_.size()*3, GL_UNSIGNED_INT, &objs[i].faces_[0]); } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisable(GL_LIGHTING); // glDisable(GL_DEPTH_TEST); } glDisable(GL_DEPTH_TEST); glBegin(GL_LINES); for(unsigned i=0;i<objs.size();i++) { glColor3ub(0,255,0); for (unsigned j=0;j<12;j++) { BoxEdge e = coltrees[i]->getRootNode()->aabb.getEdge(j); Vec3f s = e.p0; Vec3f p = e.p1; glVertex3f(s.x,s.y,s.z); glVertex3f(p.x,p.y,p.z); } for (unsigned j=0;j<colres[i].polys_.size();j++) { const Real3& a = objs[i].tvx_[colres[i].polys_[j]->getIndex(0)]; const Real3& b = objs[i].tvx_[colres[i].polys_[j]->getIndex(1)]; const Real3& c = objs[i].tvx_[colres[i].polys_[j]->getIndex(2)]; glVertex3fv(&a[0]); glVertex3fv(&b[0]); glVertex3fv(&b[0]); glVertex3fv(&c[0]); glVertex3fv(&c[0]); glVertex3fv(&a[0]); } Vec3f s = colres[i].segmentPt0_; Vec3f p = colres[i].segmentPt1_; glVertex3f(s.x,s.y,s.z); glVertex3f(p.x,p.y,p.z); } glEnd(); glEnable(GL_DEPTH_TEST); drawCube(1.); drawAxis(0.01); // glDisable(GL_DEPTH_TEST); glPopMatrix(); testTextOverlay(); glutSwapBuffers(); } void idle(void) { console.clear(); gettimeofday(&idlenew, 0); lapse = (idlenew.tv_sec - idleold.tv_sec)* (1e03f) + (idlenew.tv_usec - idleold.tv_usec)*(1e-03f); idleold = idlenew; //transformCoords(); glutPostRedisplay(); } void keyboard(unsigned char key, int x, int y) { switch (key) { case 27: /* Escape Key */ exit(0); break; case 'x': rotateX++; break; case 'X': rotateX--; break; case 'y': rotateY++; break; case 'Y': rotateY--; break; case '+': for(unsigned i=0;i<objs.size();i++) { objs[i].p_[1]+=0.01; } // offY+=0.01; break; case '-': for(unsigned i=0;i<objs.size();i++) { objs[i].p_[1]-=0.01; } // offY-=0.01; break; case 'm': multiple =!multiple; break; case 'c': init(width,height); break; case 's': showGeom=!showGeom; break; case 'w': showWire=!showWire; break; case 'a': scale+=0.1; break; case 'A': scale-=0.1; break; case 'r': rotModelX+=0.1; break; default: break; } } void processMouseActiveMotion(int x, int y) { Int2 p(x,y); deltaMousePos = p - oldMousePos; rotateX += deltaMousePos[1]; rotateY -= deltaMousePos[0]; oldMousePos = p; } void processMousePassiveMotion(int x, int y) { Int2 p(x,y); deltaMousePos = p - oldMousePos; oldMousePos = p; } void init(unsigned w, unsigned h) { ResourceMap resource; resource.addPath("Fonts",""); std::string fontPath = resource.getPath("Fonts")+"monaco11"; font.load(fontPath.c_str()); console.reserve(height/font.lineHeight()); width=w;height=h; objs.clear(); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 2000.0); glEnable(GL_DEPTH_TEST); glutIdleFunc (idle); glutDisplayFunc (draw); glutKeyboardFunc (keyboard); //adding here the mouse processing callbacks glutMotionFunc(processMouseActiveMotion); glutPassiveMotionFunc(processMousePassiveMotion); GLfloat mat_specular[] = { .5, .5, .5, 1.0 }; GLfloat mat_shininess[] = { 5.0 }; GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_SMOOTH); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position); Color3 colors [] = { Color3(255,0,0), Color3(0,255,0), Color3(0,0,255), Color3(255,255,0), Color3(0,255,255), Color3(255,0,255), Color3(255,255,255), }; int n = 1; for (unsigned i=0;i<n;i++) { size_t size; // size = objs.size(); // objs.push_back(Object()); // objs[size].p_ = DReal3(randnorm<dreal>(),randnorm<dreal>(),randnorm<dreal>()); // initModel(objs[objs.size()-1], icosa_vertex, icosa_indices,icosa_vertex_size,icosa_indices_size, colors[(i+5)%7],(7./n)); size = objs.size(); objs.push_back(Object()); // objs[size].p_ =0.8*DReal3(0.1+randnorm<dreal>(),0.1+randnorm<dreal>(),randnorm<dreal>()); //objs[size].p_ =0.5*DReal3(randnorm<dreal>(),randnorm<dreal>(),randnorm<dreal>()); objs[size].p_=Real3(0.5,0.,0.5)+0.1*Real3(randnorm<real>(),randnorm<real>(),randnorm<real>()); initModel(objs[objs.size()-1], bunny_vertex, bunny_indices,bunny_vertex_size,bunny_indices_size, colors[(i)%7],5/*(1./n)*/); // initModel(objs[objs.size()-1], bunnyh_vertex, bunnyh_indices,bunnyh_vertex_size,bunnyh_indices_size, colors[(i)%7],5/*(1./n)*/); } gettimeofday(&idleold, 0); transformCoords(); buildTree(objs,coltrees); colres.resize(coltrees.size()); for (unsigned i=0;i<coltrees.size();i++) { coltrees[i]->collideWithSegment(seg[0], seg[1], colres[i]); } } } // namespace
TextParser::TextParser(const std::wstring &text, Font &font, int x, int y, int width, int height): tokenizer(text), font(font), spaceWidth(font.getWidth(L' ')), charHeight(font.getWidth(L'A')), offsetX(x), offsetY(y), pageWidth(width), pageHeight(height) {}
static short GetFontDefaultSize(const Font& f) { return f.GetFontData().mPointSize; }
int _wrap_Font_getLineHeight(lua_State * L) { Font * t = luax_checkfont(L, 1); lua_pushnumber(L, t->getLineHeight()); return 1; }
static short GetFontHeight(const Font& f) { return f.GetFontData().mHeight;// + f.GetFontData().mDescender+1; }
void CG_DrawWeaponSelect( void ) { int i, bits, count, smallIconSize, bigIconSize, holdX, x, y, pad, sideLeftIconCnt, sideRightIconCnt, sideMax, holdCount, iconCnt, yOffset = 0; qboolean drewConc = qfalse; // can't cycle when on a weapon if ( cg.predictedPlayerState.emplacedIndex ) cg.weaponSelectTime = 0; // Time is up for the HUD to display if ( (cg.weaponSelectTime + WEAPON_SELECT_TIME) < cg.time ) return; // don't display if dead if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) return; // showing weapon select clears pickup item display, but not the blend blob cg.itemPickupTime = 0; bits = cg.predictedPlayerState.stats[STAT_WEAPONS]; // count the number of weapons owned count = 0; // display this weapon that we don't actually "have" as unhighlighted until it's deselected // since it's selected we must increase the count to display the proper number of valid selectable weapons if ( !CG_WeaponSelectable( cg.weaponSelect ) && (cg.weaponSelect == WP_THERMAL || cg.weaponSelect == WP_TRIP_MINE) ) count++; for ( i = 1; i < WP_NUM_WEAPONS; i++ ) { if ( bits & (1 << i) ) { if ( CG_WeaponSelectable( i ) || (i != WP_THERMAL && i != WP_TRIP_MINE) ) count++; } } if ( !count ) // If no weapons, don't display return; sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one holdCount = count - 1; // -1 for the center icon if ( holdCount == 0 ) { // No icons to either side sideLeftIconCnt = 0; sideRightIconCnt = 0; } else if ( count > (2 * sideMax) ) { // Go to the max on each side sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; } else { // Less than max, so do the calc sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } if ( cg.weaponSelect == WP_CONCUSSION ) i = WP_FLECHETTE; else i = cg.weaponSelect - 1; if ( i < 1 ) i = LAST_USEABLE_WEAPON; smallIconSize = 40; bigIconSize = 80; pad = 12; x = (SCREEN_WIDTH / 2); y = 410; // Left side ICONS trap->R_SetColor( &colorTable[CT_WHITE] ); // Work backwards from current icon holdX = x - ((bigIconSize / 2) + pad + smallIconSize) * cgs.widthRatioCoef; drewConc = qfalse; for ( iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i-- ) { if ( i == WP_CONCUSSION ) i--; else if ( i == WP_FLECHETTE && !drewConc && cg.weaponSelect != WP_CONCUSSION ) i = WP_CONCUSSION; if ( i < 1 ) i = LAST_USEABLE_WEAPON; // Does he have this weapon? if ( !(bits & (1 << i)) ) { if ( i == WP_CONCUSSION ) { drewConc = qtrue; i = WP_ROCKET_LAUNCHER; } continue; } // Don't show thermal and tripmine when out of them if ( !CG_WeaponSelectable( i ) && (i == WP_THERMAL || i == WP_TRIP_MINE) ) continue; ++iconCnt; // Good icon if ( media.gfx.interface.weaponIcons[i] ) { CG_RegisterWeapon( i ); trap->R_SetColor( &colorTable[CT_WHITE] ); if ( !CG_WeaponCheck( i ) ) CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize * cgs.widthRatioCoef, smallIconSize, media.gfx.interface.weaponIconsInactive[i]); else CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize * cgs.widthRatioCoef, smallIconSize, media.gfx.interface.weaponIcons[i]); holdX -= (smallIconSize + pad) * cgs.widthRatioCoef; } if ( i == WP_CONCUSSION ) { drewConc = qtrue; i = WP_ROCKET_LAUNCHER; } } // Current Center Icon if ( media.gfx.interface.weaponIcons[cg.weaponSelect] ) { CG_RegisterWeapon( cg.weaponSelect ); trap->R_SetColor( &colorTable[CT_WHITE] ); if ( !CG_WeaponCheck( cg.weaponSelect ) ) CG_DrawPic(x - (bigIconSize / 2 * cgs.widthRatioCoef), (y - ((bigIconSize - smallIconSize) / 2)) + 10 + yOffset, bigIconSize * cgs.widthRatioCoef, bigIconSize, media.gfx.interface.weaponIconsInactive[cg.weaponSelect]); else CG_DrawPic(x - (bigIconSize / 2 * cgs.widthRatioCoef), (y - ((bigIconSize - smallIconSize) / 2)) + 10 + yOffset, bigIconSize * cgs.widthRatioCoef, bigIconSize, media.gfx.interface.weaponIcons[cg.weaponSelect]); } if ( cg.weaponSelect == WP_CONCUSSION ) i = WP_ROCKET_LAUNCHER; else i = cg.weaponSelect + 1; if ( i > LAST_USEABLE_WEAPON ) i = 1; // Right side ICONS // Work forwards from current icon holdX = x + ((bigIconSize / 2) + pad) * cgs.widthRatioCoef; for ( iconCnt = 1; iconCnt<(sideRightIconCnt + 1); i++ ) { if ( i == WP_CONCUSSION ) i++; else if ( i == WP_ROCKET_LAUNCHER && !drewConc && cg.weaponSelect != WP_CONCUSSION ) i = WP_CONCUSSION; if ( i > LAST_USEABLE_WEAPON ) i = 1; if ( !(bits & (1 << i)) ) { if ( i == WP_CONCUSSION ) { drewConc = qtrue; i = WP_FLECHETTE; } continue; } // Don't show thermal and tripmine when out of them if ( !CG_WeaponSelectable( i ) && (i == WP_THERMAL || i == WP_TRIP_MINE) ) continue; ++iconCnt; // Good icon if ( media.gfx.interface.weaponIcons[i] ) { CG_RegisterWeapon( i ); // No ammo for this weapon? trap->R_SetColor( &colorTable[CT_WHITE] ); if ( !CG_WeaponCheck( i ) ) CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize * cgs.widthRatioCoef, smallIconSize, media.gfx.interface.weaponIconsInactive[i]); else CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize * cgs.widthRatioCoef, smallIconSize, media.gfx.interface.weaponIcons[i]); holdX += (smallIconSize + pad); } if ( i == WP_CONCUSSION ) { drewConc = qtrue; i = WP_FLECHETTE; } } // draw the selected name if ( cg_weapons[cg.weaponSelect].item ) { vector4 textColor = { .875f, .718f, .121f, 1.0f }; char upperKey[1024]; Com_sprintf( upperKey, sizeof(upperKey), "SP_INGAME_%s", cg_weapons[cg.weaponSelect].item->classname ); Q_strupr( upperKey ); const char *s = nullptr; char text[1024]; if ( trap->SE_GetStringTextString( upperKey, text, sizeof(text) ) ) { s = text; } else { s = cg_weapons[cg.weaponSelect].item->classname; } const Font font( FONT_SMALL, 1.0f, false ); const float width = font.Width( s ); font.Paint( (SCREEN_WIDTH / 2) - (width / 2.0f), y + 45 + yOffset, s, &textColor, ITEM_TEXTSTYLE_SHADOWED ); } trap->R_SetColor( NULL ); }
bool StartGame(RenderWindow & window, Game & game) { Level lvl; lvl.LoadFromFile(GetLevelNumb(game)); Image image; Texture texture; if (!image.loadFromFile("images/lvl1.png")) cout << "Error loading image from file " << endl; image.createMaskFromColor(Color(0, 128, 0)); if (!texture.loadFromImage(image)) cout << "Error loading texture from image " << endl; Sprite heartSprite; heartSprite.setTexture(texture); heartSprite.setTextureRect(IntRect(395, 151, 54, 46)); heartSprite.setScale(0.3f, 0.3f); Sprite lifeSprite; lifeSprite.setTexture(texture); lifeSprite.setTextureRect(IntRect(457, 149, 29, 29)); lifeSprite.setScale(0.8f, 0.8f); Font font; font.loadFromFile("fonts/pixel.ttf"); Text text("", font, 25); game.graphic.statistic.heart = heartSprite; game.graphic.statistic.life = lifeSprite; game.graphic.text = text; game.isPause = true; game.restart = false; vector <Enemy*> enemies; std::vector<Object> e = lvl.GetObjects("easyEnemy"); for (Object i : e) enemies.push_back(new Enemy(texture, "easyEnemy", i.rect.left, i.rect.top, 53, 28)); e = lvl.GetObjects("flyEnemy"); for (Object i : e) enemies.push_back(new Enemy(texture, "flyEnemy", i.rect.left, i.rect.top, 38, 36)); if (lvl.IsExist("trap")) { e = lvl.GetObjects("trap"); for (Object i : e) enemies.push_back(new Enemy(texture, "trap", i.rect.left, i.rect.top, 32, 18)); } vector <Portal*> portals; vector <Bullet*> bullets; vector <Object> objects = lvl.GetAllObjects(); Clock clock; SoundBuffer shootBuffer; shootBuffer.loadFromFile("sound/shoot.wav"); Sound shoot(shootBuffer); SoundBuffer portalBuffer; portalBuffer.loadFromFile("sound/portal.wav"); Sound portal(portalBuffer); SoundBuffer teleportBuffer; teleportBuffer.loadFromFile("sound/teleport.wav"); Sound teleport(teleportBuffer); SoundBuffer damageBuffer; damageBuffer.loadFromFile("sound/damage.wav"); Sound damage(damageBuffer); SoundBuffer deathBuffer; deathBuffer.loadFromFile("sound/damage.wav"); Sound gameOver(deathBuffer); Music music; music.openFromFile("sound/musicGame.ogg"); music.play(); Object playerObject = lvl.GetObject("player"); Player player(texture, "Player1", playerObject.rect.left, playerObject.rect.top, 32, 32); player.health = game.health; player.heart = game.hearts; while (window.isOpen() && (!game.restart)) { float time = float(clock.getElapsedTime().asMicroseconds()); clock.restart(); time = time / 800; Event event; Vector2i pixelPos = Mouse::getPosition(window); Vector2f pos = window.mapPixelToCoords(pixelPos); while (window.pollEvent(event)) { if (event.type == sf::Event::Closed || (Keyboard::isKeyPressed(Keyboard::Escape) && game.isPause)) { window.close(); game.restart = false; } if (event.type == Event::MouseButtonPressed) { pos.y = float(player.teleportY); if ((event.key.code == Mouse::Left) && (player.doesOpenPortal)) { CreatePortal(portals, game, "blue", pos, texture); portal.play(); } else if (event.key.code == Mouse::Right && (player.doesOpenPortal)) { CreatePortal(portals, game, "yellow", pos, texture); portal.play(); } } if (player.isTeleporting) { TeleportPlayer(player, portals); teleport.play(); } if (Keyboard::isKeyPressed(Keyboard::Return)) { game.isPause = false; } if (Keyboard::isKeyPressed(Keyboard::P)) { game.isPause = true; } if (Keyboard::isKeyPressed(Keyboard::Tab) && game.isPause) { game.restart = true; } } if (player.isExit) { if (game.isEndLevel) { game.isPause = true; } else { game.level++; game.restart = true; game.health = player.health; game.hearts = player.heart; } } for (auto *e : enemies) { if ((*e).name == "flyEnemy" && (*e).isShoot) { CreateBullet(bullets, (*e).GetRect(), player, texture); shoot.play(); } } EntitiesIntersection(player, enemies, portals, bullets, damage); if (player.alive) { setPlayerCoordinateForView(game.camera, player.GetPos().x, player.GetPos().y); } if (!game.isPause) { UpdateEnemies(objects, enemies, time, player); UpdatePortals(portals, time); UpdateBullets(objects, bullets, time); player.Update(objects, time, pos, game.portalH); } window.setView(game.camera); window.clear(); lvl.Draw(window); DrawEnemies(window, enemies); DrawPortals(window, portals); DrawBullets(window, bullets); DrawStatistic(window, &game, player, game.camera); window.draw(player.sprite); DrawAllMessages(player, game, window); music.setLoop(true); window.display(); } return game.restart; }
String FileChooser::basenameForWidth(const Font& f, int width) const { QFontMetrics fm(f.font()); return fm.elidedText(m_filename, Qt::ElideLeft, width); }
void SurfaceImpl::SetFont(Font &font_) { if (font_.GetID()) { hdc->SetFont(*((wxFont*)font_.GetID())); } }
gcc_pure unsigned GetFontHeight() const { return font != nullptr ? font->GetHeight() : 0; }
void Window::SetFont(Font &font) { GETWIN(id)->SetFont(*((wxFont*)font.GetID())); }
/* Interprets element \a e as a variant and returns the result of the interpretation, extracting the data as a text element is the \a comment matches the tag name. If the interpretation fails the \a defValue is returned instead. */ QVariant DomTool::elementToVariant(const QDomElement& e, const QVariant& defValue, QString &comment) { Q_UNUSED(defValue); QVariant v; Variant var; if (e.tagName() == QLatin1String("rect")) { QDomElement n3 = e.firstChild().toElement(); int x = 0, y = 0, w = 0, h = 0; while (!n3.isNull()) { if (n3.tagName() == QLatin1String("x")) x = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("y")) y = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("width")) w = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("height")) h = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } var.createRect(x, y, w, h); v.setValue(var); } else if (e.tagName() == QLatin1String("point")) { QDomElement n3 = e.firstChild().toElement(); int x = 0, y = 0; while (!n3.isNull()) { if (n3.tagName() == QLatin1String("x")) x = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("y")) y = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } var.createPoint(x,y); v.setValue(var); } else if (e.tagName() == QLatin1String("size")) { QDomElement n3 = e.firstChild().toElement(); int w = 0, h = 0; while (!n3.isNull()) { if (n3.tagName() == QLatin1String("width")) w = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("height")) h = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } var.createSize(w, h); v.setValue(var); } else if (e.tagName() == QLatin1String("color")) { var.color = readColor(e); v.setValue(var); } else if (e.tagName() == QLatin1String("font")) { QDomElement n3 = e.firstChild().toElement(); Font f; f.init(); while (!n3.isNull()) { if (n3.tagName() == QLatin1String("family")) f.family = qstrdup(n3.firstChild().toText().data().toLatin1()); else if (n3.tagName() == QLatin1String("pointsize")) f.pointsize = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("bold")) f.bold = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("italic")) f.italic = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("underline")) f.underline = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("strikeout")) f.strikeout = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } var.font = f; v.setValue(var); } else if (e.tagName() == QLatin1String("string")) { v = QVariant(e.firstChild().toText().data()); QDomElement n = e; n = n.nextSibling().toElement(); if (n.tagName() == QLatin1String("comment")) comment = n.firstChild().toText().data(); } else if (e.tagName() == QLatin1String("cstring")) { v = QVariant(e.firstChild().toText().data().toAscii()); } else if (e.tagName() == QLatin1String("number")) { bool ok = true; v = QVariant(e.firstChild().toText().data().toInt(&ok)); if (!ok) v = QVariant(e.firstChild().toText().data().toDouble()); } else if (e.tagName() == QLatin1String("bool")) { QString t = e.firstChild().toText().data(); v = QVariant(t == QLatin1String("true") || t == QLatin1String("1")); } else if (e.tagName() == QLatin1String("pixmap")) { v = QVariant(e.firstChild().toText().data()); } else if (e.tagName() == QLatin1String("iconset")) { v = QVariant(e.firstChild().toText().data()); } else if (e.tagName() == QLatin1String("image")) { v = QVariant(e.firstChild().toText().data()); } else if (e.tagName() == QLatin1String("enum")) { v = QVariant(e.firstChild().toText().data()); } else if (e.tagName() == QLatin1String("set")) { v = QVariant(e.firstChild().toText().data()); } else if (e.tagName() == QLatin1String("sizepolicy")) { QDomElement n3 = e.firstChild().toElement(); var.createSizePolicy(); while (!n3.isNull()) { if (n3.tagName() == QLatin1String("hsizetype")) var.sizePolicy.hsizetype = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("vsizetype")) var.sizePolicy.vsizetype = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("horstretch")) var.sizePolicy.horstretch = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("verstretch")) var.sizePolicy.verstretch = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } v.setValue(var); } else if (e.tagName() == QLatin1String("cursor")) { var.createCursor(e.firstChild().toText().data().toInt()); v.setValue(var); } else if (e.tagName() == QLatin1String("stringlist")) { QStringList lst; QDomElement n; for (n = e.firstChild().toElement(); !n.isNull(); n = n.nextSibling().toElement()) lst << n.firstChild().toText().data(); v = QVariant(lst); } else if (e.tagName() == QLatin1String("date")) { QDomElement n3 = e.firstChild().toElement(); int y, m, d; y = m = d = 0; while (!n3.isNull()) { if (n3.tagName() == QLatin1String("year")) y = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("month")) m = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("day")) d = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } v = QVariant(QDate(y, m, d)); } else if (e.tagName() == QLatin1String("time")) { QDomElement n3 = e.firstChild().toElement(); int h, m, s; h = m = s = 0; while (!n3.isNull()) { if (n3.tagName() == QLatin1String("hour")) h = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("minute")) m = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("second")) s = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } v = QVariant(QTime(h, m, s)); } else if (e.tagName() == QLatin1String("datetime")) { QDomElement n3 = e.firstChild().toElement(); int h, mi, s, y, mo, d ; h = mi = s = y = mo = d = 0; while (!n3.isNull()) { if (n3.tagName() == QLatin1String("hour")) h = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("minute")) mi = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("second")) s = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("year")) y = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("month")) mo = n3.firstChild().toText().data().toInt(); else if (n3.tagName() == QLatin1String("day")) d = n3.firstChild().toText().data().toInt(); n3 = n3.nextSibling().toElement(); } v = QVariant(QDateTime(QDate(y, mo, d), QTime(h, mi, s))); } return v; }
void ShowFpsGraph() { ARX_PROFILE_FUNC(); GRenderer->ResetTexture(0); static std::deque<float> lastFPSArray; lastFPSArray.push_front(1000 / arxtime.get_frame_delay()); Vec2i windowSize = mainApp->getWindow()->getSize(); if(lastFPSArray.size() == size_t(windowSize.x)) { lastFPSArray.pop_back(); } float avg = 0; float worst = lastFPSArray[0]; std::vector<TexturedVertex> vertices; vertices.resize(lastFPSArray.size()); const float SCALE_Y = 2.0f; for(size_t i = 0; i < lastFPSArray.size(); ++i) { float time = lastFPSArray[i]; avg += lastFPSArray[i]; worst = std::min(worst, lastFPSArray[i]); vertices[i].color = Color(255, 255, 255, 255).toRGBA(); vertices[i].p.x = i; vertices[i].p.y = windowSize.y - (time * SCALE_Y); vertices[i].p.z = 1.0f; vertices[i].rhw = 1.0f; } avg /= lastFPSArray.size(); EERIEDRAWPRIM(Renderer::LineStrip, &vertices[0], vertices.size()); Color avgColor = Color::blue * 0.5f + Color::white * 0.5f; float avgPos = windowSize.y - (avg * SCALE_Y); drawLine2D(0, avgPos, windowSize.x, avgPos, 1.0f, Color::blue); Color worstColor = Color::red * 0.5f + Color::white * 0.5f; float worstPos = windowSize.y - (worst * SCALE_Y); drawLine2D(0, worstPos, windowSize.x, worstPos, 1.0f, Color::red); Font * font = hFontDebug; float lineOffset = font->getLineHeight() + 2; std::string labels[3] = { "Average: ", "Worst: ", "Current: " }; Color colors[3] = { avgColor, worstColor, Color::white }; float values[3] = { avg, worst, lastFPSArray[0] }; std::string texts[3]; float widths[3]; static float labelWidth = 0.f; static float valueWidth = 0.f; for(size_t i = 0; i < 3; i++) { // Format value std::ostringstream oss; oss << std::fixed << std::setprecision(2) << values[i] << " FPS"; texts[i] = oss.str(); // Calculate widths (could be done more efficiently for monospace fonts...) labelWidth = std::max(labelWidth, float(font->getTextSize(labels[i]).x)); widths[i] = font->getTextSize(texts[i]).x; valueWidth = std::max(valueWidth, widths[i]); } float x = 10; float y = 10; float xend = x + labelWidth + 10 + valueWidth; for(size_t i = 0; i < 3; i++) { font->draw(Vec2i(x, y), labels[i], Color::gray(0.8f)); font->draw(Vec2i(xend - widths[i], y), texts[i], colors[i]); y += lineOffset; } }
void ShowFrameDurationPlot() { Vec2i windowSize = mainApp->getWindow()->getSize(); size_t maxSamples = size_t(windowSize.x); if(maxSamples != frameDurationPlotValues.capacity()) { frameDurationPlotValues.set_capacity(maxSamples); } if(maxSamples != frameDurationPlotVertices.size()) { frameDurationPlotVertices.resize(maxSamples); } GRenderer->ResetTexture(0); frameDurationPlotValues.push_front(toMs(g_platformTime.lastFrameDuration())); float avg = std::accumulate(frameDurationPlotValues.begin(), frameDurationPlotValues.end(), 0.f) / frameDurationPlotValues.size(); float worst = *std::max_element(frameDurationPlotValues.begin(), frameDurationPlotValues.end()); const float OFFSET_Y = 80.f; const float SCALE_Y = 4.0f; for(size_t i = 0; i < frameDurationPlotValues.size(); ++i) { float time = frameDurationPlotValues[i]; frameDurationPlotVertices[i].color = Color::white.toRGB(); frameDurationPlotVertices[i].p.x = i; frameDurationPlotVertices[i].p.y = OFFSET_Y + (time * SCALE_Y); frameDurationPlotVertices[i].p.z = 1.0f; frameDurationPlotVertices[i].w = 1.0f; } EERIEDRAWPRIM(Renderer::LineStrip, &frameDurationPlotVertices[0], frameDurationPlotValues.size()); Color avgColor = Color::blue * 0.5f + Color::white * 0.5f; float avgPos = OFFSET_Y + (avg * SCALE_Y); drawLine(Vec2f(0, avgPos), Vec2f(windowSize.x, avgPos), 1.0f, Color::blue); Color worstColor = Color::red * 0.5f + Color::white * 0.5f; float worstPos = OFFSET_Y + (worst * SCALE_Y); drawLine(Vec2f(0, worstPos), Vec2f(windowSize.x, worstPos), 1.0f, Color::red); Font * font = hFontDebug; float lineOffset = font->getLineHeight() + 2; std::string labels[3] = { "Average: ", "Worst: ", "Current: " }; Color colors[3] = { avgColor, worstColor, Color::white }; float values[3] = { avg, worst, frameDurationPlotValues[0] }; std::string texts[3]; float widths[3]; static float labelWidth = 0.f; static float valueWidth = 0.f; for(size_t i = 0; i < 3; i++) { // Format value std::ostringstream oss; oss << std::fixed << std::setprecision(2) << values[i] << " ms ("<< 1.f / (values[i] * 0.001f) << " FPS)"; texts[i] = oss.str(); // Calculate widths (could be done more efficiently for monospace fonts...) labelWidth = std::max(labelWidth, float(font->getTextSize(labels[i]).width())); widths[i] = font->getTextSize(texts[i]).width(); valueWidth = std::max(valueWidth, widths[i]); } float x = 10; float y = 10; float xend = x + labelWidth + 10 + valueWidth; for(size_t i = 0; i < 3; i++) { font->draw(Vec2i(x, y), labels[i], Color::gray(0.8f)); font->draw(Vec2i(xend - widths[i], y), texts[i], colors[i]); y += lineOffset; } }
void TextureFontApp::mouseDown( MouseEvent event ) { mFont = Font( Font::getNames()[Rand::randInt() % Font::getNames().size()], mFont.getSize() ); console() << mFont.getName() << std::endl; mTextureFont = gl::TextureFont::create( mFont ); }
int main() { srand( time(NULL) ); Vector2u GridSize; unsigned int noOfBugs = 100; unsigned int noOfPreds = 200; float maxBugConsumeRate = 1.0f; //float maxCellProduceRate = 0.01f; bool criticalMassReached = false; float initialBugSizeMean = 0.1f, initialBugSizeSD = 0.3f; float minSize, meanSize, maxSize; //step 8; output to a file the minimum bugsize, the average bugsize and the max bugsize; try { cout << "Input desired number of bugs: "; cin >> noOfBugs; cout << "\nInput bug consume rate: "; cin >> maxBugConsumeRate; cout << "\nInput desired number of predators: "; cin >> noOfPreds; //cout << "\nInput food production rate: "; //cin >> maxCellProduceRate; cout << "\nInput starting bug size average: "; cin >> initialBugSizeMean; cout << "\nInput starting bug size standard deviation: "; cin >> initialBugSizeSD; } catch (...) { cout << "Invalid arguement!\nIma just use the defaults..." << endl; } Font font; font.loadFromFile( "../kenvector_future.ttf" ); // Create the main window RenderWindow window(VideoMode(800, 600, 32), "Stupid model 16"); Histogram graph( 10, font ); std::vector<std::vector<HabitatCell> > grid; std::vector<Bug> bugs; std::vector<Predator> predators; grid.reserve( GridSize.x ); bugs.reserve( noOfBugs ); predators.reserve( noOfPreds ); bool mousePressed = Mouse::isButtonPressed( Mouse::Button::Left ); createGridFromFile("../Stupid_Cell.DATA", grid, GridSize); //place bugs randomly in the grid for (int i = 0; i < noOfBugs; i++) { int x = rand() % GridSize.x, y = rand() % GridSize.y; if ( grid[x][y].hasBug != true ) { grid[x][y].hasBug = true; bugs.push_back( Bug(Vector2i(x,y), 1, &grid, maxBugConsumeRate) ); //get a random float from 0.0 to twice the SD float deviation = static_cast<float>( rand() / (static_cast<float>(RAND_MAX / (initialBugSizeSD*2))) ); deviation -= initialBugSizeSD; //allow deviation to be from -SD to +SD bugs.rbegin()->setSize( max(initialBugSizeMean + deviation, 0.0f) ); //don't let size be less than 0 } else { --i; } } //place predators randomly in the grid for (int i = 0; i < noOfPreds; i++) { int x = rand() % GridSize.x, y = rand() % GridSize.y; if ( grid[x][y].hasPredator != true ) { grid[x][y].hasPredator = true; predators.push_back( Predator(Vector2i(x,y), GridSpacing, &grid) ); } else { --i; } } Clock clock = Clock(); ofstream logStream; logStream.open( "bugSizes.log" ); logStream << "\n---------------------- Application Started ----------------" << endl; //START WINDOW LOOP while (window.isOpen()) { // Process events sf::Event Event; while (window.pollEvent(Event)) { // Close window : exit if (Event.type == sf::Event::Closed) window.close(); // Escape key : exit if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape)) window.close(); } //output the values of cell on mouse button down (if button wasn't down last frame) if ( Mouse::isButtonPressed(Mouse::Button::Left) && !mousePressed) { mousePressed = true; try { Vector2i mousePos = Mouse::getPosition(window); cout << grid.at((int)(mousePos.x / GridSpacing)).at((int)(mousePos.y / GridSpacing)); } catch (...) { std::cout << "No cell at this position" << std::endl; } } mousePressed = Mouse::isButtonPressed( Mouse::Button::Left ); if ( clock.getElapsedTime().asSeconds() >= 0 ) { //tell all the HabitatCells to produce food (and draw them to the window) for(std::vector<std::vector<HabitatCell>>::iterator itr = grid.begin(); itr != grid.end(); itr++) { for(std::vector<HabitatCell>::iterator itr2 = itr->begin(); itr2 != itr->end(); itr2++) { itr2->ProduceFood(); //itr2->Draw( window ); } } //reset min and max so that we can find the new ones below... minSize = FLT_MAX; maxSize = -FLT_MAX; meanSize = 0; //sort the bugs in descending order by size; std::sort(bugs.rbegin(), bugs.rend()); for(int i = 0; i < bugs.size(); i++) { bugs[i].Move(GridSize); bugs[i].Grow(); //if the bug fails the survival probability, it dies if ( bugs[i].Mortality() ) { Vector2i loc = bugs[i].getPosition(); grid[loc.x][loc.y].hasBug = false; vector<Bug>::iterator nth = bugs.begin() + i--; //decrement i so that we don't skip next bug bugs.erase( nth ); continue; } //if the bugs reaches a certain size, kill it and hatch it's eggs else { if ( bugs[i].IsReproducing(&bugs, GridSize)) { vector<Bug>::iterator nth = bugs.begin() + i--; //decrement i so that we don't skip next bug bugs.erase( nth ); continue; } } //...find min, mean and max bug sizes float size = bugs[i].getSize(); if ( size < minSize ) minSize = size; else if ( size > maxSize ) maxSize = size; //add this bug's size to the average... meanSize += size; } for(auto itr = predators.begin(); itr != predators.end(); ++itr) { itr->Hunt(bugs, GridSize); } //...divide by the number of bugs to get the average size meanSize /= noOfBugs; logStream << "Minimum Bug Size: " << minSize; logStream << "\t Average Bug Size: " << meanSize; logStream << "\t Maximum Bug Size: " << maxSize << endl; //if no bugs left or 1000 iteration passed... static int step; if ( bugs.size() == 0 || ++step >= 1000) { cout << bugs.size() << " bugs left. " << step << " iterations processed" << endl; window.close(); } window.setTitle("Timestep: " + to_string(step)); //restart the clock clock.restart(); } //prepare frame window.clear(); for (auto x = grid.begin(); x != grid.end(); x++) { for (auto y = x->begin(); y != x->end(); y++) { y->Draw(window); } } for(auto itr = bugs.begin(); itr != bugs.end(); itr++) { itr->Draw(window); } for(auto itr = predators.begin(); itr != predators.end(); itr++) { itr->Draw(window); } window.display(); //update and draw the graph graph.Update( getBugDistribution(bugs) ); graph.Draw( Vector2i(window.getPosition().x + window.getSize().x, window.getPosition().y) ); } //loop back for next frame logStream << "-------------------- Application closing ---------------------" << endl; logStream.close(); system("PAUSE"); return EXIT_SUCCESS; }
void CallMenu(RenderWindow & window, Game & game) { int MenuNum = 0; Font font; font.loadFromFile("myFont.otf"); Text point1("7", font, SIZE_MENU_TEXT), point2("11", font, SIZE_MENU_TEXT), point3("15", font, SIZE_MENU_TEXT), newGame(L"Новая игра", font, SIZE_MENU_TEXT), exit(L"Выход", font, SIZE_MENU_TEXT); Vector2f location(0.f, 0.f); float width; location.x = SCREEN_WIDTH / 2 - newGame.getGlobalBounds().width / 2; location.y = 3 * SIZE_MENU_TEXT; width = newGame.getGlobalBounds().width; newGame.setPosition(location); if (IntRect(location.x, location.y, width, SIZE_MENU_TEXT).contains(Mouse::getPosition(window))) { newGame.setColor(Color::Yellow); MenuNum = 1; } //------------------- Расположение текста по центру ---------------------- location.x = SCREEN_WIDTH / 2 - 5 * point1.getGlobalBounds().width; location.y = 5 * SIZE_MENU_TEXT; width = point1.getGlobalBounds().width; point1.setPosition(location); if (IntRect(location.x, location.y, width, SIZE_MENU_TEXT).contains(Mouse::getPosition(window))) { point1.setColor(Color::Yellow); MenuNum = 2; } location.x = SCREEN_WIDTH / 2 - point1.getGlobalBounds().width; width = point2.getGlobalBounds().width; point2.setPosition(location); if (IntRect(location.x, location.y, width, SIZE_MENU_TEXT).contains(Mouse::getPosition(window))) { point2.setColor(Color::Yellow); MenuNum = 3; } location.x = SCREEN_WIDTH / 2 + 4 * point1.getGlobalBounds().width; width = point3.getGlobalBounds().width; point3.setPosition(location); if (IntRect(location.x, location.y, width, SIZE_MENU_TEXT).contains(Mouse::getPosition(window))) { point3.setColor(Color::Yellow); MenuNum = 4; } location.x = SCREEN_WIDTH / 2 - exit.getGlobalBounds().width / 2; location.y = 7 * SIZE_MENU_TEXT; width = exit.getGlobalBounds().width; exit.setPosition(location); if (IntRect(location.x, location.y, width, SIZE_MENU_TEXT).contains(Mouse::getPosition(window))) { exit.setColor(Color::Yellow); MenuNum = 5; } // -------------------------------------------------------------------------------------- if (Mouse::isButtonPressed(Mouse::Left)) { if (MenuNum == 1) { game.gameState.isPlay = true; game.gameState.isBegin = true; game.racket.count = 0; game.racket2.count = 0; game.ball.circle->setPosition(0, -100); game.gameState.isPayse = false; } if (MenuNum == 2) { game.ball.pointWin = POINT_1; } if (MenuNum == 3) { game.ball.pointWin = POINT_2; } if (MenuNum == 4) { game.ball.pointWin = POINT_3; } if (MenuNum == 5) { window.close(); } } //Выделение цветом очков if (game.ball.pointWin == POINT_1) point1.setColor(Color::Yellow); if (game.ball.pointWin == POINT_2) point2.setColor(Color::Yellow); if (game.ball.pointWin == POINT_3) point3.setColor(Color::Yellow); //---------------------------- window.draw(newGame); window.draw(point1); window.draw(point2); window.draw(point3); window.draw(exit); }