Debian Codegraph @

src/Viewer/splash.cxx

raw symbols SCIP
1 /*
2 * SPDX-FileName: splash.cxx
3 * SPDX-FileComment: draws the initial splash screen. Written by Curtis Olson, started July 1998.
4 * SPDX-FileCopyrightText: Copyright (C) 1997 Michele F. America - [email protected]
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include <config.h>
9
10 #include <osg/BlendFunc>
11 #include <osg/Camera>
12 #include <osg/Depth>
13 #include <osg/Geometry>
14 #include <osg/Node>
15 #include <osg/NodeCallback>
16 #include <osg/NodeVisitor>
17 #include <osg/StateSet>
18 #include <osg/Switch>
19 #include <osg/Texture2D>
20 #include <osg/TextureRectangle>
21 #include <osg/Version>
22
23 #include <osgText/Text>
24 #include <osgText/String>
25 #include <osgDB/ReadFile>
26
27 #include <simgear/compiler.h>
28
29 #include <simgear/debug/logstream.hxx>
30 #include <simgear/math/sg_random.hxx>
31 #include <simgear/misc/sg_path.hxx>
32 #include <simgear/misc/sg_dir.hxx>
33 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
34 #include <simgear/scene/util/OsgUtils.hxx>
35 #include <simgear/props/condition.hxx>
36
37 #include "VRManager.hxx"
38 #include "renderer.hxx"
39 #include "splash.hxx"
40 #include <GUI/gui.h>
41 #include <Main/fg_os.hxx>
42 #include <Main/fg_props.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/locale.hxx>
45 #include <Main/util.hxx>
46 #include <Viewer/CameraGroup.hxx>
47
48 #include <sstream>
49
50
51 static const char* LICENSE_URL_TEXT = "Licensed under the GNU GPL. See https://www.flightgear.org for more information";
52
53 using namespace std::string_literals;
54 using namespace simgear;
55
56 class SplashScreenUpdateCallback : public osg::NodeCallback {
57 public:
58 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
59 {
60 SplashScreen* screen = static_cast<SplashScreen*>(node);
61 screen->doUpdate();
62 traverse(node, nv);
63 }
64 };
65
66 SplashScreen::SplashScreen() :
67 _splashAlphaNode(fgGetNode("/sim/startup/splash-alpha", true))
68 {
69 #ifdef ENABLE_OSGXR
70 uint32_t splashW = 1920, splashH = 1080;
71 float aspect = (float)splashW / splashH;
72 _splashSwapchain = new osgXR::Swapchain(splashW, splashH);
73 _splashSwapchain->setAlphaBits(8);
74 _splashSwapchain->allowRGBEncoding(osgXR::Swapchain::Encoding::ENCODING_SRGB);
75 _splashLayer = new osgXR::CompositionLayerQuad(flightgear::VRManager::instance());
76 _splashLayer->setSubImage(_splashSwapchain);
77 _splashLayer->setSize(osg::Vec2f(aspect, 1.0f));
78 _splashLayer->setPosition(osg::Vec3f(0, 0, -2.0f));
79 _splashLayer->setAlphaMode(osgXR::CompositionLayer::BLEND_ALPHA_UNPREMULT);
80 #endif
81
82 const std::string vertex_source =
83 "#version 330 core\n"
84 "\n"
85 "layout(location = 0) in vec4 pos;\n"
86 "layout(location = 3) in vec4 multitexcoord0;\n"
87 "\n"
88 "out vec2 texcoord;\n"
89 "\n"
90 "uniform mat4 osg_ModelViewProjectionMatrix;\n"
91 "\n"
92 "void main()\n"
93 "{\n"
94 " gl_Position = osg_ModelViewProjectionMatrix * pos;\n"
95 " texcoord = multitexcoord0.st;\n"
96 "}\n";
97 osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertex_source);
98
99 const std::string fragment_source =
100 "#version 330 core\n"
101 "\n"
102 "layout(location = 0) out vec4 fragColor;\n"
103 "\n"
104 "in vec2 texcoord;\n"
105 "\n"
106 "uniform sampler2D tex;\n"
107 "\n"
108 "void main()\n"
109 "{\n"
110 " fragColor = texture(tex, texcoord);\n"
111 "}\n";
112 osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragment_source);
113
114 _program = new osg::Program();
115 _program->addShader(vertex_shader);
116 _program->addShader(fragment_shader);
117
118 setName("splashGroup");
119 setUpdateCallback(new SplashScreenUpdateCallback);
120 }
121
122 SplashScreen::~SplashScreen()
123 {
124 }
125
126 void SplashScreen::createNodes()
127 {
128 // The splash FBO is rendered as sRGB, but for VR it needs to be in an sRGB
129 // pixel format for it to be handled as such by OpenXR.
130 bool useSRGB = false;
131 osg::Camera* guiCamera = flightgear::getGUICamera(flightgear::CameraGroup::getDefault());
132 #if !defined(SG_MAC)
133 // SRGB does detect on macOS, but doesn't actually work, so we
134 // disable the check there.
135 if (guiCamera) {
136 osg::GraphicsContext* gc = guiCamera->getGraphicsContext();
137 osg::GLExtensions* glext = gc->getState()->get<osg::GLExtensions>();
138 if (glext) {
139 useSRGB = osg::isGLExtensionOrVersionSupported(glext->contextID, "GL_EXT_texture_sRGB", 2.1f) &&
140 osg::isGLExtensionOrVersionSupported(glext->contextID, "GL_EXT_framebuffer_sRGB", 3.0f);
141 }
142 }
143 #endif
144 // setup the base geometry
145 _splashFBOTexture = new osg::Texture2D;
146 _splashFBOTexture->setInternalFormat(useSRGB ? GL_SRGB8 : GL_RGB);
147
148 _splashFBOTexture->setResizeNonPowerOfTwoHint(false);
149 _splashFBOTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
150 _splashFBOTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
151
152 _splashFBOCamera = createFBOCamera();
153 addChild(_splashFBOCamera);
154
155 osg::Geometry* geometry = new osg::Geometry;
156 geometry->setSupportsDisplayList(false);
157
158 osg::Geode* geode = new osg::Geode;
159 _splashFBOCamera->addChild(geode);
160 geode->addDrawable(geometry);
161
162 // get localized GPL licence text to be displayed at splash screen startup
163 std::string licenseUrlText = globals->get_locale()->getLocalizedString("license-url", "sys", LICENSE_URL_TEXT);
164 // add the splash image
165 std::string splashImageName = selectSplashImage();
166 addImage(splashImageName, true, 0, 0, 1, 1, nullptr, true);
167
168 // parse the content from the tree
169 // there can be many <content> <model-content> and <image> nodes
170 // <content> is reserved for use in defaults.xml and is the basic
171 // text; model-content and images are for use in the model
172 // to present model related information.
173 auto root = globals->get_props()->getNode("/sim/startup");
174 bool legacySplashLogoMode = false;
175
176 // firstly add all image nodes.
177 std::vector<SGPropertyNode_ptr> images = root->getChildren("image");
178 if (!images.empty()) {
179 for (const auto& image : images) {
180 addImage(image->getStringValue("path", ""),
181 false,
182 image->getDoubleValue("x", 0.025f),
183 image->getDoubleValue("y", 0.935f),
184 image->getDoubleValue("width", 0.1),
185 image->getDoubleValue("height", 0.1),
186 image->getNode("condition"),
187 false);
188 }
189 } else {
190 // if there are no image nodes then revert to the legacy (2020.3 or before) way of doing things
191 auto splashLogoImage = fgGetString("/sim/startup/splash-logo-image");
192 if (!splashLogoImage.empty())
193 {
194 float logoX = fgGetDouble("/sim/startup/splash-logo-x-norm", 0.0);
195 float logoY = 1.0 - fgGetDouble("/sim/startup/splash-logo-y-norm", 0.065);
196
197 float logoWidth = fgGetDouble("/sim/startup/splash-logo-width", 0.6);
198
199 auto img = addImage(splashLogoImage, false, logoX, logoY, logoWidth, 0, nullptr, false);
200 if (img != nullptr)
201 legacySplashLogoMode = true;
202 }
203 }
204
205 // put this information into the property tree so the defaults or model can pull it in.
206 fgSetString("/sim/startup/splash-authors", flightgear::getAircraftAuthorsText());
207 fgSetString("/sim/startup/description", fgGetString("/sim/description"));
208 fgSetString("/sim/startup/title", "FlightGear "s + fgGetString("/sim/version/flightgear"));
209
210 if (!strcmp(FG_BUILD_TYPE, "Nightly")) {
211 fgSetString("sim/build-warning", globals->get_locale()->getLocalizedString("unstable-warning", "sys", "unstable!"));
212 fgSetBool("sim/build-warning-active", true);
213 }
214
215 // the licence node serves a dual purpose; both the licence URL and then after a delay
216 // (currently 5 seconds) it will display helpful information.
217 fgSetString("/sim/startup/licence", licenseUrlText);
218 fgSetString("/sim/startup/tip", licenseUrlText);
219
220 #ifndef NDEBUG
221 fgSetBool("/sim/startup/build-type-debug", true);
222 #else
223 fgSetBool("/sim/startup/build-type-debug", false);
224 #endif
225
226 fgSetBool("/sim/startup/legacy-splash-screen", _legacySplashScreenMode);
227 fgSetBool("/sim/startup/legacy-splash-logo", legacySplashLogoMode);
228
229 // load all model content first.
230 for (const auto& content : root->getChildren("model-content")) {
231 CreateTextFromNode(content, geode, true);
232 }
233
234 // default content comes in second; and has the ability to be overriden by the model
235 for (const auto& content : root->getChildren("content")) {
236 if (content->getIndex()) { // Skip 0 element - reserved for future usage.
237 // default content can be hidden by the model. By hidden it will never be
238 // added (there is also the possibility to use a condition to dynamically hide content)
239 if (!content->getBoolValue("hide"))
240 CreateTextFromNode(content, geode, false);
241 }
242 }
243 // add main title last so it is atop all.
244 addText(geode, osg::Vec2(0.025f, 0.02f), 0.08, "FlightGear "s + fgGetString("/sim/version/flightgear"), osgText::Text::LEFT_TOP);
245
246 ///////////
247
248 geometry = new osg::Geometry;
249 geometry->setSupportsDisplayList(false);
250
251 _splashSpinnerVertexArray = new osg::Vec3Array;
252 for (int i=0; i < 8; ++i) {
253 _splashSpinnerVertexArray->push_back(osg::Vec3(0.0f, 0.0f, -0.1f));
254 }
255 geometry->setVertexArray(_splashSpinnerVertexArray);
256
257 // QColor buttonColor(27, 122, 211);
258 osg::Vec4Array* colorArray = new osg::Vec4Array;
259 colorArray->push_back(osg::Vec4(27 / 255.0f, 122 / 255.0f, 211 / 255.0f, 0.75f));
260 geometry->setColorArray(colorArray);
261 geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
262 geometry->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, 8));
263
264 geode->addDrawable(geometry);
265
266 //// Full screen quad setup ////////////////////
267
268 _splashQuadCamera = new osg::Camera;
269 _splashQuadCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
270 _splashQuadCamera->setViewMatrix(osg::Matrix::identity());
271 _splashQuadCamera->setProjectionMatrixAsOrtho2D(0.0, 1.0, 0.0, 1.0);
272 _splashQuadCamera->setAllowEventFocus(false);
273 _splashQuadCamera->setCullingActive(false);
274 _splashQuadCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
275
276 osg::StateSet* stateSet = _splashQuadCamera->getOrCreateStateSet();
277 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
278 stateSet->setAttribute(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg::StateAttribute::ON);
279 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
280 stateSet->setRenderBinDetails(1000, "RenderBin");
281 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
282
283 bool use_vertex_attribute_aliasing = false;
284 if (guiCamera) {
285 auto gc = guiCamera->getGraphicsContext();
286 use_vertex_attribute_aliasing = gc->getState()->getUseVertexAttributeAliasing();
287 }
288 if (use_vertex_attribute_aliasing) {
289 stateSet->setAttribute(_program);
290 stateSet->addUniform(new osg::Uniform("tex", 0));
291 }
292
293 if (useSRGB) {
294 stateSet->setMode(GL_FRAMEBUFFER_SRGB, osg::StateAttribute::ON);
295 }
296
297 geometry = osg::createTexturedQuadGeometry(osg::Vec3(0.0, 0.0, 0.0),
298 osg::Vec3(1.0, 0.0, 0.0),
299 osg::Vec3(0.0, 1.0, 0.0));
300 geometry->setSupportsDisplayList(false);
301
302 _splashFSQuadColor = new osg::Vec4Array;
303 _splashFSQuadColor->push_back(osg::Vec4(1, 1.0f, 1, 1));
304 geometry->setColorArray(_splashFSQuadColor);
305 geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
306
307 stateSet = geometry->getOrCreateStateSet();
308 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
309 stateSet->setTextureAttribute(0, _splashFBOTexture);
310
311 geode = new osg::Geode;
312 geode->addDrawable(geometry);
313
314 #ifdef ENABLE_OSGXR
315 _splashSwapchain->attachToMirror(stateSet);
316 #endif
317 _splashQuadCamera->addChild(geode);
318 addChild(_splashQuadCamera);
319 }
320
321 // creates a text element from a property node;
322 // <text> defines the text
323 // <text-prop> overrides the text with the contents of a property
324 // <dynamic-text> will link to a property and update the screen when the property changes
325 // <condition> Visibility Expression
326 // <color> <r><g><b> </color> define colour to be used
327 // <font> specifies the font alignment, size and typeface
328 // <max-width> [optional] the max normalized width of the element
329 // <max-height> [optional] the max normalized height of the element.
330 // <max-lines> [optional] the max number of lines this text can be wrapped over
331 // wrapping takes place at max-width
332 //
333 void SplashScreen::CreateTextFromNode(const SGPropertyNode_ptr& content, osg::Geode* geode, bool modelContent)
334 {
335 auto text = content->getStringValue("text", "");
336 std::string textFromProperty = content->getStringValue("text-prop", "");
337 if (!textFromProperty.empty())
338 text = fgGetString(textFromProperty);
339
340 SGPropertyNode* dynamicValueNode = nullptr;
341 std::string dynamicProperty = content->getStringValue("dynamic-text");
342 if (!dynamicProperty.empty())
343 dynamicValueNode = fgGetNode(dynamicProperty, true);
344
345 auto conditionNode = content->getChild("condition");
346 SGCondition* condition = nullptr;
347
348 if (conditionNode != nullptr) {
349 condition = sgReadCondition(fgGetNode("/"), conditionNode);
350 }
351 auto x = content->getDoubleValue("x", 0.5);
352 auto y = content->getDoubleValue("y", 0.5);
353
354 if (modelContent) {
355 // the top 0.2 of the screen is for system usage
356 if (y < 0.2) {
357 SG_LOG(SG_VIEW, SG_ALERT, "model content cannot be above 0.2 y");
358 y = 0.2;
359 }
360 }
361
362 auto textItem = addText(geode, osg::Vec2(x, y),
363 content->getDoubleValue("font/size", 0.06),
364 text,
365 osgutils::mapAlignment(content->getStringValue("font/alignment", "left-top")),
366 dynamicValueNode,
367 content->getDoubleValue("max-width", -1.0),
368 osg::Vec4(content->getDoubleValue("color/r", 1), content->getDoubleValue("color/g", 1), content->getDoubleValue("color/b", 1), content->getDoubleValue("color/a", 1)),
369 content->getStringValue("font/face", "Fonts/LiberationFonts/LiberationSans-BoldItalic.ttf"));
370
371 textItem->condition = condition;
372
373 if (textItem->condition != nullptr && !textItem->condition->test())
374 textItem->textNode->setDrawMode(0);
375
376
377 auto maxHeight = content->getDoubleValue("max-height", -1.0);
378 auto maxLineCount = content->getIntValue("max-line-count", -1);
379
380 if (maxLineCount > 0)
381 textItem->maxLineCount = maxLineCount;
382 if (maxHeight > 0)
383 textItem->maxHeightFraction = maxHeight;
384 }
385
386 osg::ref_ptr<osg::Camera> SplashScreen::createFBOCamera()
387 {
388 osg::ref_ptr<osg::Camera> c = new osg::Camera;
389 c->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
390 c->setViewMatrix(osg::Matrix::identity());
391 c->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
392 c->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
393 c->setAllowEventFocus(false);
394 c->setCullingActive(false);
395 c->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
396 c->setRenderOrder(osg::Camera::PRE_RENDER);
397 c->attach(osg::Camera::COLOR_BUFFER, _splashFBOTexture);
398 #ifdef ENABLE_OSGXR
399 _splashSwapchain->attachToCamera(c);
400 #endif
401
402 osg::StateSet* stateSet = c->getOrCreateStateSet();
403 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
404 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
405 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
406 stateSet->setAttribute(new osg::Depth(osg::Depth::ALWAYS, 0, 1, false));
407 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
408
409 bool use_vertex_attribute_aliasing = false;
410 osg::Camera* guiCamera = flightgear::getGUICamera(flightgear::CameraGroup::getDefault());
411 if (guiCamera) {
412 auto gc = guiCamera->getGraphicsContext();
413 use_vertex_attribute_aliasing = gc->getState()->getUseVertexAttributeAliasing();
414 }
415 if (use_vertex_attribute_aliasing) {
416 stateSet->setAttribute(_program);
417 stateSet->addUniform(new osg::Uniform("tex", 0));
418 }
419
420 return c;
421 }
422
423 // Load an image for display
424 // - path
425 // - x,y,width,height (normalized coordinates)
426 // - isBackground flag to indicate that this image is the background image. Only set during one call to this method when loading the splash image
427 //
428 const SplashScreen::ImageItem *SplashScreen::addImage(const std::string &path, bool isAbsolutePath, double x, double y, double width, double height, SGPropertyNode*
429 conditionNode, bool isBackground)
430 {
431 if (path.empty())
432 return nullptr;
433
434 SGPath imagePath;
435
436 if (!isAbsolutePath)
437 imagePath = globals->resolve_maybe_aircraft_path(path);
438 else
439 imagePath = path;
440
441 if (!imagePath.exists() || !imagePath.isFile()) {
442 SG_LOG(SG_VIEW, SG_INFO, "Splash Image " << path << " not be found");
443 return nullptr;
444 }
445
446 ImageItem item;
447 item.name = path;
448 item.x = x;
449 item.y = y;
450 item.height = height;
451 item.width = width;
452 item.isBackground = isBackground;
453
454 if (conditionNode != nullptr)
455 item.condition = sgReadCondition(fgGetNode("/"), conditionNode);
456 else
457 item.condition = nullptr;
458
459 osg::ref_ptr<simgear::SGReaderWriterOptions> staticOptions = simgear::SGReaderWriterOptions::copyOrCreate(osgDB::Registry::instance()->getOptions());
460 staticOptions->setLoadOriginHint(simgear::SGReaderWriterOptions::LoadOriginHint::ORIGIN_SPLASH_SCREEN);
461
462 item.Image = osgDB::readRefImageFile(imagePath.utf8Str(), staticOptions);
463 if (!item.Image) {
464 SG_LOG(SG_VIEW, SG_INFO, "Splash Image " << imagePath << " failed to load");
465 return nullptr;
466 }
467
468 item.imageWidth = item.Image->s();
469 item.imageHeight = item.Image->t();
470 item.aspectRatio = static_cast<double>(item.imageWidth) / item.imageHeight;
471 if (item.height == 0 && item.imageWidth != 0)
472 item.height = item.imageHeight * (item.width / item.imageWidth);
473
474 osg::Texture2D* imageTexture = new osg::Texture2D(item.Image);
475 imageTexture->setResizeNonPowerOfTwoHint(false);
476 imageTexture->setInternalFormat(GL_RGBA);
477 imageTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
478 imageTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
479
480 osg::Geometry* geometry = new osg::Geometry;
481 geometry->setSupportsDisplayList(false);
482
483 item.vertexArray = new osg::Vec3Array;
484 for (int i=0; i < 4; ++i) {
485 item.vertexArray->push_back(osg::Vec3(0.0, 0.0, 0.0));
486 }
487 geometry->setVertexArray(item.vertexArray);
488
489 osg::Vec2Array* imageTextureCoordinates = new osg::Vec2Array;
490 imageTextureCoordinates->push_back(osg::Vec2(0, 0));
491 imageTextureCoordinates->push_back(osg::Vec2(1.0, 0));
492 imageTextureCoordinates->push_back(osg::Vec2(1.0, 1.0));
493 imageTextureCoordinates->push_back(osg::Vec2(0, 1.0));
494 geometry->setTexCoordArray(0, imageTextureCoordinates);
495
496 osg::Vec4Array* imageColorArray = new osg::Vec4Array;
497 imageColorArray->push_back(osg::Vec4(1, 1, 1, 1));
498 geometry->setColorArray(imageColorArray);
499 geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
500 geometry->addPrimitiveSet(new osg::DrawArrays(GL_POLYGON, 0, 4));
501
502 osg::StateSet* stateSet = geometry->getOrCreateStateSet();
503 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
504 stateSet->setTextureAttribute(0, imageTexture);
505 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
506
507 osg::Geode* geode = new osg::Geode;
508 _splashFBOCamera->addChild(geode);
509 geode->addDrawable(geometry);
510
511 item.geode = geode;
512 item.nodeMask = geode->getNodeMask();
513
514 if (item.condition != nullptr && !item.condition->test())
515 item.geode->setNodeMask(0);
516
517 _imageItems.push_back(item);
518 return &_imageItems.back();
519 }
520
521 SplashScreen::TextItem *SplashScreen::addText(osg::Geode* geode ,
522 const osg::Vec2& pos, double size, const std::string& text,
523 const osgText::Text::AlignmentType alignment,
524 SGPropertyNode* dynamicValue,
525 double maxWidthFraction,
526 const osg::Vec4& textColor,
527 const std::string &fontFace )
528 {
529 SGPath path = globals->resolve_maybe_aircraft_path(fontFace);
530
531 TextItem item;
532 osg::ref_ptr<osgText::Text> t = new osgText::Text;
533 item.textNode = t;
534 t->setFont(path.utf8Str());
535 t->setColor(textColor);
536 t->setFontResolution(64, 64);
537 t->setText(text, osgText::String::Encoding::ENCODING_UTF8);
538 t->setBackdropType(osgText::Text::OUTLINE);
539 t->setBackdropColor(osg::Vec4(0.2, 0.2, 0.2, 1));
540 t->setBackdropOffset(0.04);
541
542 item.fractionalCharSize = size;
543 item.fractionalPosition = pos;
544 item.dynamicContent = dynamicValue;
545 item.textNode->setAlignment(alignment);
546 item.maxWidthFraction = maxWidthFraction;
547 item.condition = nullptr; // default to always display.
548 item.drawMode = t->getDrawMode();
549 geode->addDrawable(item.textNode);
550
551 _items.push_back(item);
552 return &_items.back();
553 }
554
555 void SplashScreen::TextItem::reposition(int width, int height) const
556 {
557 const int halfWidth = width >> 1;
558 const int halfHeight = height >> 1;
559 osg::Vec3 pixelPos(fractionalPosition.x() * width - halfWidth,
560 (1.0 - fractionalPosition.y()) * height - halfHeight,
561 -0.1);
562 textNode->setPosition(pixelPos);
563 textNode->setCharacterSize(fractionalCharSize * height);
564
565 if (maxWidthFraction > 0.0) {
566 textNode->setMaximumWidth(maxWidthFraction * width);
567 }
568
569 recomputeSize(height);
570 }
571
572 void SplashScreen::TextItem::recomputeSize(int height) const
573 {
574 if ((maxLineCount == 0) && (maxHeightFraction < 0.0)) {
575 return;
576 }
577
578 double heightFraction = maxHeightFraction;
579 if (heightFraction < 0.0) {
580 heightFraction = 9999.0;
581 }
582
583 double baseSize = fractionalCharSize;
584 textNode->update();
585 while ((textNode->getLineCount() > maxLineCount) ||
586 (baseSize * textNode->getLineCount() > heightFraction)) {
587 baseSize *= 0.8; // 20% shrink each time
588 textNode->setCharacterSize(baseSize * height);
589 textNode->update();
590 }
591 }
592
593 std::string SplashScreen::selectSplashImage()
594 {
595 sg_srandom_time(); // init random seed
596
597 simgear::PropertyList previewNodes = fgGetNode("/sim/previews", true)->getChildren("preview");
598 std::vector<SGPath> paths;
599
600 for (auto n : previewNodes) {
601 if (!n->getBoolValue("splash", false)) {
602 continue;
603 }
604
605 SGPath tpath = globals->resolve_maybe_aircraft_path(n->getStringValue("path"));
606 if (tpath.exists()) {
607 paths.push_back(tpath);
608 }
609 }
610
611 if (paths.empty()) {
612 // look for a legacy aircraft splash
613 simgear::PropertyList nodes = fgGetNode("/sim/startup", true)->getChildren("splash-texture");
614 for (auto n : nodes) {
615 SGPath tpath = globals->resolve_maybe_aircraft_path(n->getStringValue());
616 if (tpath.exists()) {
617 paths.push_back(tpath);
618 _legacySplashScreenMode = true;
619 }
620 }
621 }
622
623 if (!paths.empty()) {
624 // Select a random useable texture
625 const int index = (int)(sg_random() * paths.size());
626 return paths.at(index).utf8Str();
627 }
628
629 // no splash screen specified - use one of the default ones
630 SGPath tpath = globals->get_fg_root() / "Textures";
631 paths = simgear::Dir(tpath).children(simgear::Dir::TYPE_FILE);
632 paths.erase(std::remove_if(paths.begin(), paths.end(), [](const SGPath& p) {
633 const auto f = p.file();
634 if (f.find("Splash") != 0) return true;
635 const auto ext = p.extension();
636 return ext != "png" && ext != "jpg";
637 }), paths.end());
638
639 if (!paths.empty()) {
640 // Select a random useable texture
641 const int index = (int)(sg_random() * paths.size());
642 return paths.at(index).utf8Str();
643 }
644
645 SG_LOG(SG_GUI, SG_ALERT, "Couldn't find any splash screens at all");
646 return {};
647 }
648
649 void SplashScreen::doUpdate()
650 {
651 if (!guiInit()) {
652 // don't createNodes until OSG init operations have completed
653 return;
654 }
655
656 double alpha = _splashAlphaNode->getDoubleValue();
657
658 if (alpha <= 0 || !fgGetBool("/sim/startup/splash-screen")) {
659 removeChild(0, getNumChildren());
660 _splashFBOCamera = nullptr;
661 _splashQuadCamera = nullptr;
662 #ifdef ENABLE_OSGXR
663 _splashLayer->setVisible(false);
664 #endif
665 } else if (getNumChildren() == 0) {
666 createNodes();
667 _splashStartTime.stamp();
668 resize(fgGetInt("/sim/startup/xsize"),
669 fgGetInt("/sim/startup/ysize"));
670 #ifdef ENABLE_OSGXR
671 _splashLayer->setVisible(true);
672 _splashSwapchain->setForcedAlpha(alpha);
673 #endif
674 } else {
675 (*_splashFSQuadColor)[0] = osg::Vec4(1.0, 1.0, 1.0, _splashAlphaNode->getFloatValue());
676 _splashFSQuadColor->dirty();
677
678 for (const TextItem& item : _items) {
679 if (item.condition != nullptr) {
680
681 if (item.condition->test())
682 item.textNode->setDrawMode(item.drawMode);
683 else
684 item.textNode->setDrawMode(0);
685 }
686 if (item.dynamicContent) {
687 item.textNode->setText(
688 item.dynamicContent->getStringValue(),
689 osgText::String::Encoding::ENCODING_UTF8);
690 }
691 }
692 for (const ImageItem& image : _imageItems) {
693 if (image.condition) {
694 if (!image.condition->test())
695 image.geode->setNodeMask(0);
696 else
697 image.geode->setNodeMask(image.nodeMask);
698 }
699 }
700 updateSplashSpinner();
701 updateTipText();
702 #ifdef ENABLE_OSGXR
703 _splashSwapchain->setForcedAlpha(alpha);
704 #endif
705 }
706 }
707
708 float scaleAndOffset(float v, float halfWidth)
709 {
710 return halfWidth * ((v * 2.0) - 1.0);
711 }
712
713 void SplashScreen::updateSplashSpinner()
714 {
715 const int elapsedMsec = _splashStartTime.elapsedMSec();
716 float splashSpinnerPos = (elapsedMsec % 2000) / 2000.0f;
717 float endPos = splashSpinnerPos + 0.25f;
718 float wrapStartPos = 0.0f;
719 float wrapEndPos = 0.0f; // no wrapped quad
720 if (endPos > 1.0f) {
721 wrapEndPos = endPos - 1.0f;
722 }
723
724 const float halfWidth = _width * 0.5f;
725 const float halfHeight = _height * 0.5f;
726 const float bottomY = -halfHeight;
727 const float topY = bottomY + 8;
728 const float z = -0.05f;
729
730 splashSpinnerPos = scaleAndOffset(splashSpinnerPos, halfWidth);
731 endPos = scaleAndOffset(endPos, halfWidth);
732 wrapStartPos = scaleAndOffset(wrapStartPos, halfWidth);
733 wrapEndPos = scaleAndOffset(wrapEndPos, halfWidth);
734
735 osg::Vec3 positions[8] = {
736 osg::Vec3(splashSpinnerPos, bottomY, z),
737 osg::Vec3(endPos, bottomY, z),
738 osg::Vec3(endPos,topY, z),
739 osg::Vec3(splashSpinnerPos, topY, z),
740 osg::Vec3(wrapStartPos, bottomY, z),
741 osg::Vec3(wrapEndPos, bottomY, z),
742 osg::Vec3(wrapEndPos,topY, z),
743 osg::Vec3(wrapStartPos, topY, z)
744
745 };
746
747 for (int i=0; i<8; ++i) {
748 (*_splashSpinnerVertexArray)[i] = positions[i];
749 }
750
751 _splashSpinnerVertexArray->dirty();
752 }
753
754 void SplashScreen::updateTipText()
755 {
756 // after 5 seconds change the tip; but only do this once.
757 // the tip will be set into a property and this in turn will be
758 // displayed by the content using a dynamic-text element
759 if (!_haveSetStartupTip && (_splashStartTime.elapsedMSec() > 5000)) {
760 _haveSetStartupTip = true;
761 FGLocale* locale = globals->get_locale();
762 const int tipCount = locale->getLocalizedStringCount("tip", "tips");
763 if (tipCount == 0) {
764 return;
765 }
766
767 int tipIndex = globals->get_props()->getIntValue("/sim/session",0) % tipCount;
768
769 std::string tipText = locale->getLocalizedStringWithIndex("tip", "tips", tipIndex);
770 fgSetString("/sim/startup/tip", tipText);
771 }
772 }
773
774 void SplashScreen::resize( int width, int height )
775 {
776 if (getNumChildren() == 0) {
777 return;
778 }
779
780 _width = width;
781 _height = height;
782
783 _splashQuadCamera->setViewport(0, 0, width, height);
784 _splashFBOCamera->resizeAttachments(width, height);
785 _splashFBOCamera->setViewport(0, 0, width, height);
786 _splashFBOCamera->setProjectionMatrixAsOrtho2D(-width * 0.5, width * 0.5,
787 -height * 0.5, height * 0.5);
788 #ifdef ENABLE_OSGXR
789 float aspect = (float)width / height;
790 _splashSwapchain->setSize(width, height);
791 _splashLayer->setSize(osg::Vec2f(aspect, 1.0f));
792 #endif
793
794 const double screenAspectRatio = static_cast<double>(width) / height;
795
796 // resize all of the images on the splash screen (including the background)
797 for (const auto& _imageItem : _imageItems) {
798
799 if (_imageItem.isBackground) {
800 // background is based around the centre of the screen
801 // and adjusted so that the largest of width,height is used
802 // to fill the screen so that the image fits without distortion
803 double halfWidth = width * 0.5;
804 double halfHeight = height * 0.5;
805
806 // if this is the background image and we are in legacy mode then
807 // resize to keep the image scaled to fit in the centre
808 if (_legacySplashScreenMode) {
809 halfWidth = width * 0.35;
810 halfHeight = height * 0.35;
811
812 if (screenAspectRatio > _imageItem.aspectRatio) {
813 // screen is wider than our image
814 halfWidth = halfHeight;
815 }
816 else {
817 // screen is taller than our image
818 halfHeight = halfWidth;
819 }
820 }
821 else {
822 // adjust vertex positions; image covers entire area
823 if (screenAspectRatio > _imageItem.aspectRatio) {
824 // screen is wider than our image
825 halfHeight = halfWidth / _imageItem.aspectRatio;
826 }
827 else {
828 // screen is taller than our image
829 halfWidth = halfHeight * _imageItem.aspectRatio;
830 }
831 }
832 (*_imageItem.vertexArray)[0] = osg::Vec3(-halfWidth, -halfHeight, 0.0);
833 (*_imageItem.vertexArray)[1] = osg::Vec3(halfWidth, -halfHeight, 0.0);
834 (*_imageItem.vertexArray)[2] = osg::Vec3(halfWidth, halfHeight, 0.0);
835 (*_imageItem.vertexArray)[3] = osg::Vec3(-halfWidth, halfHeight, 0.0);
836 }
837 else {
838
839 float imageWidth = _imageItem.width * width;
840 float imageHeight = _imageItem.imageHeight * (imageWidth / _imageItem.imageWidth);
841
842 float imageX = _imageItem.x * (width - imageWidth);
843 float imageY = (1.0 - _imageItem.y) * (height - imageHeight);
844
845 float originX = imageX - (width * 0.5);
846 float originY = imageY - (height * 0.5);
847
848 (*_imageItem.vertexArray)[0] = osg::Vec3(originX, originY, 0.0);
849 (*_imageItem.vertexArray)[1] = osg::Vec3(originX + imageWidth, originY, 0.0);
850 (*_imageItem.vertexArray)[2] = osg::Vec3(originX + imageWidth, originY + imageHeight, 0.0);
851 (*_imageItem.vertexArray)[3] = osg::Vec3(originX, originY + imageHeight, 0.0);
852 }
853 _imageItem.vertexArray->dirty();
854 }
855
856 // adjust all text positions.
857 for (const TextItem& item : _items) {
858 item.reposition(width, height);
859 }
860 }
861
862 void fgSplashProgress( const char *identifier, unsigned int percent )
863 {
864 fgSetString("/sim/startup/splash-progress-spinner", "");
865
866 std::string text;
867 if (identifier[0] != 0)
868 {
869 text = globals->get_locale()->getLocalizedString(identifier, "sys");
870
871 if( text.empty() )
872 text = "<incomplete language resource>: "s + identifier;
873 }
874
875 if (!strcmp(identifier,"downloading-scenery")) {
876
877 // get localized texts for units
878 std::string kbytesUnitText = globals->get_locale()->getLocalizedString("units-kbytes", "sys", "KB");
879 std::string mbytesUnitText = globals->get_locale()->getLocalizedString("units-mbytes", "sys", "MB");
880 std::string kbytesPerSecUnitText = globals->get_locale()->getLocalizedString("units-kbytes-per-sec", "sys", "KB/s");
881 std::string mbytesPerSecUnitText = globals->get_locale()->getLocalizedString("units-mbytes-per-sec", "sys", "MB/s");
882
883 std::ostringstream oss;
884 unsigned int kbytesPerSec = fgGetInt("/sim/terrasync/transfer-rate-bytes-sec") / 1024;
885 unsigned int kbytesPending = fgGetInt("/sim/terrasync/pending-kbytes");
886 unsigned int kbytesPendingExtract = fgGetInt("/sim/terrasync/extract-pending-kbytes");
887 if (kbytesPending > 0) {
888 if (kbytesPending > 1024) {
889 int mBytesPending = kbytesPending >> 10;
890 oss << " " << mBytesPending << " "s << mbytesUnitText;
891 } else {
892 oss << " " << kbytesPending << " "s << kbytesUnitText;
893 }
894 }
895
896 if (kbytesPerSec > 100) {
897 double mbytesPerSec = kbytesPerSec / 1024.0;
898 oss << " - " << std::fixed << std::setprecision(1) << mbytesPerSec << " "s << mbytesPerSecUnitText;
899 } else if (kbytesPerSec > 0) {
900 oss << " - " << kbytesPerSec << " "s << kbytesPerSecUnitText;
901 } else if (kbytesPendingExtract > 0) {
902 const std::string extractText = globals->get_locale()->getLocalizedString("scenery-extract", "sys");
903 std::ostringstream os2;
904
905 if (kbytesPendingExtract > 1024) {
906 int mBytesPendingExtract = kbytesPendingExtract >> 10;
907 os2 << mBytesPendingExtract << " "s << mbytesUnitText;
908 } else {
909 os2 << kbytesPendingExtract << " "s << kbytesUnitText;
910 }
911 auto finalText = simgear::strutils::replace(extractText, "[VALUE]", os2.str());
912 oss << " - " << finalText;
913 }
914 fgSetString("/sim/startup/splash-progress-spinner", oss.str());
915 }
916
917 if (!strcmp(identifier, "loading-scenery")) {
918
919 // get localized texts for units
920 std::string kbytesUnitText = globals->get_locale()->getLocalizedString("units-kbytes", "sys", "KB");
921 std::string mbytesUnitText = globals->get_locale()->getLocalizedString("units-mbytes", "sys", "MB");
922
923 unsigned int kbytesPendingExtract = fgGetInt("/sim/terrasync/extract-pending-kbytes");
924 if (kbytesPendingExtract > 0) {
925 const std::string extractText = globals->get_locale()->getLocalizedString("scenery-extract", "sys");
926 std::ostringstream oss;
927 if (kbytesPendingExtract > 1024) {
928 int mBytesPendingExtract = kbytesPendingExtract >> 10;
929 oss << mBytesPendingExtract << " "s << mbytesUnitText;
930 } else {
931 oss << kbytesPendingExtract << " "s << kbytesUnitText;
932 }
933
934 auto finalText = simgear::strutils::replace(extractText, "[VALUE]", oss.str());
935 fgSetString("/sim/startup/splash-progress-spinner", finalText);
936 } else {
937 fgSetString("/sim/startup/splash-progress-spinner", "");
938 }
939 }
940
941 // over-write the spinner
942 if (!strncmp(identifier, "navdata-", 8)) {
943 const std::string percentText = globals->get_locale()->getLocalizedString("navdata-load-percent", "sys");
944 auto finalText = simgear::strutils::replace(percentText, "[VALUE]", std::to_string(percent));
945 fgSetString("/sim/startup/splash-progress-spinner", finalText);
946 }
947
948 if( fgGetString("/sim/startup/splash-progress-text") == text )
949 return;
950
951 SG_LOG( SG_VIEW, SG_INFO, "Splash screen progress " << identifier );
952 fgSetString("/sim/startup/splash-progress-text", text);
953 }