AccessibilityObjectInclusion AccessibilityObject::accessibilityPlatformIncludesObject() const { AccessibilityObject* parent = parentObject(); if (!parent) return DefaultBehavior; AccessibilityRole role = roleValue(); // We expose the slider as a whole but not its value indicator. if (role == SliderThumbRole) return IgnoreObject; // When a list item is made up entirely of children (e.g. paragraphs) // the list item gets ignored. We need it. if (isGroup() && parent->isList()) return IncludeObject; // Entries and password fields have extraneous children which we want to ignore. if (parent->isPasswordField() || parent->isTextControl()) return IgnoreObject; // Include all tables, even layout tables. The AT can decide what to do with each. if (role == CellRole || role == TableRole || role == ColumnHeaderRole || role == RowHeaderRole) return IncludeObject; // The object containing the text should implement AtkText itself. if (role == StaticTextRole) return IgnoreObject; // Include all list items, regardless they have or not inline children if (role == ListItemRole) return IncludeObject; // Bullets/numbers for list items shouldn't be exposed as AtkObjects. if (role == ListMarkerRole) return IgnoreObject; // Never expose an unknown object, since AT's won't know what to // do with them. This is what is done on the Mac as well. if (role == UnknownRole) return IgnoreObject; if (role == InlineRole) return IncludeObject; // Lines past this point only make sense for AccessibilityRenderObjects. RenderObject* renderObject = renderer(); if (!renderObject) return DefaultBehavior; // We don't want <span> elements to show up in the accessibility hierarchy unless // we have good reasons for that (e.g. focusable or visible because of containing // a meaningful accessible name, maybe set through ARIA), so we can use // atk_component_grab_focus() to set the focus to it. Node* node = renderObject->node(); if (node && node->hasTagName(HTMLNames::spanTag) && !canSetFocusAttribute() && !hasAttributesRequiredForInclusion()) return IgnoreObject; // Given a paragraph or div containing a non-nested anonymous block, WebCore // ignores the paragraph or div and includes the block. We want the opposite: // ATs are expecting accessible objects associated with textual elements. They // usually have no need for the anonymous block. And when the wrong objects // get included or ignored, needed accessibility signals do not get emitted. if (role == ParagraphRole || role == DivRole) { // Don't call textUnderElement() here, because it's slow and it can // crash when called while we're in the middle of a subtree being deleted. if (!renderObject->firstChildSlow()) return DefaultBehavior; if (!parent->renderer() || parent->renderer()->isAnonymousBlock()) return DefaultBehavior; for (RenderObject* r = renderObject->firstChildSlow(); r; r = r->nextSibling()) { if (r->isAnonymousBlock()) return IncludeObject; } } // Block spans result in objects of ATK_ROLE_PANEL which are almost always unwanted. // However, if we ignore block spans whose parent is the body, the child controls // will become immediate children of the ATK_ROLE_DOCUMENT_FRAME and any text will // become text within the document frame itself. This ultimately may be what we want // and would largely be consistent with what we see from Gecko. However, ignoring // spans whose parent is the body changes the current behavior we see from WebCore. // Until we have sufficient time to properly analyze these cases, we will defer to // WebCore. We only check that the parent is not aria because we do not expect // anonymous blocks which are aria-related to themselves have an aria role, nor // have we encountered instances where the parent of an anonymous block also lacked // an aria role but the grandparent had one. if (renderObject && renderObject->isAnonymousBlock() && !parent->renderer()->isBody() && parent->ariaRoleAttribute() == UnknownRole) return IgnoreObject; return DefaultBehavior; }
int Cn3DNoWin::Run(void) { TRACEMSG("Hello! Running build from " << __DATE__); int status = 1; try { // validate arguments const CArgs& args = GetArgs(); if (!(args["f"].HasValue() || args["d"].HasValue()) || (args["f"].HasValue() && args["d"].HasValue())) ERRORTHROW("Command line: Must supply one (and only one) of -f or -d"); EModel_type model = eModel_type_ncbi_all_atom; if (args["o"].HasValue()) { if (args["o"].AsString() == "alpha") model = eModel_type_ncbi_backbone; else if (args["o"].AsString() == "PDB") model = eModel_type_pdb_model; } string favorite(args["s"].HasValue() ? args["s"].AsString() : kEmptyStr); // setup dirs SetUpWorkingDirectories(GetArguments().GetProgramName().c_str()); // read dictionary wxString dictFile = wxString(GetDataDir().c_str()) + "bstdt.val"; LoadStandardDictionary(dictFile.c_str()); // set up registry LoadRegistry(); // local structure set and renderer StructureSet *sset = NULL; OpenGLRenderer renderer(NULL); // load data from file if (args["f"].HasValue()) { // if -o is present, assume this is a Biostruc file if (args["o"].HasValue()) { CNcbi_mime_asn1 *mime = CreateMimeFromBiostruc(args["f"].AsString(), model); if (!mime || !LoadDataOnly(&sset, &renderer, NULL, mime, favorite)) ERRORTHROW("Failed to load Biostruc file " << args["f"].AsString()); } else { if (!LoadDataOnly(&sset, &renderer, args["f"].AsString().c_str(), NULL, favorite, model)) ERRORTHROW("Failed to load file " << args["f"].AsString()); } } // else network fetch else { CNcbi_mime_asn1 *mime = LoadStructureViaCache(args["d"].AsString(), model, 0); if (!mime || !LoadDataOnly(&sset, &renderer, NULL, mime, favorite)) ERRORTHROW("Failed to load from network with id " << args["d"].AsString()); } if (!sset) ERRORTHROW("Somehow ended up with NULL sset"); auto_ptr < StructureSet > sset_ap(sset); // so we can be sure it's deleted // export PNG image if (!ExportPNG(NULL, &renderer, args["p"].AsString(), args["w"].AsInteger(), args["h"].AsInteger(), args["i"].HasValue())) ERRORTHROW("PNG export failed"); TRACEMSG("Done!"); status = 0; } catch (ncbi::CException& ce) { ERRORMSG("Caught CException: " << ce.GetMsg()); } catch (std::exception& e) { ERRORMSG("Caught exception: " << e.what()); } catch (...) { ERRORMSG("Caught unknown exception"); } return status; }
void HTMLElement::setInnerText(const String& text, ExceptionCode& ec) { // follow the IE specs about when this is allowed if (endTagRequirement() == TagStatusForbidden) { ec = NO_MODIFICATION_ALLOWED_ERR; return; } if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) || hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) || hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) || hasLocalName(trTag)) { ec = NO_MODIFICATION_ALLOWED_ERR; return; } // FIXME: This doesn't take whitespace collapsing into account at all. if (!text.contains('\n') && !text.contains('\r')) { if (text.isEmpty()) { removeChildren(); return; } replaceChildrenWithText(this, text, ec); return; } // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer? // FIXME: Can the renderer be out of date here? Do we need to call updateRendering? // For example, for the contents of textarea elements that are display:none? RenderObject* r = renderer(); if (r && r->style()->preserveNewline()) { if (!text.contains('\r')) { replaceChildrenWithText(this, text, ec); return; } String textWithConsistentLineBreaks = text; textWithConsistentLineBreaks.replace("\r\n", "\n"); textWithConsistentLineBreaks.replace('\r', '\n'); replaceChildrenWithText(this, textWithConsistentLineBreaks, ec); return; } // Add text nodes and <br> elements. ec = 0; RefPtr<DocumentFragment> fragment = new DocumentFragment(document()); int lineStart = 0; UChar prev = 0; int length = text.length(); for (int i = 0; i < length; ++i) { UChar c = text[i]; if (c == '\n' || c == '\r') { if (i > lineStart) { fragment->appendChild(new Text(document(), text.substring(lineStart, i - lineStart)), ec); if (ec) return; } if (!(c == '\n' && i != 0 && prev == '\r')) { fragment->appendChild(new HTMLBRElement(brTag, document()), ec); if (ec) return; } lineStart = i + 1; } prev = c; } if (length > lineStart) fragment->appendChild(new Text(document(), text.substring(lineStart, length - lineStart)), ec); replaceChildrenWithFragment(this, fragment.release(), ec); }
RenderBlock* RootInlineBox::block() const { return toRenderBlock(renderer()); }
PassRefPtr<FilterEffect> SVGFEImageElement::build(SVGFilterBuilder*, Filter* filter) { if (m_cachedImage) return FEImage::createWithImage(filter, m_cachedImage->imageForRenderer(renderer()), preserveAspectRatio()); return FEImage::createWithIRIReference(filter, document(), href(), preserveAspectRatio()); }
bool Modules::init() { // Create modules (order is important because of dependencies) if( _extensionManager == 0x0 ) _extensionManager = new ExtensionManager(); if( _engineLog == 0x0 ) _engineLog = new EngineLog(); if( _engineConfig == 0x0 ) _engineConfig = new EngineConfig(); if( _sceneManager == 0x0 ) _sceneManager = new SceneManager(); if( _resourceManager == 0x0 ) _resourceManager = new ResourceManager(); if( _renderDevice == 0x0 ) _renderDevice = new RenderDevice(); gRDI = _renderDevice; if( _renderer == 0x0 ) _renderer = new Renderer(); if( _statManager == 0x0 ) _statManager = new StatManager(); // Init modules if( !renderer().init() ) return false; // Register resource types resMan().registerType( ResourceTypes::SceneGraph, "SceneGraph", 0x0, 0x0, SceneGraphResource::factoryFunc ); resMan().registerType( ResourceTypes::Geometry, "Geometry", GeometryResource::initializationFunc, GeometryResource::releaseFunc, GeometryResource::factoryFunc ); resMan().registerType( ResourceTypes::Animation, "Animation", 0x0, 0x0, AnimationResource::factoryFunc ); resMan().registerType( ResourceTypes::Material, "Material", 0x0, 0x0, MaterialResource::factoryFunc ); resMan().registerType( ResourceTypes::Code, "Code", 0x0, 0x0, CodeResource::factoryFunc ); resMan().registerType( ResourceTypes::Shader, "Shader", 0x0, 0x0, ShaderResource::factoryFunc ); resMan().registerType( ResourceTypes::Texture, "Texture", TextureResource::initializationFunc, TextureResource::releaseFunc, TextureResource::factoryFunc ); resMan().registerType( ResourceTypes::ParticleEffect, "ParticleEffect", 0x0, 0x0, ParticleEffectResource::factoryFunc ); resMan().registerType( ResourceTypes::Pipeline, "Pipeline", 0x0, 0x0, PipelineResource::factoryFunc ); // Register node types sceneMan().registerType( SceneNodeTypes::Group, "Group", GroupNode::parsingFunc, GroupNode::factoryFunc, 0x0 ); sceneMan().registerType( SceneNodeTypes::Model, "Model", ModelNode::parsingFunc, ModelNode::factoryFunc, 0x0 ); sceneMan().registerType( SceneNodeTypes::Mesh, "Mesh", MeshNode::parsingFunc, MeshNode::factoryFunc, Renderer::drawMeshes ); sceneMan().registerType( SceneNodeTypes::Joint, "Joint", JointNode::parsingFunc, JointNode::factoryFunc, 0x0 ); sceneMan().registerType( SceneNodeTypes::Light, "Light", LightNode::parsingFunc, LightNode::factoryFunc, 0x0 ); sceneMan().registerType( SceneNodeTypes::Camera, "Camera", CameraNode::parsingFunc, CameraNode::factoryFunc, 0x0 ); sceneMan().registerType( SceneNodeTypes::Emitter, "Emitter", EmitterNode::parsingFunc, EmitterNode::factoryFunc, Renderer::drawParticles ); // Install extensions installExtensions(); // Create default resources TextureResource *tex2DRes = new TextureResource( "$Tex2D", 32, 32, 1, TextureFormats::BGRA8, ResourceFlags::NoTexMipmaps ); void *image = tex2DRes->mapStream( TextureResData::ImageElem, 0, TextureResData::ImgPixelStream, false, true ); ASSERT( image != 0x0 ); for( uint32 i = 0; i < 32*32; ++i ) ((uint32 *)image)[i] = 0xffffffff; tex2DRes->unmapStream(); tex2DRes->addRef(); resMan().addNonExistingResource( *tex2DRes, false ); TextureResource *texCubeRes = new TextureResource( "$TexCube", 32, 32, 1, TextureFormats::BGRA8, ResourceFlags::TexCubemap | ResourceFlags::NoTexMipmaps ); for( uint32 i = 0; i < 6; ++i ) { image = texCubeRes->mapStream( TextureResData::ImageElem, i, TextureResData::ImgPixelStream, false, true ); ASSERT( image != 0x0 ); for( uint32 j = 0; j < 32*32; ++j ) ((uint32 *)image)[j] = 0xff000000; texCubeRes->unmapStream(); } texCubeRes->addRef(); resMan().addNonExistingResource( *texCubeRes, false ); TextureResource *tex3DRes = new TextureResource( "$Tex3D", 16, 16, 4, TextureFormats::BGRA8, ResourceFlags::NoTexMipmaps ); image = tex3DRes->mapStream( TextureResData::ImageElem, 0, TextureResData::ImgPixelStream, false, true ); ASSERT( image != 0x0 ); for( uint32 i = 0; i < 16*16*4; ++i ) ((uint32 *)image)[i] = 0xffffffff; tex3DRes->unmapStream(); tex3DRes->addRef(); resMan().addNonExistingResource( *tex3DRes, false ); return true; }
bool MapnikRenderer::Preprocess( IImporter* importer, QString dir ) { QString filename = fileInDirectory( dir, "Mapnik Renderer" ); try { IImporter::BoundingBox box; if ( !importer->GetBoundingBox( &box ) ) return false; std::vector< IImporter::RoutingEdge > inputEdges; std::vector< IImporter::RoutingNode > inputNodes; std::vector< IImporter::RoutingNode > inputPaths; if ( m_settings.deleteTiles ) { if ( !importer->GetRoutingEdges( &inputEdges ) ) { qCritical() << "Mapnik Renderer: failed to read routing edges"; return false; } if ( !importer->GetRoutingNodes( &inputNodes ) ) { qCritical() << "Mapnik Renderer: failed to read routing nodes"; return false; } if ( !importer->GetRoutingEdgePaths( &inputPaths ) ) { qCritical() << "Mapnik Renderer: failed to read routing paths"; } } Timer time; mapnik::datasource_cache::instance().register_datasources( m_settings.plugins.toLatin1().constData() ); QDir fonts( m_settings.fonts ); mapnik::projection projection( "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ); mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans.ttf" ).toLatin1().constData() ); mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-Bold.ttf" ).toLatin1().constData() ); mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-Oblique.ttf" ).toLatin1().constData() ); mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-BoldOblique.ttf" ).toLatin1().constData() ); qDebug() << "Mapnik Renderer: initialized mapnik connection:" << time.restart() << "ms"; int numThreads = omp_get_max_threads(); qDebug() << "Mapnik Renderer: using" << numThreads << "threads"; qDebug() << "Mapnik Renderer: x: " << box.min.x << "-" << box.max.x; qDebug() << "Mapnik Renderer: y: " << box.min.y << "-" << box.max.y; FileStream configData( filename ); if ( !configData.open( QIODevice::WriteOnly ) ) return false; configData << quint32( m_settings.tileSize ) << quint32( m_settings.zoomLevels.size() ); long long tilesSkipped = 0; long long tiles = 0; long long metaTilesRendered = 0; long long pngcrushSaved = 0; std::vector< ZoomInfo > zoomInfo( m_settings.zoomLevels.size() ); std::vector< MetaTile > tasks; for ( int zoomLevel = 0; zoomLevel < ( int ) m_settings.zoomLevels.size(); zoomLevel++ ) { ZoomInfo& info = zoomInfo[zoomLevel]; int zoom = m_settings.zoomLevels[zoomLevel]; info.minX = box.min.GetTileX( zoom ); info.maxX = box.max.GetTileX( zoom ) + 1; info.minY = box.min.GetTileY( zoom ); info.maxY = box.max.GetTileY( zoom ) + 1; if ( zoom <= m_settings.fullZoom ) { info.minX = info.minY = 0; info.maxX = info.maxY = 1 << zoom; } else { info.minX = std::max( 0 , info.minX - m_settings.tileMargin ); info.maxX = std::min ( 1 << zoom, info.maxX + m_settings.tileMargin ); info.minY = std::max( 0, info.minY - m_settings.tileMargin ); info.maxY = std::min ( 1 << zoom, info.maxY + m_settings.tileMargin ); } tiles += ( info.maxX - info.minX ) * ( info.maxY - info.minY ); qDebug() << "Mapnik Renderer: [" << zoom << "] x:" << info.minX << "-" << info.maxX << "; y:" << info.minY << "-" << info.maxY; configData << quint32( zoom ) << quint32( info.minX ) << quint32( info.maxX ) << quint32( info.minY ) << quint32( info.maxY ); int numberOfTiles = ( info.maxX - info.minX ) * ( info.maxY - info.minY ); IndexElement dummyIndex; dummyIndex.start = dummyIndex.size = 0; info.index.resize( numberOfTiles, dummyIndex ); std::vector< UnsignedCoordinate > path; for ( std::vector< IImporter::RoutingEdge >::const_iterator i = inputEdges.begin(), e = inputEdges.end(); i != e; ++i ) { path.push_back( inputNodes[i->source].coordinate ); for ( int pathID = 0; pathID < i->pathLength; pathID++ ) path.push_back( inputPaths[pathID + i->pathID].coordinate ); path.push_back( inputNodes[i->target].coordinate ); for ( unsigned edge = 0; edge < path.size(); edge++ ) { int sourceX = path[edge].GetTileX( zoom ); int sourceY = path[edge].GetTileY( zoom ); int targetX = path[edge].GetTileX( zoom ); int targetY = path[edge].GetTileY( zoom ); if ( sourceX > targetX ) std::swap( sourceX, targetX ); if ( sourceY > targetY ) std::swap( sourceY, targetY ); sourceX = std::max( sourceX, info.minX ); sourceX = std::min( sourceX, info.maxX - 1 ); sourceY = std::max( sourceY, info.minY ); sourceY = std::min( sourceY, info.maxY - 1 ); targetX = std::max( targetX, info.minX ); targetX = std::min( targetX, info.maxX - 1 ); targetY = std::max( targetY, info.minY ); targetY = std::min( targetY, info.maxY - 1 ); for ( int x = sourceX; x <= targetX; ++x ) for ( int y = sourceY; y <= targetY; ++y ) info.index[( x - info.minX ) + ( y - info.minY ) * ( info.maxX - info.minX )].size = 1; } path.clear(); } info.tilesFile = new QFile( filename + QString( "_%1_tiles" ).arg( zoom ) ); if ( !openQFile( info.tilesFile, QIODevice::WriteOnly ) ) return false; for ( int x = info.minX; x < info.maxX; x+= m_settings.metaTileSize ) { int metaTileSizeX = std::min( m_settings.metaTileSize, info.maxX - x ); for ( int y = info.minY; y < info.maxY; y+= m_settings.metaTileSize ) { int metaTileSizeY = std::min( m_settings.metaTileSize, info.maxY - y ); MetaTile tile; tile.zoom = zoomLevel; tile.x = x; tile.y = y; tile.metaTileSizeX = metaTileSizeX; tile.metaTileSizeY = metaTileSizeY; tasks.push_back( tile ); } } } #pragma omp parallel { int threadID = omp_get_thread_num(); const int metaTileSize = m_settings.metaTileSize * m_settings.tileSize + 2 * m_settings.margin; mapnik::Map map; mapnik::image_32 image( metaTileSize, metaTileSize ); QTemporaryFile tempOut; QTemporaryFile tempIn; mapnik::load_map( map, m_settings.theme.toLocal8Bit().constData() ); #pragma omp for schedule( dynamic ) for ( int i = 0; i < ( int ) tasks.size(); i++ ) { int metaTileSizeX = tasks[i].metaTileSizeX; int metaTileSizeY = tasks[i].metaTileSizeY; int x = tasks[i].x; int y = tasks[i].y; int zoomLevel = tasks[i].zoom; int zoom = m_settings.zoomLevels[zoomLevel]; ZoomInfo& info = zoomInfo[zoomLevel]; map.resize( metaTileSizeX * m_settings.tileSize + 2 * m_settings.margin, metaTileSizeY * m_settings.tileSize + 2 * m_settings.margin ); ProjectedCoordinate drawTopLeft( x - 1.0 * m_settings.margin / m_settings.tileSize, y - 1.0 * m_settings.margin / m_settings.tileSize, zoom ); ProjectedCoordinate drawBottomRight( x + metaTileSizeX + 1.0 * m_settings.margin / m_settings.tileSize, y + metaTileSizeY + 1.0 * m_settings.margin / m_settings.tileSize, zoom ); GPSCoordinate drawTopLeftGPS = drawTopLeft.ToGPSCoordinate(); GPSCoordinate drawBottomRightGPS = drawBottomRight.ToGPSCoordinate(); projection.forward( drawTopLeftGPS.longitude, drawBottomRightGPS.latitude ); projection.forward( drawBottomRightGPS.longitude, drawTopLeftGPS.latitude ); mapnik::box2d<double> boundingBox( drawTopLeftGPS.longitude, drawTopLeftGPS.latitude, drawBottomRightGPS.longitude, drawBottomRightGPS.latitude ); map.zoom_to_box( boundingBox ); mapnik::agg_renderer<mapnik::image_32> renderer( map, image ); renderer.apply(); std::string data; int skipped = 0; int saved = 0; for ( int subX = 0; subX < metaTileSizeX; ++subX ) { for ( int subY = 0; subY < metaTileSizeY; ++subY ) { int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX; mapnik::image_view<mapnik::image_data_32> view = image.get_view( subX * m_settings.tileSize + m_settings.margin, subY * m_settings.tileSize + m_settings.margin, m_settings.tileSize, m_settings.tileSize ); std::string result; if ( !m_settings.deleteTiles || info.index[( x + subX - info.minX ) + ( y + subY - info.minY ) * ( info.maxX - info.minX )].size == 1 ) { if ( m_settings.reduceColors ) result = mapnik::save_to_string( view, "png256" ); else result = mapnik::save_to_string( view, "png" ); if ( m_settings.pngcrush ) { tempOut.open(); tempOut.write( result.data(), result.size() ); tempOut.flush(); tempIn.open(); pclose( popen( ( "pngcrush " + tempOut.fileName() + " " + tempIn.fileName() ).toUtf8().constData(), "r" ) ); QByteArray buffer = tempIn.readAll(); tempIn.close(); tempOut.close(); if ( buffer.size() != 0 && buffer.size() < ( int ) result.size() ) { saved += result.size() - buffer.size(); result.assign( buffer.constData(), buffer.size() ); } } } info.index[indexNumber].start = data.size(); info.index[indexNumber].size = result.size(); data += result; } } qint64 position; #pragma omp critical { position = info.tilesFile->pos(); info.tilesFile->write( data.data(), data.size() ); metaTilesRendered++; tilesSkipped += skipped; pngcrushSaved += saved; qDebug() << "Mapnik Renderer: [" << zoom << "], thread" << threadID << ", metatiles:" << metaTilesRendered << "/" << tasks.size(); } for ( int subX = 0; subX < metaTileSizeX; ++subX ) { for ( int subY = 0; subY < metaTileSizeY; ++subY ) { int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX; info.index[indexNumber].start += position; } } } } for ( int zoomLevel = 0; zoomLevel < ( int ) m_settings.zoomLevels.size(); zoomLevel++ ) { const ZoomInfo& info = zoomInfo[zoomLevel]; int zoom = m_settings.zoomLevels[zoomLevel]; QFile indexFile( filename + QString( "_%1_index" ).arg( zoom ) ); if ( !openQFile( &indexFile, QIODevice::WriteOnly ) ) return false; for ( int i = 0; i < ( int ) info.index.size(); i++ ) { indexFile.write( ( const char* ) &info.index[i].start, sizeof( info.index[i].start ) ); indexFile.write( ( const char* ) &info.index[i].size, sizeof( info.index[i].size ) ); } delete info.tilesFile; } if ( m_settings.deleteTiles ) qDebug() << "Mapnik Renderer: removed" << tilesSkipped << "tiles"; if ( m_settings.pngcrush ) qDebug() << "Mapnik Renderer: PNGcrush saved" << pngcrushSaved / 1024 / 1024 << "MB"; qDebug() << "Mapnik Renderer: finished:" << time.restart() << "ms"; } catch ( const mapnik::config_error & ex ) { qCritical( "Mapnik Renderer: ### Configuration error: %s", ex.what() ); return false; } catch ( const std::exception & ex ) { qCritical( "Mapnik Renderer: ### STD error: %s", ex.what() ); return false; } catch ( ... ) { qCritical( "Mapnik Renderer: ### Unknown error" ); return false; } return true; }
int main() { glfwInit(); GLFWwindow* window; window = glfwCreateWindow(800, 600, "PlayerviewMouseTest", NULL, NULL); glfwMakeContextCurrent(window); // You have to give the camera a name cam.setName("Playerview"); cam.setPosition(glm::vec4(1.0, 0.0, 5.0, 1.0)); cam.setNearFar(0.01f, 100.0f); // Set all InputMaps and set one InputMap active iH.setAllInputMaps(cam); iH.changeActiveInputMap("Playerview"); // Callback glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, cursor_pos_callback); glewInit(); // Shader VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/ColorShader3D/ColorShader3D.vert"))); FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/ColorShader3D/colorShader3D.frag"))); ShaderProgram shader(vs, fs); // Renderer OpenGL3Context context; Renderer renderer(context); // Object Teapot teapot; teapot.loadBufferData(); // getting the start time double startTime = glfwGetTime(); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // You have to compute the delta time cam.setSensitivity(glfwGetTime() - startTime); startTime = glfwGetTime(); shader.bind(); // You have to send the uniform matrices of the Pilotview camera to the shader shader.sendMat4("viewMatrix", cam.getViewMatrix()); shader.sendMat4("projectionMatrix", cam.getProjectionMatrix()); teapot.renderGeometry(); shader.unbind(); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return 0; }
VisibleSelection HTMLTextAreaElement::selection() const { if (!renderer() || m_cachedSelectionStart < 0 || m_cachedSelectionEnd < 0) return VisibleSelection(); return toRenderTextControl(renderer())->selection(m_cachedSelectionStart, m_cachedSelectionEnd); }
void SVGInlineTextBox::paintSelectionBackground(PaintInfo& paintInfo) { ASSERT(paintInfo.shouldPaintWithinRoot(renderer())); ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection); ASSERT(truncation() == cNoTruncation); if (renderer()->style()->visibility() != VISIBLE) return; RenderObject* parentRenderer = parent()->renderer(); ASSERT(parentRenderer); ASSERT(!parentRenderer->document()->printing()); // Determine whether or not we're selected. bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection; bool hasSelection = selectionState() != RenderObject::SelectionNone; if (!hasSelection || paintSelectedTextOnly) return; Color backgroundColor = renderer()->selectionBackgroundColor(); if (!backgroundColor.isValid() || !backgroundColor.alpha()) return; RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer()); ASSERT(textRenderer); if (!textShouldBePainted(textRenderer)) return; RenderStyle* style = parentRenderer->style(); ASSERT(style); RenderStyle* selectionStyle = style; if (hasSelection) { selectionStyle = parentRenderer->getCachedPseudoStyle(SELECTION); if (!selectionStyle) selectionStyle = style; } int startPosition, endPosition; selectionStartEnd(startPosition, endPosition); int fragmentStartPosition = 0; int fragmentEndPosition = 0; AffineTransform fragmentTransform; unsigned textFragmentsSize = m_textFragments.size(); for (unsigned i = 0; i < textFragmentsSize; ++i) { SVGTextFragment& fragment = m_textFragments.at(i); ASSERT(!m_paintingResource); fragmentStartPosition = startPosition; fragmentEndPosition = endPosition; if (!mapStartEndPositionsIntoFragmentCoordinates(fragment, fragmentStartPosition, fragmentEndPosition)) continue; GraphicsContextStateSaver stateSaver(*paintInfo.context); fragment.buildFragmentTransform(fragmentTransform); if (!fragmentTransform.isIdentity()) paintInfo.context->concatCTM(fragmentTransform); paintInfo.context->setFillColor(backgroundColor, style->colorSpace()); paintInfo.context->fillRect(selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style), backgroundColor, style->colorSpace()); m_paintingResourceMode = ApplyToDefaultMode; } ASSERT(!m_paintingResource); }
void SVGInlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint&, LayoutUnit, LayoutUnit) { ASSERT(paintInfo.shouldPaintWithinRoot(renderer())); ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection); ASSERT(truncation() == cNoTruncation); if (renderer()->style()->visibility() != VISIBLE) return; // Note: We're explicitely not supporting composition & custom underlines and custom highlighters - unlike InlineTextBox. // If we ever need that for SVG, it's very easy to refactor and reuse the code. RenderObject* parentRenderer = parent()->renderer(); ASSERT(parentRenderer); bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection; bool hasSelection = !parentRenderer->document()->printing() && selectionState() != RenderObject::SelectionNone; if (!hasSelection && paintSelectedTextOnly) return; RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer()); ASSERT(textRenderer); if (!textShouldBePainted(textRenderer)) return; RenderStyle* style = parentRenderer->style(); ASSERT(style); const SVGRenderStyle* svgStyle = style->svgStyle(); ASSERT(svgStyle); bool hasFill = svgStyle->hasFill(); bool hasVisibleStroke = svgStyle->hasVisibleStroke(); RenderStyle* selectionStyle = style; if (hasSelection) { selectionStyle = parentRenderer->getCachedPseudoStyle(SELECTION); if (selectionStyle) { const SVGRenderStyle* svgSelectionStyle = selectionStyle->svgStyle(); ASSERT(svgSelectionStyle); if (!hasFill) hasFill = svgSelectionStyle->hasFill(); if (!hasVisibleStroke) hasVisibleStroke = svgSelectionStyle->hasVisibleStroke(); } else selectionStyle = style; } if (textRenderer->frame() && textRenderer->frame()->view() && textRenderer->frame()->view()->paintBehavior() & PaintBehaviorRenderingSVGMask) { hasFill = true; hasVisibleStroke = false; } AffineTransform fragmentTransform; unsigned textFragmentsSize = m_textFragments.size(); for (unsigned i = 0; i < textFragmentsSize; ++i) { SVGTextFragment& fragment = m_textFragments.at(i); ASSERT(!m_paintingResource); GraphicsContextStateSaver stateSaver(*paintInfo.context); fragment.buildFragmentTransform(fragmentTransform); if (!fragmentTransform.isIdentity()) paintInfo.context->concatCTM(fragmentTransform); // Spec: All text decorations except line-through should be drawn before the text is filled and stroked; thus, the text is rendered on top of these decorations. int decorations = style->textDecorationsInEffect(); if (decorations & TextDecorationUnderline) paintDecoration(paintInfo.context, TextDecorationUnderline, fragment); if (decorations & TextDecorationOverline) paintDecoration(paintInfo.context, TextDecorationOverline, fragment); // Fill text if (hasFill) { m_paintingResourceMode = ApplyToFillMode | ApplyToTextMode; paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly); } // Stroke text if (hasVisibleStroke) { m_paintingResourceMode = ApplyToStrokeMode | ApplyToTextMode; paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly); } // Spec: Line-through should be drawn after the text is filled and stroked; thus, the line-through is rendered on top of the text. if (decorations & TextDecorationLineThrough) paintDecoration(paintInfo.context, TextDecorationLineThrough, fragment); m_paintingResourceMode = ApplyToDefaultMode; } ASSERT(!m_paintingResource); }
bool render_flipbook( flipbook::flipbook_t *flip, node_t *n, int start, int end, bool mblur, int subsample) { render_cancelled = false; signal_connection_t connection = flip->closed.connect( &cancel_render); std::size_t mem_size = 0; render_context_t new_context = document_t::Instance().composition().current_context(); new_context.mode = flipbook_render; new_context.result_node = n; new_context.subsample = subsample; new_context.motion_blur_extra_samples = 0; new_context.motion_blur_shutter_factor = mblur ? 1 : 0; // recalc the domain, in case this is our first render n->recursive_calc_domain( new_context); image::image_t img( n->domain().size().x + 1, n->domain().size().y + 1); for( int i = start; i <= end; ++i) { try { new_context.time = i; renderer_t renderer( new_context, true); renderer.render(); // find the amount of memory required to store a frame. // not the most efficient way of doing it, but it's done only once. if( mem_size == 0) { // copy the renderer result to our buffer boost::gil::fill_pixels( boost::gil::view( img), image::pixel_t( 0, 0, 0, 0)); Imath::Box2i area( intersect( n->domain(), n->defined())); if( !area.isEmpty()) { boost::gil::copy_pixels( n->const_subimage_view( area), boost::gil::subimage_view( boost::gil::view( img), area.min.x - n->domain().min.x, area.min.y - n->domain().min.y, area.size().x + 1, area.size().y + 1)); } Imf::Header header = Imf::Header( renderer.domain().size().x + 1, renderer.domain().size().y + 1); header.compression() = Imf::B44_COMPRESSION; imageio::imf_null_ostream os; imageio::write_half_rgb_exr( os, header, boost::gil::const_view( img)); mem_size = os.size(); std::cout << "Flipbook: frame size = " << mem_size / 1024 << " kb \n"; } std::auto_ptr<imageio::imf_memory_ostream> os( new imageio::imf_memory_ostream( mem_size)); if( !os.get()) { // out of memory connection.disconnect(); return true; } // copy the renderer result to our buffer boost::gil::fill_pixels( boost::gil::view( img), image::pixel_t( 0, 0, 0, 0)); Imath::Box2i area( intersect( n->domain(), n->defined())); if( !area.isEmpty()) { boost::gil::copy_pixels( n->const_subimage_view( area), boost::gil::subimage_view( boost::gil::view( img), area.min.x - n->domain().min.x, area.min.y - n->domain().min.y, area.size().x + 1, area.size().y + 1)); } Imf::Header header = Imf::Header( renderer.domain().size().x + 1, renderer.domain().size().y + 1); header.compression() = Imf::B44_COMPRESSION; imageio::write_half_rgb_exr( *os, header, boost::gil::const_view( img)); if( render_cancelled) { connection.disconnect(); return false; } flip->add_frame( os); } catch( ...) { // TODO: report out of memory here // if we have any frame, then play connection.disconnect(); return !flip->empty(); } } connection.disconnect(); return true; }
bool KatePrinter::print (KateDocument *doc) { QPrinter printer; readSettings(printer); // docname is now always there, including the right Untitled name printer.setDocName(doc->documentName()); KatePrintTextSettings *kpts = new KatePrintTextSettings; KatePrintHeaderFooter *kphf = new KatePrintHeaderFooter; KatePrintLayout *kpl = new KatePrintLayout; QList<QWidget*> tabs; tabs << kpts; tabs << kphf; tabs << kpl; QWidget *parentWidget=doc->widget(); if ( !parentWidget ) parentWidget=QApplication::activeWindow(); QScopedPointer<QPrintDialog> printDialog(KdePrint::createPrintDialog(&printer, KdePrint::SystemSelectsPages, tabs, parentWidget)); if ( doc->activeView()->selection() ) { printer.setPrintRange(QPrinter::Selection); printDialog->setOption(QAbstractPrintDialog::PrintSelection, true); } if ( printDialog->exec() ) { writeSettings(printer); KateRenderer renderer(doc, doc->activeKateView()); renderer.config()->setSchema (kpl->colorScheme()); renderer.setPrinterFriendly(true); QPainter paint( &printer ); /* * We work in tree cycles: * 1) initialize variables and retrieve print settings * 2) prepare data according to those settings * 3) draw to the printer */ uint pdmWidth = printer.width(); uint pdmHeight = printer.height(); int y = 0; uint xstart = 0; // beginning point for painting lines uint lineCount = 0; uint maxWidth = pdmWidth; int headerWidth = pdmWidth; int startCol = 0; int endCol = 0; bool pageStarted = true; int remainder = 0; // remaining sublines from a wrapped line (for the top of a new page) // Text Settings Page bool selectionOnly = (printDialog->printRange() == QAbstractPrintDialog::Selection); bool useGuide = kpts->printGuide(); bool printLineNumbers = kpts->printLineNumbers(); uint lineNumberWidth( 0 ); // Header/Footer Page QFont headerFont(kphf->font()); // used for header/footer bool useHeader = kphf->useHeader(); QColor headerBgColor(kphf->headerBackground()); QColor headerFgColor(kphf->headerForeground()); uint headerHeight( 0 ); // further init only if needed QStringList headerTagList; // do bool headerDrawBg = false; // do bool useFooter = kphf->useFooter(); QColor footerBgColor(kphf->footerBackground()); QColor footerFgColor(kphf->footerForeground()); uint footerHeight( 0 ); // further init only if needed QStringList footerTagList; // do bool footerDrawBg = false; // do // Layout Page renderer.config()->setSchema( kpl->colorScheme() ); bool useBackground = kpl->useBackground(); bool useBox = kpl->useBox(); int boxWidth(kpl->boxWidth()); QColor boxColor(kpl->boxColor()); int innerMargin = useBox ? kpl->boxMargin() : 6; // Post initialization int maxHeight = (useBox ? pdmHeight-innerMargin : pdmHeight); uint currentPage( 1 ); uint lastline = doc->lastLine(); // necessary to print selection only uint firstline( 0 ); const int fontHeight = renderer.fontHeight(); KTextEditor::Range selectionRange; /* * Now on for preparations... * during preparations, variable names starting with a "_" means * those variables are local to the enclosing block. */ { if ( selectionOnly ) { // set a line range from the first selected line to the last selectionRange = doc->activeView()->selectionRange(); firstline = selectionRange.start().line(); lastline = selectionRange.end().line(); lineCount = firstline; } if ( printLineNumbers ) { // figure out the horiizontal space required QString s( QString("%1 ").arg( doc->lines() ) ); s.fill('5', -1); // some non-fixed fonts haven't equally wide numbers // FIXME calculate which is actually the widest... lineNumberWidth = renderer.currentFontMetrics().width( s ); // a small space between the line numbers and the text int _adj = renderer.currentFontMetrics().width( "5" ); // adjust available width and set horizontal start point for data maxWidth -= (lineNumberWidth + _adj); xstart += lineNumberWidth + _adj; } if ( useHeader || useFooter ) { // Set up a tag map // This retrieves all tags, ued or not, but // none of theese operations should be expensive, // and searcing each tag in the format strings is avoided. QDateTime dt = QDateTime::currentDateTime(); QMap<QString,QString> tags; KUser u (KUser::UseRealUserID); tags["u"] = u.loginName(); tags["d"] = KGlobal::locale()->formatDateTime(dt, KLocale::ShortDate); tags["D"] = KGlobal::locale()->formatDateTime(dt, KLocale::LongDate); tags["h"] = KGlobal::locale()->formatTime(dt.time(), false); tags["y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::ShortDate); tags["Y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::LongDate); tags["f"] = doc->url().fileName(); tags["U"] = doc->url().prettyUrl(); if ( selectionOnly ) { QString s( i18n("(Selection of) ") ); tags["f"].prepend( s ); tags["U"].prepend( s ); } QRegExp reTags( "%([dDfUhuyY])" ); // TODO tjeck for "%%<TAG>" if (useHeader) { headerDrawBg = kphf->useHeaderBackground(); headerHeight = QFontMetrics( headerFont ).height(); if ( useBox || headerDrawBg ) headerHeight += innerMargin * 2; else headerHeight += 1 + QFontMetrics( headerFont ).leading(); headerTagList = kphf->headerFormat(); QMutableStringListIterator it(headerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!headerBgColor.isValid()) headerBgColor = Qt::lightGray; if (!headerFgColor.isValid()) headerFgColor = Qt::black; } if (useFooter) { footerDrawBg = kphf->useFooterBackground(); footerHeight = QFontMetrics( headerFont ).height(); if ( useBox || footerDrawBg ) footerHeight += 2*innerMargin; else footerHeight += 1; // line only footerTagList = kphf->footerFormat(); QMutableStringListIterator it(footerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!footerBgColor.isValid()) footerBgColor = Qt::lightGray; if (!footerFgColor.isValid()) footerFgColor = Qt::black; // adjust maxheight, so we can know when/where to print footer maxHeight -= footerHeight; } } // if ( useHeader || useFooter ) if ( useBackground ) { if ( ! useBox ) { xstart += innerMargin; maxWidth -= innerMargin * 2; } } if ( useBox ) { if (!boxColor.isValid()) boxColor = Qt::black; if (boxWidth < 1) // shouldn't be pssible no more! boxWidth = 1; // set maxwidth to something sensible maxWidth -= ( ( boxWidth + innerMargin ) * 2 ); xstart += boxWidth + innerMargin; // maxheight too.. maxHeight -= boxWidth; } else boxWidth = 0; // now that we know the vertical amount of space needed, // it is possible to calculate the total number of pages // if needed, that is if any header/footer tag contains "%P". if ( !headerTagList.filter("%P").isEmpty() || !footerTagList.filter("%P").isEmpty() ) { kDebug(13020)<<"'%P' found! calculating number of pages..."; int pageHeight = maxHeight; if ( useHeader ) pageHeight -= ( headerHeight + innerMargin ); if ( useFooter ) pageHeight -= innerMargin; const int linesPerPage = pageHeight / fontHeight; // kDebug() << "Lines per page:" << linesPerPage; // calculate total layouted lines in the document int totalLines = 0; // TODO: right now ignores selection printing for (int i = firstline; i <= lastline; ++i) { KateLineLayoutPtr rangeptr(new KateLineLayout(doc)); rangeptr->setLine(i); renderer.layoutLine(rangeptr, (int)maxWidth, false); totalLines += rangeptr->viewLineCount(); } int totalPages = (totalLines / linesPerPage) + ((totalLines % linesPerPage) > 0 ? 1 : 0); // kDebug() << "_______ pages:" << (totalLines / linesPerPage); // kDebug() << "________ rest:" << (totalLines % linesPerPage); // TODO: add space for guide if required // if ( useGuide ) // _lt += (guideHeight + (fontHeight /2)) / fontHeight; // substitute both tag lists QString re("%P"); QStringList::Iterator it; for ( it=headerTagList.begin(); it!=headerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); for ( it=footerTagList.begin(); it!=footerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); } } // end prepare block /* On to draw something :-) */ while ( lineCount <= lastline ) { startCol = 0; endCol = 0; if ( y + fontHeight > maxHeight ) { kDebug(13020)<<"Starting new page,"<<lineCount<<"lines up to now."; printer.newPage(); paint.resetTransform(); currentPage++; pageStarted = true; y=0; } if ( pageStarted ) { if ( useHeader ) { paint.setPen(headerFgColor); paint.setFont(headerFont); if ( headerDrawBg ) paint.fillRect(0, 0, headerWidth, headerHeight, headerBgColor); if (headerTagList.count() == 3) { int valign = ( (useBox||headerDrawBg||useBackground) ? Qt::AlignVCenter : Qt::AlignTop ); int align = valign|Qt::AlignLeft; int marg = ( useBox || headerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = headerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, 0, headerWidth-(marg*2), headerHeight, align, s); align = valign|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } if ( ! ( headerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate header from contents { paint.drawLine( 0, headerHeight-1, headerWidth, headerHeight-1 ); //y += 1; now included in headerHeight } y += headerHeight + innerMargin; } if ( useFooter ) { paint.setPen(footerFgColor); if ( ! ( footerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate footer from contents paint.drawLine( 0, maxHeight + innerMargin - 1, headerWidth, maxHeight + innerMargin - 1 ); if ( footerDrawBg ) paint.fillRect(0, maxHeight+innerMargin+boxWidth, headerWidth, footerHeight, footerBgColor); if (footerTagList.count() == 3) { int align = Qt::AlignVCenter|Qt::AlignLeft; int marg = ( useBox || footerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = footerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, maxHeight+innerMargin, headerWidth-(marg*2), footerHeight, align, s); align = Qt::AlignVCenter|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } } // done footer if ( useBackground ) { // If we have a box, or the header/footer has backgrounds, we want to paint // to the border of those. Otherwise just the contents area. int _y = y, _h = maxHeight - y; if ( useBox ) { _y -= innerMargin; _h += 2 * innerMargin; } else { if ( headerDrawBg ) { _y -= innerMargin; _h += innerMargin; } if ( footerDrawBg ) { _h += innerMargin; } } paint.fillRect( 0, _y, pdmWidth, _h, renderer.config()->backgroundColor()); } if ( useBox ) { paint.setPen(QPen(boxColor, boxWidth)); paint.drawRect(0, 0, pdmWidth, pdmHeight); if (useHeader) paint.drawLine(0, headerHeight, headerWidth, headerHeight); else y += innerMargin; if ( useFooter ) // drawline is not trustable, grr. paint.fillRect( 0, maxHeight+innerMargin, headerWidth, boxWidth, boxColor ); } if ( useGuide && currentPage == 1 ) { // FIXME - this may span more pages... // draw a box unless we have boxes, in which case we end with a box line int _ystart = y; QString _hlName = doc->highlight()->name(); QList<KateExtendedAttribute::Ptr> _attributes; // list of highlight attributes for the legend doc->highlight()->getKateExtendedAttributeList(kpl->colorScheme(), _attributes); KateAttributeList _defaultAttributes; KateHlManager::self()->getDefaults ( renderer.config()->schema(), _defaultAttributes ); QColor _defaultPen = _defaultAttributes.at(0)->foreground().color(); paint.setPen(_defaultPen); int _marg = 0; if ( useBox ) _marg += (2*boxWidth) + (2*innerMargin); else { if ( useBackground ) _marg += 2*innerMargin; _marg += 1; y += 1 + innerMargin; } // draw a title string QFont _titleFont = renderer.config()->font(); _titleFont.setBold(true); paint.setFont( _titleFont ); QRect _r; paint.drawText( QRect(_marg, y, pdmWidth-(2*_marg), maxHeight - y), Qt::AlignTop|Qt::AlignHCenter, i18n("Typographical Conventions for %1", _hlName ), &_r ); int _w = pdmWidth - (_marg*2) - (innerMargin*2); int _x = _marg + innerMargin; y += _r.height() + innerMargin; paint.drawLine( _x, y, _x + _w, y ); y += 1 + innerMargin; int _widest( 0 ); foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) _widest = qMax(QFontMetrics(attribute->font()).width(attribute->name().section(':',1,1)), _widest); int _guideCols = _w/( _widest + innerMargin ); // draw attrib names using their styles int _cw = _w/_guideCols; int _i(0); _titleFont.setUnderline(true); QString _currentHlName; foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) { QString _hl = attribute->name().section(':',0,0); QString _name = attribute->name().section(':',1,1); if ( _hl != _hlName && _hl != _currentHlName ) { _currentHlName = _hl; if ( _i%_guideCols ) y += fontHeight; y += innerMargin; paint.setFont(_titleFont); paint.setPen(_defaultPen); paint.drawText( _x, y, _w, fontHeight, Qt::AlignTop, _hl + ' ' + i18n("text") ); y += fontHeight; _i = 0; } KTextEditor::Attribute _attr = *_defaultAttributes[attribute->defaultStyleIndex()]; _attr += *attribute; paint.setPen( _attr.foreground().color() ); paint.setFont( _attr.font() ); if (_attr.hasProperty(QTextFormat::BackgroundBrush) ) { QRect _rect = QFontMetrics(_attr.font()).boundingRect(_name); _rect.moveTo(_x + ((_i%_guideCols)*_cw), y); paint.fillRect(_rect, _attr.background() ); } paint.drawText(( _x + ((_i%_guideCols)*_cw)), y, _cw, fontHeight, Qt::AlignTop, _name ); _i++; if ( _i && ! ( _i%_guideCols ) ) y += fontHeight; } if ( _i%_guideCols ) y += fontHeight;// last row not full // draw a box around the legend paint.setPen ( _defaultPen ); if ( useBox ) paint.fillRect( 0, y+innerMargin, headerWidth, boxWidth, boxColor ); else { _marg -=1; paint.drawRect( _marg, _ystart, pdmWidth-(2*_marg), y-_ystart+innerMargin ); } y += ( useBox ? boxWidth : 1 ) + (innerMargin*2); } // useGuide paint.translate(xstart,y); pageStarted = false; } // pageStarted; move on to contents:)
static void setup_benchmark(sk_tools::PictureBenchmark* benchmark) { sk_tools::PictureRenderer::DrawFilterFlags drawFilters[SkDrawFilter::kTypeCount]; sk_bzero(drawFilters, sizeof(drawFilters)); if (FLAGS_filter.count() > 0) { const char* filters = FLAGS_filter[0]; const char* colon = strchr(filters, ':'); if (colon) { int32_t type = -1; size_t typeLen = colon - filters; for (size_t tIndex = 0; tIndex < kFilterTypesCount; ++tIndex) { if (typeLen == strlen(gFilterTypes[tIndex]) && !strncmp(filters, gFilterTypes[tIndex], typeLen)) { type = SkToS32(tIndex); break; } } if (type < 0) { SkString err; err.printf("Unknown type for --filter %s\n", filters); gLogger.logError(err); exit(-1); } int flag = -1; size_t flagLen = strlen(filters) - typeLen - 1; for (size_t fIndex = 0; fIndex < kFilterFlagsCount; ++fIndex) { if (flagLen == strlen(gFilterFlags[fIndex]) && !strncmp(colon + 1, gFilterFlags[fIndex], flagLen)) { flag = 1 << fIndex; break; } } if (flag < 0) { SkString err; err.printf("Unknown flag for --filter %s\n", filters); gLogger.logError(err); exit(-1); } for (int index = 0; index < SkDrawFilter::kTypeCount; ++index) { if (type != SkDrawFilter::kTypeCount && index != type) { continue; } drawFilters[index] = (sk_tools::PictureRenderer::DrawFilterFlags) (drawFilters[index] | flag); } } else { SkString err; err.printf("Unknown arg for --filter %s : missing colon\n", filters); gLogger.logError(err); exit(-1); } } if (FLAGS_timers.count() > 0) { size_t index = 0; bool timerWall = false; bool truncatedTimerWall = false; bool timerCpu = false; bool truncatedTimerCpu = false; bool timerGpu = false; while (index < strlen(FLAGS_timers[0])) { switch (FLAGS_timers[0][index]) { case 'w': timerWall = true; break; case 'c': timerCpu = true; break; case 'W': truncatedTimerWall = true; break; case 'C': truncatedTimerCpu = true; break; case 'g': timerGpu = true; break; default: SkDebugf("mystery character\n"); break; } index++; } benchmark->setTimersToShow(timerWall, truncatedTimerWall, timerCpu, truncatedTimerCpu, timerGpu); } SkString errorString; SkAutoTUnref<sk_tools::PictureRenderer> renderer(parseRenderer(errorString, kBench_PictureTool)); if (errorString.size() > 0) { gLogger.logError(errorString); } if (NULL == renderer.get()) { exit(-1); } if (FLAGS_timeIndividualTiles) { if (FLAGS_multi > 1) { gLogger.logError("Cannot time individual tiles with more than one thread.\n"); exit(-1); } sk_tools::TiledPictureRenderer* tiledRenderer = renderer->getTiledRenderer(); if (NULL == tiledRenderer) { gLogger.logError("--timeIndividualTiles requires tiled rendering.\n"); exit(-1); } if (!tiledRenderer->supportsTimingIndividualTiles()) { gLogger.logError("This renderer does not support --timeIndividualTiles.\n"); exit(-1); } benchmark->setTimeIndividualTiles(true); } benchmark->setPurgeDecodedTex(FLAGS_purgeDecodedTex); benchmark->setPreprocess(FLAGS_preprocess); if (FLAGS_readPath.count() < 1) { gLogger.logError(".skp files or directories are required.\n"); exit(-1); } renderer->setDrawFilters(drawFilters, filtersName(drawFilters)); if (FLAGS_logPerIter) { benchmark->setTimerResultType(TimerData::kPerIter_Result); } else if (FLAGS_min) { benchmark->setTimerResultType(TimerData::kMin_Result); } else { benchmark->setTimerResultType(TimerData::kAvg_Result); } benchmark->setRenderer(renderer); benchmark->setRepeats(FLAGS_repeat); benchmark->setWriter(&gWriter); }
float SVGTextContentElement::getComputedTextLength() { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).textLength(); }
int CNSRemoteJobControlApp::Run(void) { const CArgs& args = GetArgs(); IRWRegistry& reg = GetConfig(); if (args["q"]) { string queue = args["q"].AsString(); reg.Set(kNetScheduleAPIDriverName, "queue_name", queue); } if ( args["ns"]) { reg.Set(kNetScheduleAPIDriverName, "client_name", "ns_remote_job_control"); reg.Set(kNetScheduleAPIDriverName, "service", args["ns"].AsString()); reg.Set(kNetScheduleAPIDriverName, "use_permanent_connection", "true"); reg.Set(kNetScheduleAPIDriverName, "use_embedded_storage", "true"); } if ( args["nc"]) { reg.Set(kNetCacheAPIDriverName, "client_name", "ns_remote_job_control"); reg.Set(kNetCacheAPIDriverName, "service", args["nc"].AsString()); } auto_ptr<CNSInfoCollector> info_collector; CNcbiOstream* out = &NcbiCout; if (args["of"]) { out = &args["of"].AsOutputFile(); } CNetCacheAPI nc_api(reg); auto_ptr<CConfig::TParamTree> ptree(CConfig::ConvertRegToTree(reg)); const CConfig::TParamTree* ns_tree = ptree->FindSubNode(kNetScheduleAPIDriverName); if (!ns_tree) NCBI_THROW(CArgException, eInvalidArg, "Could not find \"" + string(kNetScheduleAPIDriverName) + "\" section"); CConfig ns_conf(ns_tree); string queue = ns_conf.GetString(kNetScheduleAPIDriverName, "queue_name", CConfig::eErr_NoThrow, ""); NStr::TruncateSpacesInPlace(queue); if (queue.empty()) queue = "noname"; string service = ns_conf.GetString(kNetScheduleAPIDriverName, "service", CConfig::eErr_NoThrow, ""); NStr::TruncateSpacesInPlace(service); if (service.empty()) NCBI_THROW(CArgException, eInvalidArg, "\"service\" parameter is not set " "neither in config file nor in cmd line"); info_collector.reset(new CNSInfoCollector(queue, service, nc_api)); if (args["stdout"]) { DumpStdStreams(args["stdout"], info_collector.get(), out, false); return 0; } if (args["stderr"]) { DumpStdStreams(args["stderr"], info_collector.get(), out, true); return 0; } auto_ptr<ITagWriter> writer; if (args["render"]) { string type = args["render"].AsString(); if(NStr::CompareNocase(type, "xml") == 0) writer.reset(new CXmlTagWriter(*out)); } if (!writer.get()) writer.reset(new CTextTagWriter(*out)); try { if (args["bid"]) { auto_ptr<CNSInfoRenderer> renderer(new CNSInfoRenderer(*writer, *info_collector)); string id = args["bid"].AsString(); renderer->RenderBlob(id); return 0; } CNSInfoRenderer::TFlags flags = 0; if (args["attr"]) { const CArgValue::TStringArray& strings = args["attr"].GetStringList(); CArgValue::TStringArray::const_iterator it; for( it = strings.begin(); it != strings.end(); ++it) { if (NStr::CompareNocase(*it, "minmal") == 0) flags = CNSInfoRenderer::eMinimal; if (NStr::CompareNocase(*it, "standard") == 0) flags = CNSInfoRenderer::eStandard; if (NStr::CompareNocase(*it, "full") == 0) flags = CNSInfoRenderer::eFull; if (NStr::CompareNocase(*it, "status") == 0) flags |= CNSInfoRenderer::eStatus; if (NStr::CompareNocase(*it, "progress") == 0) flags |= CNSInfoRenderer::eProgress; if (NStr::CompareNocase(*it, "retcode") == 0) flags |= CNSInfoRenderer::eRetCode; if (NStr::CompareNocase(*it, "cmdline") == 0) flags |= CNSInfoRenderer::eCmdLine; if (NStr::CompareNocase(*it, "stdin") == 0) flags |= CNSInfoRenderer::eStdIn; if (NStr::CompareNocase(*it, "stdout") == 0) flags |= CNSInfoRenderer::eStdOut; if (NStr::CompareNocase(*it, "stderr") == 0) flags |= CNSInfoRenderer::eStdErr; if (NStr::CompareNocase(*it, "raw_input") == 0) flags |= CNSInfoRenderer::eRawInput; if (NStr::CompareNocase(*it, "raw_output") == 0) flags |= CNSInfoRenderer::eRawOutput; } } auto_ptr<CNSInfoRenderer> renderer(new CNSInfoRenderer(*writer, *info_collector)); if (args["jid"]) { string jid = args["jid"].AsString(); renderer->RenderJob(jid, flags); } else if (args["wnlist"]) { renderer->RenderWNodes(flags); } else if (args["qlist"]) { renderer->RenderQueueList(); } else if (args["cancel"]) { string jid = args["cancel"].AsString(); info_collector->CancelJob(jid); } else if (args["cmd"]) { string cmd = args["cmd"].AsString(); if (NStr::CompareNocase(cmd, "shutdown_nodes") == 0) { CWNodeShutdownAction action(CNetScheduleAdmin::eShutdownImmediate); info_collector->TraverseNodes(action); } else if (NStr::CompareNocase(cmd, "kill_nodes") == 0) { CWNodeShutdownAction action(CNetScheduleAdmin::eDie); info_collector->TraverseNodes(action); } } } catch (exception& ex) { writer->WriteBeginTag("Error"); writer->WriteText(ex.what()); writer->WriteCloseTag("Error"); return 1; } catch (...) { writer->WriteTag("Error", "Unknown error"); return 2; } return 0; }
int SVGTextContentElement::getCharNumAtPosition(const FloatPoint& point) { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).characterNumberAtPosition(point); }
IntRect EllipsisBox::selectionRect() { RenderStyle* style = renderer().style(isFirstLineStyle()); const Font& font = style->font(); return enclosingIntRect(font.selectionRectForText(RenderBlockFlow::constructTextRun(&renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), IntPoint(logicalLeft(), logicalTop() + root().selectionTopAdjustedForPrecedingBlock()), root().selectionHeightAdjustedForPrecedingBlock())); }
GlyphData SVGTextRunRenderingContext::glyphDataForCharacter(const Font& font, WidthIterator& iterator, UChar32 character, bool mirror, int currentCharacter, unsigned& advanceLength, String& normalizedSpacesStringCache) { const SimpleFontData* primaryFont = font.primaryFont(); ASSERT(primaryFont); std::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 from the 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, normalizedSpacesStringCache)) 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; }
int main() { Player geko("Geko", glm::vec3(10.0, 10.0, 10.0)); // Start Konifguration - Window, Context, Camera and Callbacks // glfwInit(); Window testWindow(500, 50, 800, 600, "testWindow"); glfwMakeContextCurrent(testWindow.getWindow()); cam.setKeySpeed(2.0); cam.setNearFar(0.01, 100); //Callback for Camera and Player glfwSetKeyCallback(testWindow.getWindow(), key_callback); glewInit(); // Shader and Renderer Initialization // //Shader for Objects VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/Vertex-Shaders/TextureShader3D.vert"))); FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/Fragment-Shaders/TextureShader3D.frag"))); ShaderProgram shader(vs, fs); //Shader for a Skybox VertexShader vsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.vert"))); FragmentShader fsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.frag"))); ShaderProgram shaderSkybox(vsSkybox, fsSkybox); //Renderer with context OpenGL3Context context; Renderer renderer(context); //Level and Scene Level testLevel("testLevel"); Scene testScene("testScene"); testLevel.addScene(&testScene); testLevel.changeScene("testScene"); //Add Camera to scenegraph testScene.getScenegraph()->addCamera(&cam); testScene.getScenegraph()->getCamera("PlayerViewCam"); testScene.getScenegraph()->setActiveCamera("PlayerViewCam"); //Set all InputMaps and set one InputMap active iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera())); iH.changeActiveInputMap("Object"); iH.getActiveInputMap()->update(geko); // ============================================================== // == Object (ant, afraid) ====================================== // ============================================================== Teapot teaAnt; Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp"); //AntMesh antMesh; //Node aiNodeFlick("Flick"); //aiNodeFlick.addGeometry(&teaAnt); //aiNodeFlick.addTexture(&texCV); //testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNodeFlick); //AI ant_Flick; //ant_Flick.setAntAfraid(); //aiNodeFlick.ssetObject(&ant_Flick); // ============================================================== // == Object (ant, aggressiv) =================================== // ============================================================== AntMesh antMesh; //Node aiNodeFlack("Flack"); //aiNodeFlack.addGeometry(&teaAnt); //aiNodeFlack.addGeometry(&antMesh); //aiNodeFlack.addTexture(&texCV); //testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNodeFlack); //AI ant_Flack; //ant_Flack.setAntAggressiv(); //aiNodeFlack.setObject(&ant_Flack); // ============================================================== // == Object (Tree) ============================================= // ============================================================== Texture texBrick((char*)RESOURCES_PATH "/brick.bmp"); //TreeMesh treeMesh; Teapot teaTree; TreeMesh treeMesh; Node treeNode("CookieTree"); StaticObject tree; tree.setTree(); treeNode.setObject(&tree); treeNode.addTexture(&texCV); treeNode.addGeometry(&treeMesh); glm::vec3 posFood(10.0, 0.0, -5.0); treeNode.addTranslation(posFood); treeNode.getBoundingSphere()->radius = 2.0; testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode); // ============================================================== // == Player ==================================================== // ============================================================== Teapot teaPlayer; GekoMesh gekomesh; // Texture texBrick((char*)RESOURCES_PATH "/brick.bmp"); Node playerNode("Player"); playerNode.addTexture(&texBrick); playerNode.setObject(&geko); //playerNode.addGeometry(&teaPlayer); playerNode.addGeometry(&gekomesh); playerNode.setCamera(&cam); geko.setPosition(glm::vec3(10.0, 0.0, 10.0)); //Add the node to the Scene testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode); // ============================================================== // == Questsystem ==================================================== // ============================================================== //QuestHandler questhandler; Quest questCollect(1); questCollect.setActive(true); Goal_Collect goalCollect(1); Goal_Collect goalCollect3(3); questCollect.addGoal(&goalCollect); questCollect.addGoal(&goalCollect3); Quest questCollect2(2); questCollect2.setActive(true); Goal_Collect goalCollect2(2); questCollect2.addGoal(&goalCollect2); goalCollect.setGoalCount(50); goalCollect2.setGoalCount(50); goalCollect3.setGoalCount(50); goalCollect.setItemType(ItemType::BRANCH); goalCollect2.setItemType(ItemType::BRANCH); goalCollect3.setItemType(ItemType::COOKIE); testLevel.getQuestHandler()->addQuest(&questCollect); testLevel.getQuestHandler()->addQuest(&questCollect2); /*questhandler.addQuest(&questCollect); questhandler.addQuest(&questCollect2);*/ //std::cout << "GRÖßE DES QUESTHANDLERS : " << questhandler.getQuests().size() << std::endl; // ============================================================== // == Collision, FightSystem===================================== // ============================================================== // Bounding Box creation for the objects and collision test // CollisionTest collision; FightSystem fight; //===================================================================// //==================Setting up the Observers========================// //==================================================================// ObjectObserver aiObserver(&testLevel); //ant_Flick.addObserver(&aiObserver); //ant_Flack.addObserver(&aiObserver); ObjectObserver playerObserver(&testLevel); geko.addObserver(&playerObserver); CollisionObserver colObserver(&testLevel); collision.addObserver(&colObserver); GravityObserver gravityObserver(&testLevel); collision.addObserver(&gravityObserver); SoundObserver soundObserver(&testLevel); // ============================================================== // == Object (Anthome) ========================================== // ============================================================== //TreeMesh treeMesh; AntHomeMesh homeMesh; Node homeNode("AntHome"); StaticObject home; //home.setTree(); homeNode.setObject(&home); homeNode.addTexture(&texBrick); homeNode.addGeometry(&homeMesh); glm::vec3 posHome(1.0, 0.0, 1.0); homeNode.addTranslation(posHome); homeNode.getBoundingSphere()->radius = 0.5; testScene.getScenegraph()->getRootNode()->addChildrenNode(&homeNode); glm::vec3 posFood2(10.0, 0.0, -5.0); glm::vec3 posSpawn(3.0, 0.0, 3.0); glm::vec3 posDefaultPlayer(0.0, 0.0, 0.0); DecisionTree *aggressivedecisionTree = new DecisionTree(); aggressivedecisionTree->setAntTreeAggressiv(); DecisionTree *afraidDecisionTree = new DecisionTree(); afraidDecisionTree->setAntTreeAfraid(); Graph<AStarNode, AStarAlgorithm>* antAggressiveGraph = new Graph<AStarNode, AStarAlgorithm>(); antAggressiveGraph->setExampleAntAfraid(posSpawn, posFood2, posDefaultPlayer); Graph<AStarNode, AStarAlgorithm>* antAfraidGraph = new Graph<AStarNode, AStarAlgorithm>(); antAfraidGraph->setExampleAntAfraid(posSpawn, posFood, posDefaultPlayer); //AntHome antHome(posSpawn, antMesh, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph); ////antHome.generateGuards(5, &aiObserver); //antHome.generateWorkers(1, &aiObserver); SoundFileHandler sfh(1000); AntHome antHome(posSpawn, &sfh, antMesh, &soundObserver, &playerObserver, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph); antHome.generateWorkers(5, testScene.getScenegraph()->getRootNode()); antHome.addAntsToSceneGraph(testScene.getScenegraph()->getRootNode()); collision.collectNodes(testScene.getScenegraph()->getRootNode()); float lastTime = glfwGetTime(); int i = 0; while (!glfwWindowShouldClose(testWindow.getWindow())) { i++; if (i == 30){ i++; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float currentTime = glfwGetTime(); float deltaTime = currentTime - lastTime; lastTime = currentTime; collision.update(); antHome.updateAnts(); antHome.printPosWorkers(); /* ant_Flick.update(); ant_Flack.update();*/ geko.update(); geko.setDeltaTime(currentTime); renderer.renderScene(testScene, testWindow); } glfwDestroyWindow(testWindow.getWindow()); glfwTerminate(); return 0; }
void RootInlineBox::paintEllipsisBox(RenderObject::PaintInfo& paintInfo, int tx, int ty) const { if (m_hasEllipsisBox && renderer()->shouldPaintWithinRoot(paintInfo) && renderer()->style()->visibility() == VISIBLE && paintInfo.phase == PaintPhaseForeground) ellipsisBox()->paint(paintInfo, tx, ty); }
//! Renders a OSM layer onto the given cairo surface void Renderer::renderObjects(CairoLayer layers[], RenderAttributes& map, const Cairo::Matrix& transform, std::vector<NodeId>& nodes, std::vector<WayId>& ways, std::vector<RelId>& relations, std::list<shared_ptr<Label>>& labels, std::list<shared_ptr<Shield>>& shields, AssetCache& cache) const { const boost::unordered_map<WayId, Style*> &wayStyles = map.getWayMap(); const boost::unordered_map<NodeId, Style*> &nodeStyles = map.getNodeMap(); const boost::unordered_map<RelId, Style*> &relationStyles = map.getRelationMap(); /* find min and max z_index */ int minZ = 0; int maxZ = 0; if (ways.size() > 0) { minZ = std::min(minZ, wayStyles.at(ways.front())->z_index); maxZ = std::max(maxZ, wayStyles.at(ways.back())->z_index); } if (nodes.size() > 0) { minZ = std::min(minZ, nodeStyles.at(nodes.front())->z_index); maxZ = std::max(maxZ, nodeStyles.at(nodes.back())->z_index); } if (relations.size() > 0) { minZ = std::min(minZ, relationStyles.at(relations.front())->z_index); maxZ = std::max(maxZ, relationStyles.at(relations.back())->z_index); } auto rid = relations.begin(); auto wid = ways.begin(); auto nid = nodes.begin(); int nextZ; // used to skip empty z-index int layer = minZ / 100; // z-index = osm_layer * 100 + mapcss_z_index for (int z = minZ; z <= maxZ; z = nextZ) { if (z/100 != layer) { layer = z/100; compositeLayers(layers); } // if nextZ is not overwritten we have reached the end nextZ = INT_MAX; for (; rid != relations.end(); rid++) { const Style* s = relationStyles.at(*rid); if (s->z_index > z) { nextZ = std::min(nextZ, s->z_index); break; } RelationRenderer renderer(data, *rid, s, transform); renderer.fill(layers[LAYER_FILL].cr, cache); } for (; wid != ways.end(); wid++) { const Style* s = wayStyles.at(*wid); if (s->z_index > z) { nextZ = std::min(nextZ, s->z_index); break; } WayRenderer renderer(data, *wid, s, transform); renderer.fill(layers[LAYER_FILL].cr, cache); renderer.casing(layers[LAYER_CASING].cr); renderer.stroke(layers[LAYER_STROKE].cr, cache); renderer.label(layers[LAYER_LABELS].cr, labels, cache); renderer.shield(layers[LAYER_LABELS].cr, shields, cache); } for (; nid != nodes.end(); nid++) { const Style* s = nodeStyles.at(*nid); if (s->z_index > z) { nextZ = std::min(nextZ, s->z_index); break; } NodeRenderer renderer(data, *nid, s, transform); renderer.casing(layers[LAYER_CASING].cr); renderer.stroke(layers[LAYER_STROKE].cr); renderer.label(layers[LAYER_LABELS].cr, labels, cache); renderer.shield(layers[LAYER_LABELS].cr, shields, cache); renderer.icon(layers[LAYER_ICONS].cr, cache); } } }
void WMLInputElement::select() { if (RenderTextControl* r = toRenderTextControl(renderer())) setSelectionRange(this, 0, r->text().length()); }
void SvgIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode /*mode*/, QIcon::State /*state*/) { QSvgRenderer renderer(svgData); renderer.render(painter, rect); }
vtkCamera * RendererImplementationBase3D::camera(unsigned int subViewIndex) { return renderer(subViewIndex)->GetActiveCamera(); }
void EntitiesEditor::drawContents(Renderer2D &out) const { m_view.updateVisibility(); SceneRenderer renderer(clippedRect(), m_view.pos()); { vector<int> visible_ids; visible_ids.reserve(1024); m_tile_map.findAll(visible_ids, renderer.targetRect(), Flags::all | Flags::visible); for(int i = 0; i < (int)visible_ids.size(); i++) { auto &object = m_tile_map[visible_ids[i]]; int3 pos(object.bbox.min); object.ptr->addToRender(renderer, pos, Color::white); } visible_ids.clear(); m_entity_map.findAll(visible_ids, renderer.targetRect(), Flags::all | Flags::visible); vector<char> selection_map(m_entity_map.size(), 0); vector<float3> old_positions(m_selected_ids.size()); for(int n = 0; n < (int)m_selected_ids.size(); n++) { selection_map[m_selected_ids[n]] = 1; visible_ids.push_back(m_selected_ids[n]); if(m_is_moving) { auto &object = m_entity_map[m_selected_ids[n]]; old_positions[n] = object.ptr->pos(); object.ptr->setPos(old_positions[n] + float3(m_move_offset)); m_entity_map.update(m_selected_ids[n]); } } sort(visible_ids.begin(), visible_ids.end()); visible_ids.resize(std::unique(visible_ids.begin(), visible_ids.end()) - visible_ids.begin()); for(int n = 0; n < (int)visible_ids.size(); n++) { auto &object = m_entity_map[visible_ids[n]]; float3 old_pos = object.ptr->pos(); bool is_selected = selection_map[visible_ids[n]]; FBox bbox = object.ptr->boundingBox(); if(object.ptr->typeId() == EntityId::trigger) { renderer.addBox(bbox, Color(Color::green, 64), true); renderer.addBox(FBox(bbox.min + float3(0.1, 0.1, 0.1), bbox.max - float3(0.1, 0.1, 0.1)), Color::green); } else { object.ptr->addToRender(renderer); } bool is_colliding = m_tile_map.findAny(bbox) != -1 || m_entity_map.findAny(bbox, visible_ids[n]) != -1; if(is_colliding) renderer.addBox(bbox, Color::red); if(is_selected) { if(!is_colliding) renderer.addBox(bbox, Color::white); FBox overground_box = computeOvergroundBox(bbox); if(!overground_box.isEmpty()) renderer.addBox(overground_box, Color::yellow); } } if(m_is_moving) for(int n = 0; n < (int)m_selected_ids.size(); n++) { auto &object = m_entity_map[m_selected_ids[n]]; object.ptr->setPos(old_positions[n]); m_entity_map.update(m_selected_ids[n]); } } if(m_proto && m_mode == Mode::placing) { m_proto->setPos(m_cursor_pos); m_proto->addToRender(renderer); FBox bbox = m_proto->boundingBox(); bool is_colliding = m_tile_map.findAny(bbox) != -1 || m_entity_map.findAny(bbox) != -1; renderer.addBox(bbox, is_colliding? Color::red : Color::white); if(bbox.max.y == bbox.min.y) bbox.max.y += 1.0f; FBox overground_box = computeOvergroundBox(bbox); if(!overground_box.isEmpty()) renderer.addBox(overground_box, Color::yellow); } renderer.render(); if(m_mode == Mode::selecting && m_is_selecting) out.addRect(m_selection - m_view.pos(), Color::white); out.setScissorRect(clippedRect()); out.setViewPos(-clippedRect().min + m_view.pos()); m_view.drawGrid(out); out.setViewPos(-clippedRect().min); auto font = res::getFont(WindowStyle::fonts[1]); font->draw(out, int2(0, clippedRect().height() - 25), {Color::white, Color::black}, format("Cursor: (%.0f, %.0f, %.0f) Grid: %d Mode: %s\n", m_cursor_pos.x, m_cursor_pos.y, m_cursor_pos.z, m_view.gridHeight(), EntitiesEditorMode::toString(m_mode))); }
int tool_main(int argc, char** argv) { SkCommandLineFlags::SetUsage("Render .skp files."); SkCommandLineFlags::Parse(argc, argv); if (FLAGS_readPath.isEmpty()) { SkDebugf(".skp files or directories are required.\n"); exit(-1); } if (FLAGS_maxComponentDiff < 0 || FLAGS_maxComponentDiff > 256) { SkDebugf("--maxComponentDiff must be between 0 and 256\n"); exit(-1); } if (FLAGS_maxComponentDiff != 256 && !FLAGS_validate) { SkDebugf("--maxComponentDiff requires --validate\n"); exit(-1); } if (FLAGS_writeEncodedImages) { if (FLAGS_writePath.isEmpty()) { SkDebugf("--writeEncodedImages requires --writePath\n"); exit(-1); } if (FLAGS_deferImageDecoding) { SkDebugf("--writeEncodedImages is not compatible with --deferImageDecoding\n"); exit(-1); } } SkString errorString; SkAutoTUnref<sk_tools::PictureRenderer> renderer(parseRenderer(errorString, kRender_PictureTool)); if (errorString.size() > 0) { SkDebugf("%s\n", errorString.c_str()); } if (renderer.get() == nullptr) { exit(-1); } SkAutoGraphics ag; SkString writePath; if (FLAGS_writePath.count() == 1) { writePath.set(FLAGS_writePath[0]); } SkString mismatchPath; if (FLAGS_mismatchPath.count() == 1) { mismatchPath.set(FLAGS_mismatchPath[0]); } sk_tools::ImageResultsAndExpectations jsonSummary; sk_tools::ImageResultsAndExpectations* jsonSummaryPtr = nullptr; if (FLAGS_writeJsonSummaryPath.count() == 1) { jsonSummaryPtr = &jsonSummary; if (FLAGS_readJsonSummaryPath.count() == 1) { SkASSERT(jsonSummary.readExpectationsFile(FLAGS_readJsonSummaryPath[0])); } } int failures = 0; for (int i = 0; i < FLAGS_readPath.count(); i ++) { failures += process_input(FLAGS_readPath[i], &writePath, &mismatchPath, *renderer.get(), jsonSummaryPtr); } if (failures != 0) { SkDebugf("Failed to render %i pictures.\n", failures); return 1; } #if GR_CACHE_STATS && SK_SUPPORT_GPU if (renderer->isUsingGpuDevice()) { GrContext* ctx = renderer->getGrContext(); ctx->printCacheStats(); } #endif #if GR_GPU_STATS && SK_SUPPORT_GPU if (FLAGS_gpuStats && renderer->isUsingGpuDevice()) { renderer->getGrContext()->printGpuStats(); } #endif if (FLAGS_writeJsonSummaryPath.count() == 1) { // If there were any descriptions on the command line, insert them now. for (int i=0; i<FLAGS_descriptions.count(); i++) { SkTArray<SkString> tokens; SkStrSplit(FLAGS_descriptions[i], "=", &tokens); SkASSERT(tokens.count() == 2); jsonSummary.addDescription(tokens[0].c_str(), tokens[1].c_str()); } if (FLAGS_imageBaseGSUrl.count() == 1) { jsonSummary.setImageBaseGSUrl(FLAGS_imageBaseGSUrl[0]); } jsonSummary.writeToFile(FLAGS_writeJsonSummaryPath[0]); } return 0; }
unsigned SVGTextContentElement::getNumberOfChars() { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).numberOfCharacters(); }
Text::~Text() { ASSERT(!renderer()); }
void points(int p[][2], int n) { //Grapic& g = Grapic::singleton(); SDL_RenderDrawPoints(renderer(), ((const SDL_Point*)(p)), n); }