diff --git a/.gitignore b/.gitignore index a20830ba55..92d0697d9e 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,5 @@ customization.lua # The COMMIT info is generated everytime CMake is run COMMIT.md *_codegen.cpp +# SkyBrowser Module downloaded data +/modules/skybrowser/wwtimagedata diff --git a/data/assets/circle.png b/data/assets/circle.png new file mode 100644 index 0000000000..5f3a08e5c5 Binary files /dev/null and b/data/assets/circle.png differ diff --git a/data/assets/hoverCircle.asset b/data/assets/hoverCircle.asset new file mode 100644 index 0000000000..f5673b1bd3 --- /dev/null +++ b/data/assets/hoverCircle.asset @@ -0,0 +1,29 @@ +-- This asset requires OpenSpace to be built with the OPENSPACE_MODULE_SPOUT enabled + +local transforms = asset.require("scene/solarsystem/sun/transforms") + +local circle = { + Identifier = "hoverCircle", + Parent = transforms.SolarSystemBarycenter.Identifier, + Renderable = { + Type = "RenderablePlaneImageLocal", + Size = 3.0E15, + Origin = "Center", + Billboard = true, + Texture = "${ASSETS}/circle.png" + }, + GUI = { + Path = "/SkyBrowser" + } +} + +asset.onInitialize(function() + openspace.addSceneGraphNode(circle) + openspace.skybrowser.setHoverCircle('hoverCircle') +end) + +asset.onDeinitialize(function() + openspace.removeSceneGraphNode(circle) +end) + +asset.export(circle) diff --git a/data/assets/util/webgui.asset b/data/assets/util/webgui.asset index 85335141b1..a2835cd596 100644 --- a/data/assets/util/webgui.asset +++ b/data/assets/util/webgui.asset @@ -3,7 +3,7 @@ asset.require("./static_server") local guiCustomization = asset.require("customization/gui") -- Select which commit hashes to use for the frontend and backend -local frontendHash = "8c3d18a4a2cb1df526e1c3f2ea228013ce89099e" +local frontendHash = "ea33990de2e1477ecafa89861cf6f65e4c2fd46d" local dataProvider = "data.openspaceproject.com/files/webgui" local frontend = asset.syncedResource({ @@ -66,7 +66,7 @@ asset.onDeinitialize(function () end end -- @TODO(maci, 2019-08-23) setting this value on exit was causing the server to restart - -- on macos, which in turn, stopped the application from exiting. + -- on macos, which in turn, stopped the application from exiting. -- need to address in webguimodule.cpp --openspace.setPropertyValueSingle("Modules.WebGui.Directories", newDirectories) end) diff --git a/include/openspace/rendering/screenspacerenderable.h b/include/openspace/rendering/screenspacerenderable.h index 8e210f73ff..9fd44254a8 100644 --- a/include/openspace/rendering/screenspacerenderable.h +++ b/include/openspace/rendering/screenspacerenderable.h @@ -70,24 +70,46 @@ public: virtual void update(); virtual bool isReady() const; bool isEnabled() const; + bool isUsingRaeCoords() const; + bool isFacingCamera() const; + void setEnabled(bool isEnabled); float depth(); + // Screen space functionality in these coords: [-1,1][-ratio,ratio] + glm::vec2 screenSpacePosition(); + glm::vec2 screenSpaceDimensions(); + glm::vec2 upperRightCornerScreenSpace(); + glm::vec2 lowerLeftCornerScreenSpace(); + bool isIntersecting(glm::vec2 coord); + void translate(glm::vec2 translation, glm::vec2 position); + void setCartesianPosition(const glm::vec3& position); + void setRaeFromCartesianPosition(const glm::vec3& position); + glm::vec3 raePosition() const; + static documentation::Documentation Documentation(); protected: void createShaders(); std::string makeUniqueIdentifier(std::string name); - glm::mat4 scaleMatrix(); + virtual glm::mat4 scaleMatrix(); glm::mat4 globalRotationMatrix(); glm::mat4 translationMatrix(); glm::mat4 localRotationMatrix(); + glm::vec3 raeToCartesian(const glm::vec3& rae) const; + glm::vec3 cartesianToRae(const glm::vec3& cartesian) const; + void draw(glm::mat4 modelTransform); virtual void bindTexture() = 0; virtual void unbindTexture(); + glm::vec3 sphericalToRae(glm::vec3 spherical) const; + glm::vec3 raeToSpherical(glm::vec3 rae) const; + glm::vec3 cartesianToSpherical(const glm::vec3& cartesian) const; + glm::vec3 sphericalToCartesian(glm::vec3 spherical) const; + glm::vec3 sanitizeSphericalCoordinates(glm::vec3 spherical) const; float opacity() const; properties::BoolProperty _enabled; diff --git a/modules/base/rendering/renderableplane.h b/modules/base/rendering/renderableplane.h index b70c609656..843cdd9a36 100644 --- a/modules/base/rendering/renderableplane.h +++ b/modules/base/rendering/renderableplane.h @@ -67,23 +67,20 @@ public: protected: virtual void bindTexture(); virtual void unbindTexture(); - -protected: - properties::OptionProperty _blendMode; - -private: void createPlane(); - - properties::BoolProperty _billboard; + + properties::OptionProperty _blendMode; properties::BoolProperty _mirrorBackside; + properties::BoolProperty _billboard; properties::FloatProperty _size; properties::Vec3Property _multiplyColor; - + ghoul::opengl::ProgramObject* _shader = nullptr; - + GLuint _quad = 0; GLuint _vertexPositionBuffer = 0; +private: bool _planeIsDirty = false; }; diff --git a/modules/skybrowser/CMakeLists.txt b/modules/skybrowser/CMakeLists.txt new file mode 100644 index 0000000000..0eba482bc2 --- /dev/null +++ b/modules/skybrowser/CMakeLists.txt @@ -0,0 +1,59 @@ +########################################################################################## +# # +# OpenSpace # +# # +# Copyright (c) 2014-2022 # +# # +# Permission is hereby granted, free of charge, to any person obtaining a copy of this # +# software and associated documentation files (the "Software"), to deal in the Software # +# without restriction, including without limitation the rights to use, copy, modify, # +# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # +# permit persons to whom the Software is furnished to do so, subject to the following # +# conditions: # +# # +# The above copyright notice and this permission notice shall be included in all copies # +# or substantial portions of the Software. # +# # +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # +# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # +# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # +# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # +# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # +########################################################################################## + +include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake) + +set(HEADER_FILES + skybrowsermodule.h + include/renderableskytarget.h + include/wwtdatahandler.h + include/utility.h + include/targetbrowserpair.h + include/wwtcommunicator.h + include/browser.h + include/screenspaceskybrowser.h + ext/tinyxml2/tinyxml2.h +) +source_group("Header Files" FILES ${HEADER_FILES}) + +set(SOURCE_FILES + skybrowsermodule.cpp + skybrowsermodule_lua.inl + src/renderableskytarget.cpp + src/wwtdatahandler.cpp + src/utility.cpp + src/targetbrowserpair.cpp + src/wwtcommunicator.cpp + src/browser.cpp + src/screenspaceskybrowser.cpp + ext/tinyxml2/tinyxml2.cpp +) +source_group("Source Files" FILES ${SOURCE_FILES}) + +create_new_module( + "SkyBrowser" + skybrowser_module + STATIC + ${HEADER_FILES} ${SOURCE_FILES} +) diff --git a/modules/skybrowser/ext/tinyxml2/tinyxml2.cpp b/modules/skybrowser/ext/tinyxml2/tinyxml2.cpp new file mode 100644 index 0000000000..925cffd28c --- /dev/null +++ b/modules/skybrowser/ext/tinyxml2/tinyxml2.cpp @@ -0,0 +1,2986 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#include "tinyxml2.h" + +#include // yes, this one new style header, is in the Android SDK. +#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) +# include +# include +#else +# include +# include +#endif + +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + // Microsoft Visual Studio, version 2005 and higher. Not WinCE. + /*int _snprintf_s( + char *buffer, + size_t sizeOfBuffer, + size_t count, + const char *format [, + argument] ... + );*/ + static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) + { + va_list va; + va_start( va, format ); + const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + va_end( va ); + return result; + } + + static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) + { + const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + return result; + } + + #define TIXML_VSCPRINTF _vscprintf + #define TIXML_SSCANF sscanf_s +#elif defined _MSC_VER + // Microsoft Visual Studio 2003 and earlier or WinCE + #define TIXML_SNPRINTF _snprintf + #define TIXML_VSNPRINTF _vsnprintf + #define TIXML_SSCANF sscanf + #if (_MSC_VER < 1400 ) && (!defined WINCE) + // Microsoft Visual Studio 2003 and not WinCE. + #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. + #else + // Microsoft Visual Studio 2003 and earlier or WinCE. + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = 512; + for (;;) { + len = len*2; + char* str = new char[len](); + const int required = _vsnprintf(str, len, format, va); + delete[] str; + if ( required != -1 ) { + TIXMLASSERT( required >= 0 ); + len = required; + break; + } + } + TIXMLASSERT( len >= 0 ); + return len; + } + #endif +#else + // GCC version 3 and higher + //#warning( "Using sn* functions." ) + #define TIXML_SNPRINTF snprintf + #define TIXML_VSNPRINTF vsnprintf + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = vsnprintf( 0, 0, format, va ); + TIXMLASSERT( len >= 0 ); + return len; + } + #define TIXML_SSCANF sscanf +#endif + +#if defined(_WIN64) + #define TIXML_FSEEK _fseeki64 + #define TIXML_FTELL _ftelli64 +#elif defined(__APPLE__) || defined(__FreeBSD__) + #define TIXML_FSEEK fseeko + #define TIXML_FTELL ftello +#elif defined(__unix__) && defined(__x86_64__) + #define TIXML_FSEEK fseeko64 + #define TIXML_FTELL ftello64 +#else + #define TIXML_FSEEK fseek + #define TIXML_FTELL ftell +#endif + + +static const char LINE_FEED = static_cast(0x0a); // all line endings are normalized to LF +static const char LF = LINE_FEED; +static const char CARRIAGE_RETURN = static_cast(0x0d); // CR gets filtered out +static const char CR = CARRIAGE_RETURN; +static const char SINGLE_QUOTE = '\''; +static const char DOUBLE_QUOTE = '\"'; + +// Bunch of unicode info at: +// http://www.unicode.org/faq/utf_bom.html +// ef bb bf (Microsoft "lead bytes") - designates UTF-8 + +static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; +static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; +static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; + +namespace tinyxml2 +{ + +struct Entity { + const char* pattern; + int length; + char value; +}; + +static const int NUM_ENTITIES = 5; +static const Entity entities[NUM_ENTITIES] = { + { "quot", 4, DOUBLE_QUOTE }, + { "amp", 3, '&' }, + { "apos", 4, SINGLE_QUOTE }, + { "lt", 2, '<' }, + { "gt", 2, '>' } +}; + + +StrPair::~StrPair() +{ + Reset(); +} + + +void StrPair::TransferTo( StrPair* other ) +{ + if ( this == other ) { + return; + } + // This in effect implements the assignment operator by "moving" + // ownership (as in auto_ptr). + + TIXMLASSERT( other != 0 ); + TIXMLASSERT( other->_flags == 0 ); + TIXMLASSERT( other->_start == 0 ); + TIXMLASSERT( other->_end == 0 ); + + other->Reset(); + + other->_flags = _flags; + other->_start = _start; + other->_end = _end; + + _flags = 0; + _start = 0; + _end = 0; +} + + +void StrPair::Reset() +{ + if ( _flags & NEEDS_DELETE ) { + delete [] _start; + } + _flags = 0; + _start = 0; + _end = 0; +} + + +void StrPair::SetStr( const char* str, int flags ) +{ + TIXMLASSERT( str ); + Reset(); + size_t len = strlen( str ); + TIXMLASSERT( _start == 0 ); + _start = new char[ len+1 ]; + memcpy( _start, str, len+1 ); + _end = _start + len; + _flags = flags | NEEDS_DELETE; +} + + +char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr ) +{ + TIXMLASSERT( p ); + TIXMLASSERT( endTag && *endTag ); + TIXMLASSERT(curLineNumPtr); + + char* start = p; + const char endChar = *endTag; + size_t length = strlen( endTag ); + + // Inner loop of text parsing. + while ( *p ) { + if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { + Set( start, p, strFlags ); + return p + length; + } else if (*p == '\n') { + ++(*curLineNumPtr); + } + ++p; + TIXMLASSERT( p ); + } + return 0; +} + + +char* StrPair::ParseName( char* p ) +{ + if ( !p || !(*p) ) { + return 0; + } + if ( !XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { + return 0; + } + + char* const start = p; + ++p; + while ( *p && XMLUtil::IsNameChar( (unsigned char) *p ) ) { + ++p; + } + + Set( start, p, 0 ); + return p; +} + + +void StrPair::CollapseWhitespace() +{ + // Adjusting _start would cause undefined behavior on delete[] + TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); + // Trim leading space. + _start = XMLUtil::SkipWhiteSpace( _start, 0 ); + + if ( *_start ) { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( *p ) { + if ( XMLUtil::IsWhiteSpace( *p )) { + p = XMLUtil::SkipWhiteSpace( p, 0 ); + if ( *p == 0 ) { + break; // don't write to q; this trims the trailing space. + } + *q = ' '; + ++q; + } + *q = *p; + ++q; + ++p; + } + *q = 0; + } +} + + +const char* StrPair::GetStr() +{ + TIXMLASSERT( _start ); + TIXMLASSERT( _end ); + if ( _flags & NEEDS_FLUSH ) { + *_end = 0; + _flags ^= NEEDS_FLUSH; + + if ( _flags ) { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( p < _end ) { + if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { + // CR-LF pair becomes LF + // CR alone becomes LF + // LF-CR becomes LF + if ( *(p+1) == LF ) { + p += 2; + } + else { + ++p; + } + *q = LF; + ++q; + } + else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { + if ( *(p+1) == CR ) { + p += 2; + } + else { + ++p; + } + *q = LF; + ++q; + } + else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { + // Entities handled by tinyXML2: + // - special entities in the entity table [in/out] + // - numeric character reference [in] + // 中 or 中 + + if ( *(p+1) == '#' ) { + const int buflen = 10; + char buf[buflen] = { 0 }; + int len = 0; + const char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); + if ( adjusted == 0 ) { + *q = *p; + ++p; + ++q; + } + else { + TIXMLASSERT( 0 <= len && len <= buflen ); + TIXMLASSERT( q + len <= adjusted ); + p = adjusted; + memcpy( q, buf, len ); + q += len; + } + } + else { + bool entityFound = false; + for( int i = 0; i < NUM_ENTITIES; ++i ) { + const Entity& entity = entities[i]; + if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 + && *( p + entity.length + 1 ) == ';' ) { + // Found an entity - convert. + *q = entity.value; + ++q; + p += entity.length + 2; + entityFound = true; + break; + } + } + if ( !entityFound ) { + // fixme: treat as error? + ++p; + ++q; + } + } + } + else { + *q = *p; + ++p; + ++q; + } + } + *q = 0; + } + // The loop below has plenty going on, and this + // is a less useful mode. Break it out. + if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { + CollapseWhitespace(); + } + _flags = (_flags & NEEDS_DELETE); + } + TIXMLASSERT( _start ); + return _start; +} + + + + +// --------- XMLUtil ----------- // + +const char* XMLUtil::writeBoolTrue = "true"; +const char* XMLUtil::writeBoolFalse = "false"; + +void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) +{ + static const char* defTrue = "true"; + static const char* defFalse = "false"; + + writeBoolTrue = (writeTrue) ? writeTrue : defTrue; + writeBoolFalse = (writeFalse) ? writeFalse : defFalse; +} + + +const char* XMLUtil::ReadBOM( const char* p, bool* bom ) +{ + TIXMLASSERT( p ); + TIXMLASSERT( bom ); + *bom = false; + const unsigned char* pu = reinterpret_cast(p); + // Check for BOM: + if ( *(pu+0) == TIXML_UTF_LEAD_0 + && *(pu+1) == TIXML_UTF_LEAD_1 + && *(pu+2) == TIXML_UTF_LEAD_2 ) { + *bom = true; + p += 3; + } + TIXMLASSERT( p ); + return p; +} + + +void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) +{ + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + + if (input < 0x80) { + *length = 1; + } + else if ( input < 0x800 ) { + *length = 2; + } + else if ( input < 0x10000 ) { + *length = 3; + } + else if ( input < 0x200000 ) { + *length = 4; + } + else { + *length = 0; // This code won't convert this correctly anyway. + return; + } + + output += *length; + + // Scary scary fall throughs are annotated with carefully designed comments + // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc + switch (*length) { + case 4: + --output; + *output = static_cast((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 3: + --output; + *output = static_cast((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 2: + --output; + *output = static_cast((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 1: + --output; + *output = static_cast(input | FIRST_BYTE_MARK[*length]); + break; + default: + TIXMLASSERT( false ); + } +} + + +const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) +{ + // Presume an entity, and pull it out. + *length = 0; + + if ( *(p+1) == '#' && *(p+2) ) { + unsigned long ucs = 0; + TIXMLASSERT( sizeof( ucs ) >= 4 ); + ptrdiff_t delta = 0; + unsigned mult = 1; + static const char SEMICOLON = ';'; + + if ( *(p+2) == 'x' ) { + // Hexadecimal. + const char* q = p+3; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != 'x' ) { + unsigned int digit = 0; + + if ( *q >= '0' && *q <= '9' ) { + digit = *q - '0'; + } + else if ( *q >= 'a' && *q <= 'f' ) { + digit = *q - 'a' + 10; + } + else if ( *q >= 'A' && *q <= 'F' ) { + digit = *q - 'A' + 10; + } + else { + return 0; + } + TIXMLASSERT( digit < 16 ); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + TIXMLASSERT( mult <= UINT_MAX / 16 ); + mult *= 16; + --q; + } + } + else { + // Decimal. + const char* q = p+2; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != '#' ) { + if ( *q >= '0' && *q <= '9' ) { + const unsigned int digit = *q - '0'; + TIXMLASSERT( digit < 10 ); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + } + else { + return 0; + } + TIXMLASSERT( mult <= UINT_MAX / 10 ); + mult *= 10; + --q; + } + } + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8( ucs, value, length ); + return p + delta + 1; + } + return p+1; +} + + +void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); +} + + +void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); +} + + +void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); +} + +/* + ToStr() of a number is a very tricky topic. + https://github.com/leethomason/tinyxml2/issues/106 +*/ +void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); +} + + +void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); +} + + +void XMLUtil::ToStr( int64_t v, char* buffer, int bufferSize ) +{ + // horrible syntax trick to make the compiler happy about %lld + TIXML_SNPRINTF(buffer, bufferSize, "%lld", static_cast(v)); +} + +void XMLUtil::ToStr( uint64_t v, char* buffer, int bufferSize ) +{ + // horrible syntax trick to make the compiler happy about %llu + TIXML_SNPRINTF(buffer, bufferSize, "%llu", (long long)v); +} + +bool XMLUtil::ToInt(const char* str, int* value) +{ + if (IsPrefixHex(str)) { + unsigned v; + if (TIXML_SSCANF(str, "%x", &v) == 1) { + *value = static_cast(v); + return true; + } + } + else { + if (TIXML_SSCANF(str, "%d", value) == 1) { + return true; + } + } + return false; +} + +bool XMLUtil::ToUnsigned(const char* str, unsigned* value) +{ + if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%x" : "%u", value) == 1) { + return true; + } + return false; +} + +bool XMLUtil::ToBool( const char* str, bool* value ) +{ + int ival = 0; + if ( ToInt( str, &ival )) { + *value = (ival==0) ? false : true; + return true; + } + static const char* TRUE_VALS[] = { "true", "True", "TRUE", 0 }; + static const char* FALSE_VALS[] = { "false", "False", "FALSE", 0 }; + + for (int i = 0; TRUE_VALS[i]; ++i) { + if (StringEqual(str, TRUE_VALS[i])) { + *value = true; + return true; + } + } + for (int i = 0; FALSE_VALS[i]; ++i) { + if (StringEqual(str, FALSE_VALS[i])) { + *value = false; + return true; + } + } + return false; +} + + +bool XMLUtil::ToFloat( const char* str, float* value ) +{ + if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { + return true; + } + return false; +} + + +bool XMLUtil::ToDouble( const char* str, double* value ) +{ + if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { + return true; + } + return false; +} + + +bool XMLUtil::ToInt64(const char* str, int64_t* value) +{ + if (IsPrefixHex(str)) { + unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llx + if (TIXML_SSCANF(str, "%llx", &v) == 1) { + *value = static_cast(v); + return true; + } + } + else { + long long v = 0; // horrible syntax trick to make the compiler happy about %lld + if (TIXML_SSCANF(str, "%lld", &v) == 1) { + *value = static_cast(v); + return true; + } + } + return false; +} + + +bool XMLUtil::ToUnsigned64(const char* str, uint64_t* value) { + unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llu + if(TIXML_SSCANF(str, IsPrefixHex(str) ? "%llx" : "%llu", &v) == 1) { + *value = (uint64_t)v; + return true; + } + return false; +} + + +char* XMLDocument::Identify( char* p, XMLNode** node ) +{ + TIXMLASSERT( node ); + TIXMLASSERT( p ); + char* const start = p; + int const startLine = _parseCurLineNum; + p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); + if( !*p ) { + *node = 0; + TIXMLASSERT( p ); + return p; + } + + // These strings define the matching patterns: + static const char* xmlHeader = { "( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += xmlHeaderLen; + } + else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += commentHeaderLen; + } + else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { + XMLText* text = CreateUnlinkedNode( _textPool ); + returnNode = text; + returnNode->_parseLineNum = _parseCurLineNum; + p += cdataHeaderLen; + text->SetCData( true ); + } + else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += dtdHeaderLen; + } + else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _elementPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += elementHeaderLen; + } + else { + returnNode = CreateUnlinkedNode( _textPool ); + returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character + p = start; // Back it up, all the text counts. + _parseCurLineNum = startLine; + } + + TIXMLASSERT( returnNode ); + TIXMLASSERT( p ); + *node = returnNode; + return p; +} + + +bool XMLDocument::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } + } + return visitor->VisitExit( *this ); +} + + +// --------- XMLNode ----------- // + +XMLNode::XMLNode( XMLDocument* doc ) : + _document( doc ), + _parent( 0 ), + _value(), + _parseLineNum( 0 ), + _firstChild( 0 ), _lastChild( 0 ), + _prev( 0 ), _next( 0 ), + _userData( 0 ), + _memPool( 0 ) +{ +} + + +XMLNode::~XMLNode() +{ + DeleteChildren(); + if ( _parent ) { + _parent->Unlink( this ); + } +} + +const char* XMLNode::Value() const +{ + // Edge case: XMLDocuments don't have a Value. Return null. + if ( this->ToDocument() ) + return 0; + return _value.GetStr(); +} + +void XMLNode::SetValue( const char* str, bool staticMem ) +{ + if ( staticMem ) { + _value.SetInternedStr( str ); + } + else { + _value.SetStr( str ); + } +} + +XMLNode* XMLNode::DeepClone(XMLDocument* target) const +{ + XMLNode* clone = this->ShallowClone(target); + if (!clone) return 0; + + for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { + XMLNode* childClone = child->DeepClone(target); + TIXMLASSERT(childClone); + clone->InsertEndChild(childClone); + } + return clone; +} + +void XMLNode::DeleteChildren() +{ + while( _firstChild ) { + TIXMLASSERT( _lastChild ); + DeleteChild( _firstChild ); + } + _firstChild = _lastChild = 0; +} + + +void XMLNode::Unlink( XMLNode* child ) +{ + TIXMLASSERT( child ); + TIXMLASSERT( child->_document == _document ); + TIXMLASSERT( child->_parent == this ); + if ( child == _firstChild ) { + _firstChild = _firstChild->_next; + } + if ( child == _lastChild ) { + _lastChild = _lastChild->_prev; + } + + if ( child->_prev ) { + child->_prev->_next = child->_next; + } + if ( child->_next ) { + child->_next->_prev = child->_prev; + } + child->_next = 0; + child->_prev = 0; + child->_parent = 0; +} + + +void XMLNode::DeleteChild( XMLNode* node ) +{ + TIXMLASSERT( node ); + TIXMLASSERT( node->_document == _document ); + TIXMLASSERT( node->_parent == this ); + Unlink( node ); + TIXMLASSERT(node->_prev == 0); + TIXMLASSERT(node->_next == 0); + TIXMLASSERT(node->_parent == 0); + DeleteNode( node ); +} + + +XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); + + if ( _lastChild ) { + TIXMLASSERT( _firstChild ); + TIXMLASSERT( _lastChild->_next == 0 ); + _lastChild->_next = addThis; + addThis->_prev = _lastChild; + _lastChild = addThis; + + addThis->_next = 0; + } + else { + TIXMLASSERT( _firstChild == 0 ); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; +} + + +XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); + + if ( _firstChild ) { + TIXMLASSERT( _lastChild ); + TIXMLASSERT( _firstChild->_prev == 0 ); + + _firstChild->_prev = addThis; + addThis->_next = _firstChild; + _firstChild = addThis; + + addThis->_prev = 0; + } + else { + TIXMLASSERT( _lastChild == 0 ); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; +} + + +XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + + TIXMLASSERT( afterThis ); + + if ( afterThis->_parent != this ) { + TIXMLASSERT( false ); + return 0; + } + if ( afterThis == addThis ) { + // Current state: BeforeThis -> AddThis -> OneAfterAddThis + // Now AddThis must disappear from it's location and then + // reappear between BeforeThis and OneAfterAddThis. + // So just leave it where it is. + return addThis; + } + + if ( afterThis->_next == 0 ) { + // The last node or the only node. + return InsertEndChild( addThis ); + } + InsertChildPreamble( addThis ); + addThis->_prev = afterThis; + addThis->_next = afterThis->_next; + afterThis->_next->_prev = addThis; + afterThis->_next = addThis; + addThis->_parent = this; + return addThis; +} + + + + +const XMLElement* XMLNode::FirstChildElement( const char* name ) const +{ + for( const XMLNode* node = _firstChild; node; node = node->_next ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +const XMLElement* XMLNode::LastChildElement( const char* name ) const +{ + for( const XMLNode* node = _lastChild; node; node = node->_prev ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +const XMLElement* XMLNode::NextSiblingElement( const char* name ) const +{ + for( const XMLNode* node = _next; node; node = node->_next ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const +{ + for( const XMLNode* node = _prev; node; node = node->_prev ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) +{ + // This is a recursive method, but thinking about it "at the current level" + // it is a pretty simple flat list: + // + // + // + // With a special case: + // + // + // + // + // Where the closing element (/foo) *must* be the next thing after the opening + // element, and the names must match. BUT the tricky bit is that the closing + // element will be read by the child. + // + // 'endTag' is the end tag for this node, it is returned by a call to a child. + // 'parentEnd' is the end tag for the parent, which is filled in and returned. + + XMLDocument::DepthTracker tracker(_document); + if (_document->Error()) + return 0; + + while( p && *p ) { + XMLNode* node = 0; + + p = _document->Identify( p, &node ); + TIXMLASSERT( p ); + if ( node == 0 ) { + break; + } + + const int initialLineNum = node->_parseLineNum; + + StrPair endTag; + p = node->ParseDeep( p, &endTag, curLineNumPtr ); + if ( !p ) { + DeleteNode( node ); + if ( !_document->Error() ) { + _document->SetError( XML_ERROR_PARSING, initialLineNum, 0); + } + break; + } + + const XMLDeclaration* const decl = node->ToDeclaration(); + if ( decl ) { + // Declarations are only allowed at document level + // + // Multiple declarations are allowed but all declarations + // must occur before anything else. + // + // Optimized due to a security test case. If the first node is + // a declaration, and the last node is a declaration, then only + // declarations have so far been added. + bool wellLocated = false; + + if (ToDocument()) { + if (FirstChild()) { + wellLocated = + FirstChild() && + FirstChild()->ToDeclaration() && + LastChild() && + LastChild()->ToDeclaration(); + } + else { + wellLocated = true; + } + } + if ( !wellLocated ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); + DeleteNode( node ); + break; + } + } + + XMLElement* ele = node->ToElement(); + if ( ele ) { + // We read the end tag. Return it to the parent. + if ( ele->ClosingType() == XMLElement::CLOSING ) { + if ( parentEndTag ) { + ele->_value.TransferTo( parentEndTag ); + } + node->_memPool->SetTracked(); // created and then immediately deleted. + DeleteNode( node ); + return p; + } + + // Handle an end tag returned to this level. + // And handle a bunch of annoying errors. + bool mismatch = false; + if ( endTag.Empty() ) { + if ( ele->ClosingType() == XMLElement::OPEN ) { + mismatch = true; + } + } + else { + if ( ele->ClosingType() != XMLElement::OPEN ) { + mismatch = true; + } + else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { + mismatch = true; + } + } + if ( mismatch ) { + _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); + DeleteNode( node ); + break; + } + } + InsertEndChild( node ); + } + return 0; +} + +/*static*/ void XMLNode::DeleteNode( XMLNode* node ) +{ + if ( node == 0 ) { + return; + } + TIXMLASSERT(node->_document); + if (!node->ToDocument()) { + node->_document->MarkInUse(node); + } + + MemPool* pool = node->_memPool; + node->~XMLNode(); + pool->Free( node ); +} + +void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const +{ + TIXMLASSERT( insertThis ); + TIXMLASSERT( insertThis->_document == _document ); + + if (insertThis->_parent) { + insertThis->_parent->Unlink( insertThis ); + } + else { + insertThis->_document->MarkInUse(insertThis); + insertThis->_memPool->SetTracked(); + } +} + +const XMLElement* XMLNode::ToElementWithName( const char* name ) const +{ + const XMLElement* element = this->ToElement(); + if ( element == 0 ) { + return 0; + } + if ( name == 0 ) { + return element; + } + if ( XMLUtil::StringEqual( element->Name(), name ) ) { + return element; + } + return 0; +} + +// --------- XMLText ---------- // +char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + if ( this->CData() ) { + p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 ); + } + return p; + } + else { + int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; + if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { + flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; + } + + p = _value.ParseText( p, "<", flags, curLineNumPtr ); + if ( p && *p ) { + return p-1; + } + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 ); + } + } + return 0; +} + + +XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? + text->SetCData( this->CData() ); + return text; +} + + +bool XMLText::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLText* text = compare->ToText(); + return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); +} + + +bool XMLText::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + + +// --------- XMLComment ---------- // + +XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLComment::~XMLComment() +{ +} + + +char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + // Comment parses as text. + p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 ); + } + return p; +} + + +XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? + return comment; +} + + +bool XMLComment::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLComment* comment = compare->ToComment(); + return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); +} + + +bool XMLComment::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + + +// --------- XMLDeclaration ---------- // + +XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLDeclaration::~XMLDeclaration() +{ + //printf( "~XMLDeclaration\n" ); +} + + +char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + // Declaration parses as text. + p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 ); + } + return p; +} + + +XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? + return dec; +} + + +bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLDeclaration* declaration = compare->ToDeclaration(); + return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); +} + + + +bool XMLDeclaration::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + +// --------- XMLUnknown ---------- // + +XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLUnknown::~XMLUnknown() +{ +} + + +char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + // Unknown parses as text. + p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 ); + } + return p; +} + + +XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? + return text; +} + + +bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLUnknown* unknown = compare->ToUnknown(); + return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); +} + + +bool XMLUnknown::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + +// --------- XMLAttribute ---------- // + +const char* XMLAttribute::Name() const +{ + return _name.GetStr(); +} + +const char* XMLAttribute::Value() const +{ + return _value.GetStr(); +} + +char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr ) +{ + // Parse using the name rules: bug fix, was using ParseText before + p = _name.ParseName( p ); + if ( !p || !*p ) { + return 0; + } + + // Skip white space before = + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( *p != '=' ) { + return 0; + } + + ++p; // move up to opening quote + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( *p != '\"' && *p != '\'' ) { + return 0; + } + + const char endTag[2] = { *p, 0 }; + ++p; // move past opening quote + + p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr ); + return p; +} + + +void XMLAttribute::SetName( const char* n ) +{ + _name.SetStr( n ); +} + + +XMLError XMLAttribute::QueryIntValue( int* value ) const +{ + if ( XMLUtil::ToInt( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const +{ + if ( XMLUtil::ToUnsigned( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryInt64Value(int64_t* value) const +{ + if (XMLUtil::ToInt64(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryUnsigned64Value(uint64_t* value) const +{ + if(XMLUtil::ToUnsigned64(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryBoolValue( bool* value ) const +{ + if ( XMLUtil::ToBool( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryFloatValue( float* value ) const +{ + if ( XMLUtil::ToFloat( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryDoubleValue( double* value ) const +{ + if ( XMLUtil::ToDouble( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +void XMLAttribute::SetAttribute( const char* v ) +{ + _value.SetStr( v ); +} + + +void XMLAttribute::SetAttribute( int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute( unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute(int64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); +} + +void XMLAttribute::SetAttribute(uint64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); +} + + +void XMLAttribute::SetAttribute( bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( float v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +// --------- XMLElement ---------- // +XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), + _closingType( OPEN ), + _rootAttribute( 0 ) +{ +} + + +XMLElement::~XMLElement() +{ + while( _rootAttribute ) { + XMLAttribute* next = _rootAttribute->_next; + DeleteAttribute( _rootAttribute ); + _rootAttribute = next; + } +} + + +const XMLAttribute* XMLElement::FindAttribute( const char* name ) const +{ + for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { + if ( XMLUtil::StringEqual( a->Name(), name ) ) { + return a; + } + } + return 0; +} + + +const char* XMLElement::Attribute( const char* name, const char* value ) const +{ + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return 0; + } + if ( !value || XMLUtil::StringEqual( a->Value(), value )) { + return a->Value(); + } + return 0; +} + +int XMLElement::IntAttribute(const char* name, int defaultValue) const +{ + int i = defaultValue; + QueryIntAttribute(name, &i); + return i; +} + +unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const +{ + unsigned i = defaultValue; + QueryUnsignedAttribute(name, &i); + return i; +} + +int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const +{ + int64_t i = defaultValue; + QueryInt64Attribute(name, &i); + return i; +} + +uint64_t XMLElement::Unsigned64Attribute(const char* name, uint64_t defaultValue) const +{ + uint64_t i = defaultValue; + QueryUnsigned64Attribute(name, &i); + return i; +} + +bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const +{ + bool b = defaultValue; + QueryBoolAttribute(name, &b); + return b; +} + +double XMLElement::DoubleAttribute(const char* name, double defaultValue) const +{ + double d = defaultValue; + QueryDoubleAttribute(name, &d); + return d; +} + +float XMLElement::FloatAttribute(const char* name, float defaultValue) const +{ + float f = defaultValue; + QueryFloatAttribute(name, &f); + return f; +} + +const char* XMLElement::GetText() const +{ + /* skip comment node */ + const XMLNode* node = FirstChild(); + while (node) { + if (node->ToComment()) { + node = node->NextSibling(); + continue; + } + break; + } + + if ( node && node->ToText() ) { + return node->Value(); + } + return 0; +} + + +void XMLElement::SetText( const char* inText ) +{ + if ( FirstChild() && FirstChild()->ToText() ) + FirstChild()->SetValue( inText ); + else { + XMLText* theText = GetDocument()->NewText( inText ); + InsertFirstChild( theText ); + } +} + + +void XMLElement::SetText( int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText(int64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); +} + +void XMLElement::SetText(uint64_t v) { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); +} + + +void XMLElement::SetText( bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( float v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +XMLError XMLElement::QueryIntText( int* ival ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToInt( t, ival ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToUnsigned( t, uval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryInt64Text(int64_t* ival) const +{ + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToInt64(t, ival)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryUnsigned64Text(uint64_t* ival) const +{ + if(FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if(XMLUtil::ToUnsigned64(t, ival)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryBoolText( bool* bval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToBool( t, bval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryDoubleText( double* dval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToDouble( t, dval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryFloatText( float* fval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToFloat( t, fval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + +int XMLElement::IntText(int defaultValue) const +{ + int i = defaultValue; + QueryIntText(&i); + return i; +} + +unsigned XMLElement::UnsignedText(unsigned defaultValue) const +{ + unsigned i = defaultValue; + QueryUnsignedText(&i); + return i; +} + +int64_t XMLElement::Int64Text(int64_t defaultValue) const +{ + int64_t i = defaultValue; + QueryInt64Text(&i); + return i; +} + +uint64_t XMLElement::Unsigned64Text(uint64_t defaultValue) const +{ + uint64_t i = defaultValue; + QueryUnsigned64Text(&i); + return i; +} + +bool XMLElement::BoolText(bool defaultValue) const +{ + bool b = defaultValue; + QueryBoolText(&b); + return b; +} + +double XMLElement::DoubleText(double defaultValue) const +{ + double d = defaultValue; + QueryDoubleText(&d); + return d; +} + +float XMLElement::FloatText(float defaultValue) const +{ + float f = defaultValue; + QueryFloatText(&f); + return f; +} + + +XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) +{ + XMLAttribute* last = 0; + XMLAttribute* attrib = 0; + for( attrib = _rootAttribute; + attrib; + last = attrib, attrib = attrib->_next ) { + if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { + break; + } + } + if ( !attrib ) { + attrib = CreateAttribute(); + TIXMLASSERT( attrib ); + if ( last ) { + TIXMLASSERT( last->_next == 0 ); + last->_next = attrib; + } + else { + TIXMLASSERT( _rootAttribute == 0 ); + _rootAttribute = attrib; + } + attrib->SetName( name ); + } + return attrib; +} + + +void XMLElement::DeleteAttribute( const char* name ) +{ + XMLAttribute* prev = 0; + for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { + if ( XMLUtil::StringEqual( name, a->Name() ) ) { + if ( prev ) { + prev->_next = a->_next; + } + else { + _rootAttribute = a->_next; + } + DeleteAttribute( a ); + break; + } + prev = a; + } +} + + +char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr ) +{ + XMLAttribute* prevAttribute = 0; + + // Read the attributes. + while( p ) { + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( !(*p) ) { + _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() ); + return 0; + } + + // attribute. + if (XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { + XMLAttribute* attrib = CreateAttribute(); + TIXMLASSERT( attrib ); + attrib->_parseLineNum = _document->_parseCurLineNum; + + const int attrLineNum = attrib->_parseLineNum; + + p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr ); + if ( !p || Attribute( attrib->Name() ) ) { + DeleteAttribute( attrib ); + _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() ); + return 0; + } + // There is a minor bug here: if the attribute in the source xml + // document is duplicated, it will not be detected and the + // attribute will be doubly added. However, tracking the 'prevAttribute' + // avoids re-scanning the attribute list. Preferring performance for + // now, may reconsider in the future. + if ( prevAttribute ) { + TIXMLASSERT( prevAttribute->_next == 0 ); + prevAttribute->_next = attrib; + } + else { + TIXMLASSERT( _rootAttribute == 0 ); + _rootAttribute = attrib; + } + prevAttribute = attrib; + } + // end of the tag + else if ( *p == '>' ) { + ++p; + break; + } + // end of the tag + else if ( *p == '/' && *(p+1) == '>' ) { + _closingType = CLOSED; + return p+2; // done; sealed element. + } + else { + _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 ); + return 0; + } + } + return p; +} + +void XMLElement::DeleteAttribute( XMLAttribute* attribute ) +{ + if ( attribute == 0 ) { + return; + } + MemPool* pool = attribute->_memPool; + attribute->~XMLAttribute(); + pool->Free( attribute ); +} + +XMLAttribute* XMLElement::CreateAttribute() +{ + TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); + XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); + TIXMLASSERT( attrib ); + attrib->_memPool = &_document->_attributePool; + attrib->_memPool->SetTracked(); + return attrib; +} + + +XMLElement* XMLElement::InsertNewChildElement(const char* name) +{ + XMLElement* node = _document->NewElement(name); + return InsertEndChild(node) ? node : 0; +} + +XMLComment* XMLElement::InsertNewComment(const char* comment) +{ + XMLComment* node = _document->NewComment(comment); + return InsertEndChild(node) ? node : 0; +} + +XMLText* XMLElement::InsertNewText(const char* text) +{ + XMLText* node = _document->NewText(text); + return InsertEndChild(node) ? node : 0; +} + +XMLDeclaration* XMLElement::InsertNewDeclaration(const char* text) +{ + XMLDeclaration* node = _document->NewDeclaration(text); + return InsertEndChild(node) ? node : 0; +} + +XMLUnknown* XMLElement::InsertNewUnknown(const char* text) +{ + XMLUnknown* node = _document->NewUnknown(text); + return InsertEndChild(node) ? node : 0; +} + + + +// +// +// foobar +// +char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) +{ + // Read the element name. + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + + // The closing element is the form. It is + // parsed just like a regular element then deleted from + // the DOM. + if ( *p == '/' ) { + _closingType = CLOSING; + ++p; + } + + p = _value.ParseName( p ); + if ( _value.Empty() ) { + return 0; + } + + p = ParseAttributes( p, curLineNumPtr ); + if ( !p || !*p || _closingType != OPEN ) { + return p; + } + + p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr ); + return p; +} + + + +XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? + for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { + element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? + } + return element; +} + + +bool XMLElement::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLElement* other = compare->ToElement(); + if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { + + const XMLAttribute* a=FirstAttribute(); + const XMLAttribute* b=other->FirstAttribute(); + + while ( a && b ) { + if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { + return false; + } + a = a->Next(); + b = b->Next(); + } + if ( a || b ) { + // different count + return false; + } + return true; + } + return false; +} + + +bool XMLElement::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this, _rootAttribute ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } + } + return visitor->VisitExit( *this ); +} + + +// --------- XMLDocument ----------- // + +// Warning: List must match 'enum XMLError' +const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { + "XML_SUCCESS", + "XML_NO_ATTRIBUTE", + "XML_WRONG_ATTRIBUTE_TYPE", + "XML_ERROR_FILE_NOT_FOUND", + "XML_ERROR_FILE_COULD_NOT_BE_OPENED", + "XML_ERROR_FILE_READ_ERROR", + "XML_ERROR_PARSING_ELEMENT", + "XML_ERROR_PARSING_ATTRIBUTE", + "XML_ERROR_PARSING_TEXT", + "XML_ERROR_PARSING_CDATA", + "XML_ERROR_PARSING_COMMENT", + "XML_ERROR_PARSING_DECLARATION", + "XML_ERROR_PARSING_UNKNOWN", + "XML_ERROR_EMPTY_DOCUMENT", + "XML_ERROR_MISMATCHED_ELEMENT", + "XML_ERROR_PARSING", + "XML_CAN_NOT_CONVERT_TEXT", + "XML_NO_TEXT_NODE", + "XML_ELEMENT_DEPTH_EXCEEDED" +}; + + +XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) : + XMLNode( 0 ), + _writeBOM( false ), + _processEntities( processEntities ), + _errorID(XML_SUCCESS), + _whitespaceMode( whitespaceMode ), + _errorStr(), + _errorLineNum( 0 ), + _charBuffer( 0 ), + _parseCurLineNum( 0 ), + _parsingDepth(0), + _unlinked(), + _elementPool(), + _attributePool(), + _textPool(), + _commentPool() +{ + // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) + _document = this; +} + + +XMLDocument::~XMLDocument() +{ + Clear(); +} + + +void XMLDocument::MarkInUse(const XMLNode* const node) +{ + TIXMLASSERT(node); + TIXMLASSERT(node->_parent == 0); + + for (int i = 0; i < _unlinked.Size(); ++i) { + if (node == _unlinked[i]) { + _unlinked.SwapRemove(i); + break; + } + } +} + +void XMLDocument::Clear() +{ + DeleteChildren(); + while( _unlinked.Size()) { + DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. + } + +#ifdef TINYXML2_DEBUG + const bool hadError = Error(); +#endif + ClearError(); + + delete [] _charBuffer; + _charBuffer = 0; + _parsingDepth = 0; + +#if 0 + _textPool.Trace( "text" ); + _elementPool.Trace( "element" ); + _commentPool.Trace( "comment" ); + _attributePool.Trace( "attribute" ); +#endif + +#ifdef TINYXML2_DEBUG + if ( !hadError ) { + TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); + TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); + TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); + TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); + } +#endif +} + + +void XMLDocument::DeepCopy(XMLDocument* target) const +{ + TIXMLASSERT(target); + if (target == this) { + return; // technically success - a no-op. + } + + target->Clear(); + for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { + target->InsertEndChild(node->DeepClone(target)); + } +} + +XMLElement* XMLDocument::NewElement( const char* name ) +{ + XMLElement* ele = CreateUnlinkedNode( _elementPool ); + ele->SetName( name ); + return ele; +} + + +XMLComment* XMLDocument::NewComment( const char* str ) +{ + XMLComment* comment = CreateUnlinkedNode( _commentPool ); + comment->SetValue( str ); + return comment; +} + + +XMLText* XMLDocument::NewText( const char* str ) +{ + XMLText* text = CreateUnlinkedNode( _textPool ); + text->SetValue( str ); + return text; +} + + +XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) +{ + XMLDeclaration* dec = CreateUnlinkedNode( _commentPool ); + dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); + return dec; +} + + +XMLUnknown* XMLDocument::NewUnknown( const char* str ) +{ + XMLUnknown* unk = CreateUnlinkedNode( _commentPool ); + unk->SetValue( str ); + return unk; +} + +static FILE* callfopen( const char* filepath, const char* mode ) +{ + TIXMLASSERT( filepath ); + TIXMLASSERT( mode ); +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + FILE* fp = 0; + const errno_t err = fopen_s( &fp, filepath, mode ); + if ( err ) { + return 0; + } +#else + FILE* fp = fopen( filepath, mode ); +#endif + return fp; +} + +void XMLDocument::DeleteNode( XMLNode* node ) { + TIXMLASSERT( node ); + TIXMLASSERT(node->_document == this ); + if (node->_parent) { + node->_parent->DeleteChild( node ); + } + else { + // Isn't in the tree. + // Use the parent delete. + // Also, we need to mark it tracked: we 'know' + // it was never used. + node->_memPool->SetTracked(); + // Call the static XMLNode version: + XMLNode::DeleteNode(node); + } +} + + +XMLError XMLDocument::LoadFile( const char* filename ) +{ + if ( !filename ) { + TIXMLASSERT( false ); + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); + return _errorID; + } + + Clear(); + FILE* fp = callfopen( filename, "rb" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ); + return _errorID; + } + LoadFile( fp ); + fclose( fp ); + return _errorID; +} + +XMLError XMLDocument::LoadFile( FILE* fp ) +{ + Clear(); + + TIXML_FSEEK( fp, 0, SEEK_SET ); + if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + TIXML_FSEEK( fp, 0, SEEK_END ); + + unsigned long long filelength; + { + const long long fileLengthSigned = TIXML_FTELL( fp ); + TIXML_FSEEK( fp, 0, SEEK_SET ); + if ( fileLengthSigned == -1L ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + TIXMLASSERT( fileLengthSigned >= 0 ); + filelength = static_cast(fileLengthSigned); + } + + const size_t maxSizeT = static_cast(-1); + // We'll do the comparison as an unsigned long long, because that's guaranteed to be at + // least 8 bytes, even on a 32-bit platform. + if ( filelength >= static_cast(maxSizeT) ) { + // Cannot handle files which won't fit in buffer together with null terminator + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + if ( filelength == 0 ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + + const size_t size = static_cast(filelength); + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[size+1]; + const size_t read = fread( _charBuffer, 1, size, fp ); + if ( read != size ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + _charBuffer[size] = 0; + + Parse(); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( const char* filename, bool compact ) +{ + if ( !filename ) { + TIXMLASSERT( false ); + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); + return _errorID; + } + + FILE* fp = callfopen( filename, "w" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ); + return _errorID; + } + SaveFile(fp, compact); + fclose( fp ); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) +{ + // Clear any error from the last save, otherwise it will get reported + // for *this* call. + ClearError(); + XMLPrinter stream( fp, compact ); + Print( &stream ); + return _errorID; +} + + +XMLError XMLDocument::Parse( const char* p, size_t len ) +{ + Clear(); + + if ( len == 0 || !p || !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + if ( len == static_cast(-1) ) { + len = strlen( p ); + } + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[ len+1 ]; + memcpy( _charBuffer, p, len ); + _charBuffer[len] = 0; + + Parse(); + if ( Error() ) { + // clean up now essentially dangling memory. + // and the parse fail can put objects in the + // pools that are dead and inaccessible. + DeleteChildren(); + _elementPool.Clear(); + _attributePool.Clear(); + _textPool.Clear(); + _commentPool.Clear(); + } + return _errorID; +} + + +void XMLDocument::Print( XMLPrinter* streamer ) const +{ + if ( streamer ) { + Accept( streamer ); + } + else { + XMLPrinter stdoutStreamer( stdout ); + Accept( &stdoutStreamer ); + } +} + + +void XMLDocument::ClearError() { + _errorID = XML_SUCCESS; + _errorLineNum = 0; + _errorStr.Reset(); +} + + +void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... ) +{ + TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); + _errorID = error; + _errorLineNum = lineNum; + _errorStr.Reset(); + + const size_t BUFFER_SIZE = 1000; + char* buffer = new char[BUFFER_SIZE]; + + TIXMLASSERT(sizeof(error) <= sizeof(int)); + TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); + + if (format) { + size_t len = strlen(buffer); + TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); + len = strlen(buffer); + + va_list va; + va_start(va, format); + TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); + va_end(va); + } + _errorStr.SetStr(buffer); + delete[] buffer; +} + + +/*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) +{ + TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT ); + const char* errorName = _errorNames[errorID]; + TIXMLASSERT( errorName && errorName[0] ); + return errorName; +} + +const char* XMLDocument::ErrorStr() const +{ + return _errorStr.Empty() ? "" : _errorStr.GetStr(); +} + + +void XMLDocument::PrintError() const +{ + printf("%s\n", ErrorStr()); +} + +const char* XMLDocument::ErrorName() const +{ + return ErrorIDToName(_errorID); +} + +void XMLDocument::Parse() +{ + TIXMLASSERT( NoChildren() ); // Clear() must have been called previously + TIXMLASSERT( _charBuffer ); + _parseCurLineNum = 1; + _parseLineNum = 1; + char* p = _charBuffer; + p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); + p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); + if ( !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return; + } + ParseDeep(p, 0, &_parseCurLineNum ); +} + +void XMLDocument::PushDepth() +{ + _parsingDepth++; + if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) { + SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep." ); + } +} + +void XMLDocument::PopDepth() +{ + TIXMLASSERT(_parsingDepth > 0); + --_parsingDepth; +} + +XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : + _elementJustOpened( false ), + _stack(), + _firstElement( true ), + _fp( file ), + _depth( depth ), + _textDepth( -1 ), + _processEntities( true ), + _compactMode( compact ), + _buffer() +{ + for( int i=0; i(entityValue); + TIXMLASSERT( flagIndex < ENTITY_RANGE ); + _entityFlag[flagIndex] = true; + } + _restrictedEntityFlag[static_cast('&')] = true; + _restrictedEntityFlag[static_cast('<')] = true; + _restrictedEntityFlag[static_cast('>')] = true; // not required, but consistency is nice + _buffer.Push( 0 ); +} + + +void XMLPrinter::Print( const char* format, ... ) +{ + va_list va; + va_start( va, format ); + + if ( _fp ) { + vfprintf( _fp, format, va ); + } + else { + const int len = TIXML_VSCPRINTF( format, va ); + // Close out and re-start the va-args + va_end( va ); + TIXMLASSERT( len >= 0 ); + va_start( va, format ); + TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); + char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. + TIXML_VSNPRINTF( p, len+1, format, va ); + } + va_end( va ); +} + + +void XMLPrinter::Write( const char* data, size_t size ) +{ + if ( _fp ) { + fwrite ( data , sizeof(char), size, _fp); + } + else { + char* p = _buffer.PushArr( static_cast(size) ) - 1; // back up over the null terminator. + memcpy( p, data, size ); + p[size] = 0; + } +} + + +void XMLPrinter::Putc( char ch ) +{ + if ( _fp ) { + fputc ( ch, _fp); + } + else { + char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator. + p[0] = ch; + p[1] = 0; + } +} + + +void XMLPrinter::PrintSpace( int depth ) +{ + for( int i=0; i 0 && *q < ENTITY_RANGE ) { + // Check for entities. If one is found, flush + // the stream up until the entity, write the + // entity, and keep looking. + if ( flag[static_cast(*q)] ) { + while ( p < q ) { + const size_t delta = q - p; + const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast(delta); + Write( p, toPrint ); + p += toPrint; + } + bool entityPatternPrinted = false; + for( int i=0; i(delta); + Write( p, toPrint ); + } + } + else { + Write( p ); + } +} + + +void XMLPrinter::PushHeader( bool writeBOM, bool writeDec ) +{ + if ( writeBOM ) { + static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; + Write( reinterpret_cast< const char* >( bom ) ); + } + if ( writeDec ) { + PushDeclaration( "xml version=\"1.0\"" ); + } +} + +void XMLPrinter::PrepareForNewNode( bool compactMode ) +{ + SealElementIfJustOpened(); + + if ( compactMode ) { + return; + } + + if ( _firstElement ) { + PrintSpace (_depth); + } else if ( _textDepth < 0) { + Putc( '\n' ); + PrintSpace( _depth ); + } + + _firstElement = false; +} + +void XMLPrinter::OpenElement( const char* name, bool compactMode ) +{ + PrepareForNewNode( compactMode ); + _stack.Push( name ); + + Write ( "<" ); + Write ( name ); + + _elementJustOpened = true; + ++_depth; +} + + +void XMLPrinter::PushAttribute( const char* name, const char* value ) +{ + TIXMLASSERT( _elementJustOpened ); + Putc ( ' ' ); + Write( name ); + Write( "=\"" ); + PrintString( value, false ); + Putc ( '\"' ); +} + + +void XMLPrinter::PushAttribute( const char* name, int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute( const char* name, unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute(const char* name, int64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); +} + + +void XMLPrinter::PushAttribute(const char* name, uint64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); +} + + +void XMLPrinter::PushAttribute( const char* name, bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute( const char* name, double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::CloseElement( bool compactMode ) +{ + --_depth; + const char* name = _stack.Pop(); + + if ( _elementJustOpened ) { + Write( "/>" ); + } + else { + if ( _textDepth < 0 && !compactMode) { + Putc( '\n' ); + PrintSpace( _depth ); + } + Write ( "" ); + } + + if ( _textDepth == _depth ) { + _textDepth = -1; + } + if ( _depth == 0 && !compactMode) { + Putc( '\n' ); + } + _elementJustOpened = false; +} + + +void XMLPrinter::SealElementIfJustOpened() +{ + if ( !_elementJustOpened ) { + return; + } + _elementJustOpened = false; + Putc( '>' ); +} + + +void XMLPrinter::PushText( const char* text, bool cdata ) +{ + _textDepth = _depth-1; + + SealElementIfJustOpened(); + if ( cdata ) { + Write( "" ); + } + else { + PrintString( text, true ); + } +} + + +void XMLPrinter::PushText( int64_t value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( uint64_t value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); +} + + +void XMLPrinter::PushText( int value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( unsigned value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( bool value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( float value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( double value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushComment( const char* comment ) +{ + PrepareForNewNode( _compactMode ); + + Write( "" ); +} + + +void XMLPrinter::PushDeclaration( const char* value ) +{ + PrepareForNewNode( _compactMode ); + + Write( "" ); +} + + +void XMLPrinter::PushUnknown( const char* value ) +{ + PrepareForNewNode( _compactMode ); + + Write( "' ); +} + + +bool XMLPrinter::VisitEnter( const XMLDocument& doc ) +{ + _processEntities = doc.ProcessEntities(); + if ( doc.HasBOM() ) { + PushHeader( true, false ); + } + return true; +} + + +bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) +{ + const XMLElement* parentElem = 0; + if ( element.Parent() ) { + parentElem = element.Parent()->ToElement(); + } + const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; + OpenElement( element.Name(), compactMode ); + while ( attribute ) { + PushAttribute( attribute->Name(), attribute->Value() ); + attribute = attribute->Next(); + } + return true; +} + + +bool XMLPrinter::VisitExit( const XMLElement& element ) +{ + CloseElement( CompactMode(element) ); + return true; +} + + +bool XMLPrinter::Visit( const XMLText& text ) +{ + PushText( text.Value(), text.CData() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLComment& comment ) +{ + PushComment( comment.Value() ); + return true; +} + +bool XMLPrinter::Visit( const XMLDeclaration& declaration ) +{ + PushDeclaration( declaration.Value() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLUnknown& unknown ) +{ + PushUnknown( unknown.Value() ); + return true; +} + +} // namespace tinyxml2 diff --git a/modules/skybrowser/ext/tinyxml2/tinyxml2.h b/modules/skybrowser/ext/tinyxml2/tinyxml2.h new file mode 100644 index 0000000000..d257966c97 --- /dev/null +++ b/modules/skybrowser/ext/tinyxml2/tinyxml2.h @@ -0,0 +1,2380 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#ifndef TINYXML2_INCLUDED +#define TINYXML2_INCLUDED + +#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) +# include +# include +# include +# include +# include +# if defined(__PS3__) +# include +# endif +#else +# include +# include +# include +# include +# include +#endif +#include + +/* + TODO: intern strings instead of allocation. +*/ +/* + gcc: + g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe + + Formatting, Artistic Style: + AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h +*/ + +#if defined( _DEBUG ) || defined (__DEBUG__) +# ifndef TINYXML2_DEBUG +# define TINYXML2_DEBUG +# endif +#endif + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4251) +#endif + +#ifdef _WIN32 +# ifdef TINYXML2_EXPORT +# define TINYXML2_LIB __declspec(dllexport) +# elif defined(TINYXML2_IMPORT) +# define TINYXML2_LIB __declspec(dllimport) +# else +# define TINYXML2_LIB +# endif +#elif __GNUC__ >= 4 +# define TINYXML2_LIB __attribute__((visibility("default"))) +#else +# define TINYXML2_LIB +#endif + + +#if !defined(TIXMLASSERT) +#if defined(TINYXML2_DEBUG) +# if defined(_MSC_VER) +# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like +# define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } +# elif defined (ANDROID_NDK) +# include +# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } +# else +# include +# define TIXMLASSERT assert +# endif +#else +# define TIXMLASSERT( x ) {} +#endif +#endif + +/* Versioning, past 1.0.14: + http://semver.org/ +*/ +static const int TIXML2_MAJOR_VERSION = 8; +static const int TIXML2_MINOR_VERSION = 0; +static const int TIXML2_PATCH_VERSION = 0; + +#define TINYXML2_MAJOR_VERSION 8 +#define TINYXML2_MINOR_VERSION 0 +#define TINYXML2_PATCH_VERSION 0 + +// A fixed element depth limit is problematic. There needs to be a +// limit to avoid a stack overflow. However, that limit varies per +// system, and the capacity of the stack. On the other hand, it's a trivial +// attack that can result from ill, malicious, or even correctly formed XML, +// so there needs to be a limit in place. +static const int TINYXML2_MAX_ELEMENT_DEPTH = 100; + +namespace tinyxml2 +{ +class XMLDocument; +class XMLElement; +class XMLAttribute; +class XMLComment; +class XMLText; +class XMLDeclaration; +class XMLUnknown; +class XMLPrinter; + +/* + A class that wraps strings. Normally stores the start and end + pointers into the XML file itself, and will apply normalization + and entity translation if actually read. Can also store (and memory + manage) a traditional char[] + + Isn't clear why TINYXML2_LIB is needed; but seems to fix #719 +*/ +class TINYXML2_LIB StrPair +{ +public: + enum Mode { + NEEDS_ENTITY_PROCESSING = 0x01, + NEEDS_NEWLINE_NORMALIZATION = 0x02, + NEEDS_WHITESPACE_COLLAPSING = 0x04, + + TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_NAME = 0, + ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + COMMENT = NEEDS_NEWLINE_NORMALIZATION + }; + + StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} + ~StrPair(); + + void Set( char* start, char* end, int flags ) { + TIXMLASSERT( start ); + TIXMLASSERT( end ); + Reset(); + _start = start; + _end = end; + _flags = flags | NEEDS_FLUSH; + } + + const char* GetStr(); + + bool Empty() const { + return _start == _end; + } + + void SetInternedStr( const char* str ) { + Reset(); + _start = const_cast(str); + } + + void SetStr( const char* str, int flags=0 ); + + char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); + char* ParseName( char* in ); + + void TransferTo( StrPair* other ); + void Reset(); + +private: + void CollapseWhitespace(); + + enum { + NEEDS_FLUSH = 0x100, + NEEDS_DELETE = 0x200 + }; + + int _flags; + char* _start; + char* _end; + + StrPair( const StrPair& other ); // not supported + void operator=( const StrPair& other ); // not supported, use TransferTo() +}; + + +/* + A dynamic array of Plain Old Data. Doesn't support constructors, etc. + Has a small initial memory pool, so that low or no usage will not + cause a call to new/delete +*/ +template +class DynArray +{ +public: + DynArray() : + _mem( _pool ), + _allocated( INITIAL_SIZE ), + _size( 0 ) + { + } + + ~DynArray() { + if ( _mem != _pool ) { + delete [] _mem; + } + } + + void Clear() { + _size = 0; + } + + void Push( T t ) { + TIXMLASSERT( _size < INT_MAX ); + EnsureCapacity( _size+1 ); + _mem[_size] = t; + ++_size; + } + + T* PushArr( int count ) { + TIXMLASSERT( count >= 0 ); + TIXMLASSERT( _size <= INT_MAX - count ); + EnsureCapacity( _size+count ); + T* ret = &_mem[_size]; + _size += count; + return ret; + } + + T Pop() { + TIXMLASSERT( _size > 0 ); + --_size; + return _mem[_size]; + } + + void PopArr( int count ) { + TIXMLASSERT( _size >= count ); + _size -= count; + } + + bool Empty() const { + return _size == 0; + } + + T& operator[](int i) { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& operator[](int i) const { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& PeekTop() const { + TIXMLASSERT( _size > 0 ); + return _mem[ _size - 1]; + } + + int Size() const { + TIXMLASSERT( _size >= 0 ); + return _size; + } + + int Capacity() const { + TIXMLASSERT( _allocated >= INITIAL_SIZE ); + return _allocated; + } + + void SwapRemove(int i) { + TIXMLASSERT(i >= 0 && i < _size); + TIXMLASSERT(_size > 0); + _mem[i] = _mem[_size - 1]; + --_size; + } + + const T* Mem() const { + TIXMLASSERT( _mem ); + return _mem; + } + + T* Mem() { + TIXMLASSERT( _mem ); + return _mem; + } + +private: + DynArray( const DynArray& ); // not supported + void operator=( const DynArray& ); // not supported + + void EnsureCapacity( int cap ) { + TIXMLASSERT( cap > 0 ); + if ( cap > _allocated ) { + TIXMLASSERT( cap <= INT_MAX / 2 ); + const int newAllocated = cap * 2; + T* newMem = new T[newAllocated]; + TIXMLASSERT( newAllocated >= _size ); + memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs + if ( _mem != _pool ) { + delete [] _mem; + } + _mem = newMem; + _allocated = newAllocated; + } + } + + T* _mem; + T _pool[INITIAL_SIZE]; + int _allocated; // objects allocated + int _size; // number objects in use +}; + + +/* + Parent virtual class of a pool for fast allocation + and deallocation of objects. +*/ +class MemPool +{ +public: + MemPool() {} + virtual ~MemPool() {} + + virtual int ItemSize() const = 0; + virtual void* Alloc() = 0; + virtual void Free( void* ) = 0; + virtual void SetTracked() = 0; +}; + + +/* + Template child class to create pools of the correct type. +*/ +template< int ITEM_SIZE > +class MemPoolT : public MemPool +{ +public: + MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} + ~MemPoolT() { + MemPoolT< ITEM_SIZE >::Clear(); + } + + void Clear() { + // Delete the blocks. + while( !_blockPtrs.Empty()) { + Block* lastBlock = _blockPtrs.Pop(); + delete lastBlock; + } + _root = 0; + _currentAllocs = 0; + _nAllocs = 0; + _maxAllocs = 0; + _nUntracked = 0; + } + + virtual int ItemSize() const { + return ITEM_SIZE; + } + int CurrentAllocs() const { + return _currentAllocs; + } + + virtual void* Alloc() { + if ( !_root ) { + // Need a new block. + Block* block = new Block(); + _blockPtrs.Push( block ); + + Item* blockItems = block->items; + for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { + blockItems[i].next = &(blockItems[i + 1]); + } + blockItems[ITEMS_PER_BLOCK - 1].next = 0; + _root = blockItems; + } + Item* const result = _root; + TIXMLASSERT( result != 0 ); + _root = _root->next; + + ++_currentAllocs; + if ( _currentAllocs > _maxAllocs ) { + _maxAllocs = _currentAllocs; + } + ++_nAllocs; + ++_nUntracked; + return result; + } + + virtual void Free( void* mem ) { + if ( !mem ) { + return; + } + --_currentAllocs; + Item* item = static_cast( mem ); +#ifdef TINYXML2_DEBUG + memset( item, 0xfe, sizeof( *item ) ); +#endif + item->next = _root; + _root = item; + } + void Trace( const char* name ) { + printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", + name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, + ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); + } + + void SetTracked() { + --_nUntracked; + } + + int Untracked() const { + return _nUntracked; + } + + // This number is perf sensitive. 4k seems like a good tradeoff on my machine. + // The test file is large, 170k. + // Release: VS2010 gcc(no opt) + // 1k: 4000 + // 2k: 4000 + // 4k: 3900 21000 + // 16k: 5200 + // 32k: 4300 + // 64k: 4000 21000 + // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK + // in private part if ITEMS_PER_BLOCK is private + enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; + +private: + MemPoolT( const MemPoolT& ); // not supported + void operator=( const MemPoolT& ); // not supported + + union Item { + Item* next; + char itemData[ITEM_SIZE]; + }; + struct Block { + Item items[ITEMS_PER_BLOCK]; + }; + DynArray< Block*, 10 > _blockPtrs; + Item* _root; + + int _currentAllocs; + int _nAllocs; + int _maxAllocs; + int _nUntracked; +}; + + + +/** + Implements the interface to the "Visitor pattern" (see the Accept() method.) + If you call the Accept() method, it requires being passed a XMLVisitor + class to handle callbacks. For nodes that contain other nodes (Document, Element) + you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs + are simply called with Visit(). + + If you return 'true' from a Visit method, recursive parsing will continue. If you return + false, no children of this node or its siblings will be visited. + + All flavors of Visit methods have a default implementation that returns 'true' (continue + visiting). You need to only override methods that are interesting to you. + + Generally Accept() is called on the XMLDocument, although all nodes support visiting. + + You should never change the document from a callback. + + @sa XMLNode::Accept() +*/ +class TINYXML2_LIB XMLVisitor +{ +public: + virtual ~XMLVisitor() {} + + /// Visit a document. + virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { + return true; + } + /// Visit a document. + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + /// Visit an element. + virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { + return true; + } + /// Visit an element. + virtual bool VisitExit( const XMLElement& /*element*/ ) { + return true; + } + + /// Visit a declaration. + virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { + return true; + } + /// Visit a text node. + virtual bool Visit( const XMLText& /*text*/ ) { + return true; + } + /// Visit a comment node. + virtual bool Visit( const XMLComment& /*comment*/ ) { + return true; + } + /// Visit an unknown node. + virtual bool Visit( const XMLUnknown& /*unknown*/ ) { + return true; + } +}; + +// WARNING: must match XMLDocument::_errorNames[] +enum XMLError { + XML_SUCCESS = 0, + XML_NO_ATTRIBUTE, + XML_WRONG_ATTRIBUTE_TYPE, + XML_ERROR_FILE_NOT_FOUND, + XML_ERROR_FILE_COULD_NOT_BE_OPENED, + XML_ERROR_FILE_READ_ERROR, + XML_ERROR_PARSING_ELEMENT, + XML_ERROR_PARSING_ATTRIBUTE, + XML_ERROR_PARSING_TEXT, + XML_ERROR_PARSING_CDATA, + XML_ERROR_PARSING_COMMENT, + XML_ERROR_PARSING_DECLARATION, + XML_ERROR_PARSING_UNKNOWN, + XML_ERROR_EMPTY_DOCUMENT, + XML_ERROR_MISMATCHED_ELEMENT, + XML_ERROR_PARSING, + XML_CAN_NOT_CONVERT_TEXT, + XML_NO_TEXT_NODE, + XML_ELEMENT_DEPTH_EXCEEDED, + + XML_ERROR_COUNT +}; + + +/* + Utility functionality. +*/ +class TINYXML2_LIB XMLUtil +{ +public: + static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { + TIXMLASSERT( p ); + + while( IsWhiteSpace(*p) ) { + if (curLineNumPtr && *p == '\n') { + ++(*curLineNumPtr); + } + ++p; + } + TIXMLASSERT( p ); + return p; + } + static char* SkipWhiteSpace( char* const p, int* curLineNumPtr ) { + return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); + } + + // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't + // correct, but simple, and usually works. + static bool IsWhiteSpace( char p ) { + return !IsUTF8Continuation(p) && isspace( static_cast(p) ); + } + + inline static bool IsNameStartChar( unsigned char ch ) { + if ( ch >= 128 ) { + // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() + return true; + } + if ( isalpha( ch ) ) { + return true; + } + return ch == ':' || ch == '_'; + } + + inline static bool IsNameChar( unsigned char ch ) { + return IsNameStartChar( ch ) + || isdigit( ch ) + || ch == '.' + || ch == '-'; + } + + inline static bool IsPrefixHex( const char* p) { + p = SkipWhiteSpace(p, 0); + return p && *p == '0' && ( *(p + 1) == 'x' || *(p + 1) == 'X'); + } + + inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { + if ( p == q ) { + return true; + } + TIXMLASSERT( p ); + TIXMLASSERT( q ); + TIXMLASSERT( nChar >= 0 ); + return strncmp( p, q, nChar ) == 0; + } + + inline static bool IsUTF8Continuation( const char p ) { + return ( p & 0x80 ) != 0; + } + + static const char* ReadBOM( const char* p, bool* hasBOM ); + // p is the starting location, + // the UTF-8 value of the entity will be placed in value, and length filled in. + static const char* GetCharacterRef( const char* p, char* value, int* length ); + static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); + + // converts primitive types to strings + static void ToStr( int v, char* buffer, int bufferSize ); + static void ToStr( unsigned v, char* buffer, int bufferSize ); + static void ToStr( bool v, char* buffer, int bufferSize ); + static void ToStr( float v, char* buffer, int bufferSize ); + static void ToStr( double v, char* buffer, int bufferSize ); + static void ToStr(int64_t v, char* buffer, int bufferSize); + static void ToStr(uint64_t v, char* buffer, int bufferSize); + + // converts strings to primitive types + static bool ToInt( const char* str, int* value ); + static bool ToUnsigned( const char* str, unsigned* value ); + static bool ToBool( const char* str, bool* value ); + static bool ToFloat( const char* str, float* value ); + static bool ToDouble( const char* str, double* value ); + static bool ToInt64(const char* str, int64_t* value); + static bool ToUnsigned64(const char* str, uint64_t* value); + // Changes what is serialized for a boolean value. + // Default to "true" and "false". Shouldn't be changed + // unless you have a special testing or compatibility need. + // Be careful: static, global, & not thread safe. + // Be sure to set static const memory as parameters. + static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); + +private: + static const char* writeBoolTrue; + static const char* writeBoolFalse; +}; + + +/** XMLNode is a base class for every object that is in the + XML Document Object Model (DOM), except XMLAttributes. + Nodes have siblings, a parent, and children which can + be navigated. A node is always in a XMLDocument. + The type of a XMLNode can be queried, and it can + be cast to its more defined type. + + A XMLDocument allocates memory for all its Nodes. + When the XMLDocument gets deleted, all its Nodes + will also be deleted. + + @verbatim + A Document can contain: Element (container or leaf) + Comment (leaf) + Unknown (leaf) + Declaration( leaf ) + + An Element can contain: Element (container or leaf) + Text (leaf) + Attributes (not on tree) + Comment (leaf) + Unknown (leaf) + + @endverbatim +*/ +class TINYXML2_LIB XMLNode +{ + friend class XMLDocument; + friend class XMLElement; +public: + + /// Get the XMLDocument that owns this XMLNode. + const XMLDocument* GetDocument() const { + TIXMLASSERT( _document ); + return _document; + } + /// Get the XMLDocument that owns this XMLNode. + XMLDocument* GetDocument() { + TIXMLASSERT( _document ); + return _document; + } + + /// Safely cast to an Element, or null. + virtual XMLElement* ToElement() { + return 0; + } + /// Safely cast to Text, or null. + virtual XMLText* ToText() { + return 0; + } + /// Safely cast to a Comment, or null. + virtual XMLComment* ToComment() { + return 0; + } + /// Safely cast to a Document, or null. + virtual XMLDocument* ToDocument() { + return 0; + } + /// Safely cast to a Declaration, or null. + virtual XMLDeclaration* ToDeclaration() { + return 0; + } + /// Safely cast to an Unknown, or null. + virtual XMLUnknown* ToUnknown() { + return 0; + } + + virtual const XMLElement* ToElement() const { + return 0; + } + virtual const XMLText* ToText() const { + return 0; + } + virtual const XMLComment* ToComment() const { + return 0; + } + virtual const XMLDocument* ToDocument() const { + return 0; + } + virtual const XMLDeclaration* ToDeclaration() const { + return 0; + } + virtual const XMLUnknown* ToUnknown() const { + return 0; + } + + /** The meaning of 'value' changes for the specific type. + @verbatim + Document: empty (NULL is returned, not an empty string) + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + */ + const char* Value() const; + + /** Set the Value of an XML node. + @sa Value() + */ + void SetValue( const char* val, bool staticMem=false ); + + /// Gets the line number the node is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } + + /// Get the parent of this node on the DOM. + const XMLNode* Parent() const { + return _parent; + } + + XMLNode* Parent() { + return _parent; + } + + /// Returns true if this node has no children. + bool NoChildren() const { + return !_firstChild; + } + + /// Get the first child node, or null if none exists. + const XMLNode* FirstChild() const { + return _firstChild; + } + + XMLNode* FirstChild() { + return _firstChild; + } + + /** Get the first child element, or optionally the first child + element with the specified name. + */ + const XMLElement* FirstChildElement( const char* name = 0 ) const; + + XMLElement* FirstChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->FirstChildElement( name )); + } + + /// Get the last child node, or null if none exists. + const XMLNode* LastChild() const { + return _lastChild; + } + + XMLNode* LastChild() { + return _lastChild; + } + + /** Get the last child element or optionally the last child + element with the specified name. + */ + const XMLElement* LastChildElement( const char* name = 0 ) const; + + XMLElement* LastChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->LastChildElement(name) ); + } + + /// Get the previous (left) sibling node of this node. + const XMLNode* PreviousSibling() const { + return _prev; + } + + XMLNode* PreviousSibling() { + return _prev; + } + + /// Get the previous (left) sibling element of this node, with an optionally supplied name. + const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; + + XMLElement* PreviousSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); + } + + /// Get the next (right) sibling node of this node. + const XMLNode* NextSibling() const { + return _next; + } + + XMLNode* NextSibling() { + return _next; + } + + /// Get the next (right) sibling element of this node, with an optionally supplied name. + const XMLElement* NextSiblingElement( const char* name = 0 ) const; + + XMLElement* NextSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->NextSiblingElement( name ) ); + } + + /** + Add a child node as the last (right) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertEndChild( XMLNode* addThis ); + + XMLNode* LinkEndChild( XMLNode* addThis ) { + return InsertEndChild( addThis ); + } + /** + Add a child node as the first (left) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertFirstChild( XMLNode* addThis ); + /** + Add a node after the specified child node. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the afterThis node + is not a child of this node, or if the node does not + belong to the same document. + */ + XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); + + /** + Delete all the children of this node. + */ + void DeleteChildren(); + + /** + Delete a child of this node. + */ + void DeleteChild( XMLNode* node ); + + /** + Make a copy of this node, but not its children. + You may pass in a Document pointer that will be + the owner of the new Node. If the 'document' is + null, then the node returned will be allocated + from the current Document. (this->GetDocument()) + + Note: if called on a XMLDocument, this will return null. + */ + virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; + + /** + Make a copy of this node and all its children. + + If the 'target' is null, then the nodes will + be allocated in the current document. If 'target' + is specified, the memory will be allocated is the + specified XMLDocument. + + NOTE: This is probably not the correct tool to + copy a document, since XMLDocuments can have multiple + top level XMLNodes. You probably want to use + XMLDocument::DeepCopy() + */ + XMLNode* DeepClone( XMLDocument* target ) const; + + /** + Test if 2 nodes are the same, but don't test children. + The 2 nodes do not need to be in the same Document. + + Note: if called on a XMLDocument, this will return false. + */ + virtual bool ShallowEqual( const XMLNode* compare ) const = 0; + + /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the XMLVisitor interface. + + This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this + interface versus any other.) + + The interface has been based on ideas from: + + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + + Which are both good references for "visiting". + + An example of using Accept(): + @verbatim + XMLPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept( XMLVisitor* visitor ) const = 0; + + /** + Set user data into the XMLNode. TinyXML-2 in + no way processes or interprets user data. + It is initially 0. + */ + void SetUserData(void* userData) { _userData = userData; } + + /** + Get user data set into the XMLNode. TinyXML-2 in + no way processes or interprets user data. + It is initially 0. + */ + void* GetUserData() const { return _userData; } + +protected: + explicit XMLNode( XMLDocument* ); + virtual ~XMLNode(); + + virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); + + XMLDocument* _document; + XMLNode* _parent; + mutable StrPair _value; + int _parseLineNum; + + XMLNode* _firstChild; + XMLNode* _lastChild; + + XMLNode* _prev; + XMLNode* _next; + + void* _userData; + +private: + MemPool* _memPool; + void Unlink( XMLNode* child ); + static void DeleteNode( XMLNode* node ); + void InsertChildPreamble( XMLNode* insertThis ) const; + const XMLElement* ToElementWithName( const char* name ) const; + + XMLNode( const XMLNode& ); // not supported + XMLNode& operator=( const XMLNode& ); // not supported +}; + + +/** XML text. + + Note that a text node can have child element nodes, for example: + @verbatim + This is bold + @endverbatim + + A text node can have 2 ways to output the next. "normal" output + and CDATA. It will default to the mode it was parsed from the XML file and + you generally want to leave it alone, but you can change the output mode with + SetCData() and query it with CData(). +*/ +class TINYXML2_LIB XMLText : public XMLNode +{ + friend class XMLDocument; +public: + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLText* ToText() { + return this; + } + virtual const XMLText* ToText() const { + return this; + } + + /// Declare whether this should be CDATA or standard text. + void SetCData( bool isCData ) { + _isCData = isCData; + } + /// Returns true if this is a CDATA text element. + bool CData() const { + return _isCData; + } + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} + virtual ~XMLText() {} + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + bool _isCData; + + XMLText( const XMLText& ); // not supported + XMLText& operator=( const XMLText& ); // not supported +}; + + +/** An XML Comment. */ +class TINYXML2_LIB XMLComment : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLComment* ToComment() { + return this; + } + virtual const XMLComment* ToComment() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLComment( XMLDocument* doc ); + virtual ~XMLComment(); + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); + +private: + XMLComment( const XMLComment& ); // not supported + XMLComment& operator=( const XMLComment& ); // not supported +}; + + +/** In correct XML the declaration is the first entry in the file. + @verbatim + + @endverbatim + + TinyXML-2 will happily read or write files without a declaration, + however. + + The text of the declaration isn't interpreted. It is parsed + and written as a string. +*/ +class TINYXML2_LIB XMLDeclaration : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLDeclaration* ToDeclaration() { + return this; + } + virtual const XMLDeclaration* ToDeclaration() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLDeclaration( XMLDocument* doc ); + virtual ~XMLDeclaration(); + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + XMLDeclaration( const XMLDeclaration& ); // not supported + XMLDeclaration& operator=( const XMLDeclaration& ); // not supported +}; + + +/** Any tag that TinyXML-2 doesn't recognize is saved as an + unknown. It is a tag of text, but should not be modified. + It will be written back to the XML, unchanged, when the file + is saved. + + DTD tags get thrown into XMLUnknowns. +*/ +class TINYXML2_LIB XMLUnknown : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLUnknown* ToUnknown() { + return this; + } + virtual const XMLUnknown* ToUnknown() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLUnknown( XMLDocument* doc ); + virtual ~XMLUnknown(); + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + XMLUnknown( const XMLUnknown& ); // not supported + XMLUnknown& operator=( const XMLUnknown& ); // not supported +}; + + + +/** An attribute is a name-value pair. Elements have an arbitrary + number of attributes, each with a unique name. + + @note The attributes are not XMLNodes. You may only query the + Next() attribute in a list. +*/ +class TINYXML2_LIB XMLAttribute +{ + friend class XMLElement; +public: + /// The name of the attribute. + const char* Name() const; + + /// The value of the attribute. + const char* Value() const; + + /// Gets the line number the attribute is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } + + /// The next attribute in the list. + const XMLAttribute* Next() const { + return _next; + } + + /** IntValue interprets the attribute as an integer, and returns the value. + If the value isn't an integer, 0 will be returned. There is no error checking; + use QueryIntValue() if you need error checking. + */ + int IntValue() const { + int i = 0; + QueryIntValue(&i); + return i; + } + + int64_t Int64Value() const { + int64_t i = 0; + QueryInt64Value(&i); + return i; + } + + uint64_t Unsigned64Value() const { + uint64_t i = 0; + QueryUnsigned64Value(&i); + return i; + } + + /// Query as an unsigned integer. See IntValue() + unsigned UnsignedValue() const { + unsigned i=0; + QueryUnsignedValue( &i ); + return i; + } + /// Query as a boolean. See IntValue() + bool BoolValue() const { + bool b=false; + QueryBoolValue( &b ); + return b; + } + /// Query as a double. See IntValue() + double DoubleValue() const { + double d=0; + QueryDoubleValue( &d ); + return d; + } + /// Query as a float. See IntValue() + float FloatValue() const { + float f=0; + QueryFloatValue( &f ); + return f; + } + + /** QueryIntValue interprets the attribute as an integer, and returns the value + in the provided parameter. The function will return XML_SUCCESS on success, + and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. + */ + XMLError QueryIntValue( int* value ) const; + /// See QueryIntValue + XMLError QueryUnsignedValue( unsigned int* value ) const; + /// See QueryIntValue + XMLError QueryInt64Value(int64_t* value) const; + /// See QueryIntValue + XMLError QueryUnsigned64Value(uint64_t* value) const; + /// See QueryIntValue + XMLError QueryBoolValue( bool* value ) const; + /// See QueryIntValue + XMLError QueryDoubleValue( double* value ) const; + /// See QueryIntValue + XMLError QueryFloatValue( float* value ) const; + + /// Set the attribute to a string value. + void SetAttribute( const char* value ); + /// Set the attribute to value. + void SetAttribute( int value ); + /// Set the attribute to value. + void SetAttribute( unsigned value ); + /// Set the attribute to value. + void SetAttribute(int64_t value); + /// Set the attribute to value. + void SetAttribute(uint64_t value); + /// Set the attribute to value. + void SetAttribute( bool value ); + /// Set the attribute to value. + void SetAttribute( double value ); + /// Set the attribute to value. + void SetAttribute( float value ); + +private: + enum { BUF_SIZE = 200 }; + + XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} + virtual ~XMLAttribute() {} + + XMLAttribute( const XMLAttribute& ); // not supported + void operator=( const XMLAttribute& ); // not supported + void SetName( const char* name ); + + char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); + + mutable StrPair _name; + mutable StrPair _value; + int _parseLineNum; + XMLAttribute* _next; + MemPool* _memPool; +}; + + +/** The element is a container class. It has a value, the element name, + and can contain other elements, text, comments, and unknowns. + Elements also contain an arbitrary number of attributes. +*/ +class TINYXML2_LIB XMLElement : public XMLNode +{ + friend class XMLDocument; +public: + /// Get the name of an element (which is the Value() of the node.) + const char* Name() const { + return Value(); + } + /// Set the name of the element. + void SetName( const char* str, bool staticMem=false ) { + SetValue( str, staticMem ); + } + + virtual XMLElement* ToElement() { + return this; + } + virtual const XMLElement* ToElement() const { + return this; + } + virtual bool Accept( XMLVisitor* visitor ) const; + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none + exists. For example: + + @verbatim + const char* value = ele->Attribute( "foo" ); + @endverbatim + + The 'value' parameter is normally null. However, if specified, + the attribute will only be returned if the 'name' and 'value' + match. This allow you to write code: + + @verbatim + if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); + @endverbatim + + rather than: + @verbatim + if ( ele->Attribute( "foo" ) ) { + if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); + } + @endverbatim + */ + const char* Attribute( const char* name, const char* value=0 ) const; + + /** Given an attribute name, IntAttribute() returns the value + of the attribute interpreted as an integer. The default + value will be returned if the attribute isn't present, + or if there is an error. (For a method with error + checking, see QueryIntAttribute()). + */ + int IntAttribute(const char* name, int defaultValue = 0) const; + /// See IntAttribute() + unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; + /// See IntAttribute() + int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; + /// See IntAttribute() + uint64_t Unsigned64Attribute(const char* name, uint64_t defaultValue = 0) const; + /// See IntAttribute() + bool BoolAttribute(const char* name, bool defaultValue = false) const; + /// See IntAttribute() + double DoubleAttribute(const char* name, double defaultValue = 0) const; + /// See IntAttribute() + float FloatAttribute(const char* name, float defaultValue = 0) const; + + /** Given an attribute name, QueryIntAttribute() returns + XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryIntAttribute( const char* name, int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryIntValue( value ); + } + + /// See QueryIntAttribute() + XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsignedValue( value ); + } + + /// See QueryIntAttribute() + XMLError QueryInt64Attribute(const char* name, int64_t* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryInt64Value(value); + } + + /// See QueryIntAttribute() + XMLError QueryUnsigned64Attribute(const char* name, uint64_t* value) const { + const XMLAttribute* a = FindAttribute(name); + if(!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsigned64Value(value); + } + + /// See QueryIntAttribute() + XMLError QueryBoolAttribute( const char* name, bool* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryBoolValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryDoubleAttribute( const char* name, double* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryDoubleValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryFloatAttribute( const char* name, float* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryFloatValue( value ); + } + + /// See QueryIntAttribute() + XMLError QueryStringAttribute(const char* name, const char** value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + *value = a->Value(); + return XML_SUCCESS; + } + + + + /** Given an attribute name, QueryAttribute() returns + XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. It is overloaded for the primitive types, + and is a generally more convenient replacement of + QueryIntAttribute() and related functions. + + If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryAttribute( const char* name, int* value ) const { + return QueryIntAttribute( name, value ); + } + + XMLError QueryAttribute( const char* name, unsigned int* value ) const { + return QueryUnsignedAttribute( name, value ); + } + + XMLError QueryAttribute(const char* name, int64_t* value) const { + return QueryInt64Attribute(name, value); + } + + XMLError QueryAttribute(const char* name, uint64_t* value) const { + return QueryUnsigned64Attribute(name, value); + } + + XMLError QueryAttribute( const char* name, bool* value ) const { + return QueryBoolAttribute( name, value ); + } + + XMLError QueryAttribute( const char* name, double* value ) const { + return QueryDoubleAttribute( name, value ); + } + + XMLError QueryAttribute( const char* name, float* value ) const { + return QueryFloatAttribute( name, value ); + } + + XMLError QueryAttribute(const char* name, const char** value) const { + return QueryStringAttribute(name, value); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, const char* value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, int value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, unsigned value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, int64_t value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, uint64_t value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, bool value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, double value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, float value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /** + Delete an attribute. + */ + void DeleteAttribute( const char* name ); + + /// Return the first attribute in the list. + const XMLAttribute* FirstAttribute() const { + return _rootAttribute; + } + /// Query a specific attribute in the list. + const XMLAttribute* FindAttribute( const char* name ) const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the XMLText child + and accessing it directly. + + If the first child of 'this' is a XMLText, the GetText() + returns the character string of the Text node, else null is returned. + + This is a convenient method for getting the text of simple contained text: + @verbatim + This is text + const char* str = fooElement->GetText(); + @endverbatim + + 'str' will be a pointer to "This is text". + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + This is text + @endverbatim + GetText() will return "This is ". + */ + const char* GetText() const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, SetText() is limited compared to creating an XMLText child + and mutating it directly. + + If the first child of 'this' is a XMLText, SetText() sets its value to + the given string, otherwise it will create a first child that is an XMLText. + + This is a convenient method for setting the text of simple contained text: + @verbatim + This is text + fooElement->SetText( "Hullaballoo!" ); + Hullaballoo! + @endverbatim + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then it will not change "This is text", but rather prefix it with a text element: + @verbatim + Hullaballoo!This is text + @endverbatim + + For this XML: + @verbatim + + @endverbatim + SetText() will generate + @verbatim + Hullaballoo! + @endverbatim + */ + void SetText( const char* inText ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( int value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( unsigned value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(int64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(uint64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( bool value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( double value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( float value ); + + /** + Convenience method to query the value of a child text node. This is probably best + shown by example. Given you have a document is this form: + @verbatim + + 1 + 1.4 + + @endverbatim + + The QueryIntText() and similar functions provide a safe and easier way to get to the + "value" of x and y. + + @verbatim + int x = 0; + float y = 0; // types of x and y are contrived for example + const XMLElement* xElement = pointElement->FirstChildElement( "x" ); + const XMLElement* yElement = pointElement->FirstChildElement( "y" ); + xElement->QueryIntText( &x ); + yElement->QueryFloatText( &y ); + @endverbatim + + @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted + to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. + + */ + XMLError QueryIntText( int* ival ) const; + /// See QueryIntText() + XMLError QueryUnsignedText( unsigned* uval ) const; + /// See QueryIntText() + XMLError QueryInt64Text(int64_t* uval) const; + /// See QueryIntText() + XMLError QueryUnsigned64Text(uint64_t* uval) const; + /// See QueryIntText() + XMLError QueryBoolText( bool* bval ) const; + /// See QueryIntText() + XMLError QueryDoubleText( double* dval ) const; + /// See QueryIntText() + XMLError QueryFloatText( float* fval ) const; + + int IntText(int defaultValue = 0) const; + + /// See QueryIntText() + unsigned UnsignedText(unsigned defaultValue = 0) const; + /// See QueryIntText() + int64_t Int64Text(int64_t defaultValue = 0) const; + /// See QueryIntText() + uint64_t Unsigned64Text(uint64_t defaultValue = 0) const; + /// See QueryIntText() + bool BoolText(bool defaultValue = false) const; + /// See QueryIntText() + double DoubleText(double defaultValue = 0) const; + /// See QueryIntText() + float FloatText(float defaultValue = 0) const; + + /** + Convenience method to create a new XMLElement and add it as last (right) + child of this node. Returns the created and inserted element. + */ + XMLElement* InsertNewChildElement(const char* name); + /// See InsertNewChildElement() + XMLComment* InsertNewComment(const char* comment); + /// See InsertNewChildElement() + XMLText* InsertNewText(const char* text); + /// See InsertNewChildElement() + XMLDeclaration* InsertNewDeclaration(const char* text); + /// See InsertNewChildElement() + XMLUnknown* InsertNewUnknown(const char* text); + + + // internal: + enum ElementClosingType { + OPEN, // + CLOSED, // + CLOSING // + }; + ElementClosingType ClosingType() const { + return _closingType; + } + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + XMLElement( XMLDocument* doc ); + virtual ~XMLElement(); + XMLElement( const XMLElement& ); // not supported + void operator=( const XMLElement& ); // not supported + + XMLAttribute* FindOrCreateAttribute( const char* name ); + char* ParseAttributes( char* p, int* curLineNumPtr ); + static void DeleteAttribute( XMLAttribute* attribute ); + XMLAttribute* CreateAttribute(); + + enum { BUF_SIZE = 200 }; + ElementClosingType _closingType; + // The attribute list is ordered; there is no 'lastAttribute' + // because the list needs to be scanned for dupes before adding + // a new attribute. + XMLAttribute* _rootAttribute; +}; + + +enum Whitespace { + PRESERVE_WHITESPACE, + COLLAPSE_WHITESPACE +}; + + +/** A Document binds together all the functionality. + It can be saved, loaded, and printed to the screen. + All Nodes are connected and allocated to a Document. + If the Document is deleted, all its Nodes are also deleted. +*/ +class TINYXML2_LIB XMLDocument : public XMLNode +{ + friend class XMLElement; + // Gives access to SetError and Push/PopDepth, but over-access for everything else. + // Wishing C++ had "internal" scope. + friend class XMLNode; + friend class XMLText; + friend class XMLComment; + friend class XMLDeclaration; + friend class XMLUnknown; +public: + /// constructor + XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE ); + ~XMLDocument(); + + virtual XMLDocument* ToDocument() { + TIXMLASSERT( this == _document ); + return this; + } + virtual const XMLDocument* ToDocument() const { + TIXMLASSERT( this == _document ); + return this; + } + + /** + Parse an XML file from a character string. + Returns XML_SUCCESS (0) on success, or + an errorID. + + You may optionally pass in the 'nBytes', which is + the number of bytes which will be parsed. If not + specified, TinyXML-2 will assume 'xml' points to a + null terminated string. + */ + XMLError Parse( const char* xml, size_t nBytes=static_cast(-1) ); + + /** + Load an XML file from disk. + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError LoadFile( const char* filename ); + + /** + Load an XML file from disk. You are responsible + for providing and closing the FILE*. + + NOTE: The file should be opened as binary ("rb") + not text in order for TinyXML-2 to correctly + do newline normalization. + + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError LoadFile( FILE* ); + + /** + Save the XML file to disk. + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError SaveFile( const char* filename, bool compact = false ); + + /** + Save the XML file to disk. You are responsible + for providing and closing the FILE*. + + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError SaveFile( FILE* fp, bool compact = false ); + + bool ProcessEntities() const { + return _processEntities; + } + Whitespace WhitespaceMode() const { + return _whitespaceMode; + } + + /** + Returns true if this document has a leading Byte Order Mark of UTF8. + */ + bool HasBOM() const { + return _writeBOM; + } + /** Sets whether to write the BOM when writing the file. + */ + void SetBOM( bool useBOM ) { + _writeBOM = useBOM; + } + + /** Return the root element of DOM. Equivalent to FirstChildElement(). + To get the first node, use FirstChild(). + */ + XMLElement* RootElement() { + return FirstChildElement(); + } + const XMLElement* RootElement() const { + return FirstChildElement(); + } + + /** Print the Document. If the Printer is not provided, it will + print to stdout. If you provide Printer, this can print to a file: + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Or you can use a printer to print to memory: + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + // printer.CStr() has a const char* to the XML + @endverbatim + */ + void Print( XMLPrinter* streamer=0 ) const; + virtual bool Accept( XMLVisitor* visitor ) const; + + /** + Create a new Element associated with + this Document. The memory for the Element + is managed by the Document. + */ + XMLElement* NewElement( const char* name ); + /** + Create a new Comment associated with + this Document. The memory for the Comment + is managed by the Document. + */ + XMLComment* NewComment( const char* comment ); + /** + Create a new Text associated with + this Document. The memory for the Text + is managed by the Document. + */ + XMLText* NewText( const char* text ); + /** + Create a new Declaration associated with + this Document. The memory for the object + is managed by the Document. + + If the 'text' param is null, the standard + declaration is used.: + @verbatim + + @endverbatim + */ + XMLDeclaration* NewDeclaration( const char* text=0 ); + /** + Create a new Unknown associated with + this Document. The memory for the object + is managed by the Document. + */ + XMLUnknown* NewUnknown( const char* text ); + + /** + Delete a node associated with this document. + It will be unlinked from the DOM. + */ + void DeleteNode( XMLNode* node ); + + /// Clears the error flags. + void ClearError(); + + /// Return true if there was an error parsing the document. + bool Error() const { + return _errorID != XML_SUCCESS; + } + /// Return the errorID. + XMLError ErrorID() const { + return _errorID; + } + const char* ErrorName() const; + static const char* ErrorIDToName(XMLError errorID); + + /** Returns a "long form" error description. A hopefully helpful + diagnostic with location, line number, and/or additional info. + */ + const char* ErrorStr() const; + + /// A (trivial) utility function that prints the ErrorStr() to stdout. + void PrintError() const; + + /// Return the line where the error occurred, or zero if unknown. + int ErrorLineNum() const + { + return _errorLineNum; + } + + /// Clear the document, resetting it to the initial state. + void Clear(); + + /** + Copies this document to a target document. + The target will be completely cleared before the copy. + If you want to copy a sub-tree, see XMLNode::DeepClone(). + + NOTE: that the 'target' must be non-null. + */ + void DeepCopy(XMLDocument* target) const; + + // internal + char* Identify( char* p, XMLNode** node ); + + // internal + void MarkInUse(const XMLNode* const); + + virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { + return 0; + } + virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { + return false; + } + +private: + XMLDocument( const XMLDocument& ); // not supported + void operator=( const XMLDocument& ); // not supported + + bool _writeBOM; + bool _processEntities; + XMLError _errorID; + Whitespace _whitespaceMode; + mutable StrPair _errorStr; + int _errorLineNum; + char* _charBuffer; + int _parseCurLineNum; + int _parsingDepth; + // Memory tracking does add some overhead. + // However, the code assumes that you don't + // have a bunch of unlinked nodes around. + // Therefore it takes less memory to track + // in the document vs. a linked list in the XMLNode, + // and the performance is the same. + DynArray _unlinked; + + MemPoolT< sizeof(XMLElement) > _elementPool; + MemPoolT< sizeof(XMLAttribute) > _attributePool; + MemPoolT< sizeof(XMLText) > _textPool; + MemPoolT< sizeof(XMLComment) > _commentPool; + + static const char* _errorNames[XML_ERROR_COUNT]; + + void Parse(); + + void SetError( XMLError error, int lineNum, const char* format, ... ); + + // Something of an obvious security hole, once it was discovered. + // Either an ill-formed XML or an excessively deep one can overflow + // the stack. Track stack depth, and error out if needed. + class DepthTracker { + public: + explicit DepthTracker(XMLDocument * document) { + this->_document = document; + document->PushDepth(); + } + ~DepthTracker() { + _document->PopDepth(); + } + private: + XMLDocument * _document; + }; + void PushDepth(); + void PopDepth(); + + template + NodeType* CreateUnlinkedNode( MemPoolT& pool ); +}; + +template +inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& pool ) +{ + TIXMLASSERT( sizeof( NodeType ) == PoolElementSize ); + TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() ); + NodeType* returnNode = new (pool.Alloc()) NodeType( this ); + TIXMLASSERT( returnNode ); + returnNode->_memPool = &pool; + + _unlinked.Push(returnNode); + return returnNode; +} + +/** + A XMLHandle is a class that wraps a node pointer with null checks; this is + an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 + DOM structure. It is a separate utility class. + + Take an example: + @verbatim + + + + + + + @endverbatim + + Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very + easy to write a *lot* of code that looks like: + + @verbatim + XMLElement* root = document.FirstChildElement( "Document" ); + if ( root ) + { + XMLElement* element = root->FirstChildElement( "Element" ); + if ( element ) + { + XMLElement* child = element->FirstChildElement( "Child" ); + if ( child ) + { + XMLElement* child2 = child->NextSiblingElement( "Child" ); + if ( child2 ) + { + // Finally do something useful. + @endverbatim + + And that doesn't even cover "else" cases. XMLHandle addresses the verbosity + of such code. A XMLHandle checks for null pointers so it is perfectly safe + and correct to use: + + @verbatim + XMLHandle docHandle( &document ); + XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); + if ( child2 ) + { + // do something useful + @endverbatim + + Which is MUCH more concise and useful. + + It is also safe to copy handles - internally they are nothing more than node pointers. + @verbatim + XMLHandle handleCopy = handle; + @endverbatim + + See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. +*/ +class TINYXML2_LIB XMLHandle +{ +public: + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + explicit XMLHandle( XMLNode* node ) : _node( node ) { + } + /// Create a handle from a node. + explicit XMLHandle( XMLNode& node ) : _node( &node ) { + } + /// Copy constructor + XMLHandle( const XMLHandle& ref ) : _node( ref._node ) { + } + /// Assignment + XMLHandle& operator=( const XMLHandle& ref ) { + _node = ref._node; + return *this; + } + + /// Get the first child of this handle. + XMLHandle FirstChild() { + return XMLHandle( _node ? _node->FirstChild() : 0 ); + } + /// Get the first child element of this handle. + XMLHandle FirstChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + /// Get the last child of this handle. + XMLHandle LastChild() { + return XMLHandle( _node ? _node->LastChild() : 0 ); + } + /// Get the last child element of this handle. + XMLHandle LastChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + /// Get the previous sibling of this handle. + XMLHandle PreviousSibling() { + return XMLHandle( _node ? _node->PreviousSibling() : 0 ); + } + /// Get the previous sibling element of this handle. + XMLHandle PreviousSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + /// Get the next sibling of this handle. + XMLHandle NextSibling() { + return XMLHandle( _node ? _node->NextSibling() : 0 ); + } + /// Get the next sibling element of this handle. + XMLHandle NextSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + /// Safe cast to XMLNode. This can return null. + XMLNode* ToNode() { + return _node; + } + /// Safe cast to XMLElement. This can return null. + XMLElement* ToElement() { + return ( _node ? _node->ToElement() : 0 ); + } + /// Safe cast to XMLText. This can return null. + XMLText* ToText() { + return ( _node ? _node->ToText() : 0 ); + } + /// Safe cast to XMLUnknown. This can return null. + XMLUnknown* ToUnknown() { + return ( _node ? _node->ToUnknown() : 0 ); + } + /// Safe cast to XMLDeclaration. This can return null. + XMLDeclaration* ToDeclaration() { + return ( _node ? _node->ToDeclaration() : 0 ); + } + +private: + XMLNode* _node; +}; + + +/** + A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the + same in all regards, except for the 'const' qualifiers. See XMLHandle for API. +*/ +class TINYXML2_LIB XMLConstHandle +{ +public: + explicit XMLConstHandle( const XMLNode* node ) : _node( node ) { + } + explicit XMLConstHandle( const XMLNode& node ) : _node( &node ) { + } + XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) { + } + + XMLConstHandle& operator=( const XMLConstHandle& ref ) { + _node = ref._node; + return *this; + } + + const XMLConstHandle FirstChild() const { + return XMLConstHandle( _node ? _node->FirstChild() : 0 ); + } + const XMLConstHandle FirstChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + const XMLConstHandle LastChild() const { + return XMLConstHandle( _node ? _node->LastChild() : 0 ); + } + const XMLConstHandle LastChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + const XMLConstHandle PreviousSibling() const { + return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); + } + const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + const XMLConstHandle NextSibling() const { + return XMLConstHandle( _node ? _node->NextSibling() : 0 ); + } + const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + + const XMLNode* ToNode() const { + return _node; + } + const XMLElement* ToElement() const { + return ( _node ? _node->ToElement() : 0 ); + } + const XMLText* ToText() const { + return ( _node ? _node->ToText() : 0 ); + } + const XMLUnknown* ToUnknown() const { + return ( _node ? _node->ToUnknown() : 0 ); + } + const XMLDeclaration* ToDeclaration() const { + return ( _node ? _node->ToDeclaration() : 0 ); + } + +private: + const XMLNode* _node; +}; + + +/** + Printing functionality. The XMLPrinter gives you more + options than the XMLDocument::Print() method. + + It can: + -# Print to memory. + -# Print to a file you provide. + -# Print XML without a XMLDocument. + + Print to Memory + + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + SomeFunction( printer.CStr() ); + @endverbatim + + Print to a File + + You provide the file pointer. + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Print without a XMLDocument + + When loading, an XML parser is very useful. However, sometimes + when saving, it just gets in the way. The code is often set up + for streaming, and constructing the DOM is just overhead. + + The Printer supports the streaming case. The following code + prints out a trivially simple XML file without ever creating + an XML document. + + @verbatim + XMLPrinter printer( fp ); + printer.OpenElement( "foo" ); + printer.PushAttribute( "foo", "bar" ); + printer.CloseElement(); + @endverbatim +*/ +class TINYXML2_LIB XMLPrinter : public XMLVisitor +{ +public: + /** Construct the printer. If the FILE* is specified, + this will print to the FILE. Else it will print + to memory, and the result is available in CStr(). + If 'compact' is set to true, then output is created + with only required whitespace and newlines. + */ + XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); + virtual ~XMLPrinter() {} + + /** If streaming, write the BOM and declaration. */ + void PushHeader( bool writeBOM, bool writeDeclaration ); + /** If streaming, start writing an element. + The element must be closed with CloseElement() + */ + void OpenElement( const char* name, bool compactMode=false ); + /// If streaming, add an attribute to an open element. + void PushAttribute( const char* name, const char* value ); + void PushAttribute( const char* name, int value ); + void PushAttribute( const char* name, unsigned value ); + void PushAttribute( const char* name, int64_t value ); + void PushAttribute( const char* name, uint64_t value ); + void PushAttribute( const char* name, bool value ); + void PushAttribute( const char* name, double value ); + /// If streaming, close the Element. + virtual void CloseElement( bool compactMode=false ); + + /// Add a text node. + void PushText( const char* text, bool cdata=false ); + /// Add a text node from an integer. + void PushText( int value ); + /// Add a text node from an unsigned. + void PushText( unsigned value ); + /// Add a text node from a signed 64bit integer. + void PushText( int64_t value ); + /// Add a text node from an unsigned 64bit integer. + void PushText( uint64_t value ); + /// Add a text node from a bool. + void PushText( bool value ); + /// Add a text node from a float. + void PushText( float value ); + /// Add a text node from a double. + void PushText( double value ); + + /// Add a comment + void PushComment( const char* comment ); + + void PushDeclaration( const char* value ); + void PushUnknown( const char* value ); + + virtual bool VisitEnter( const XMLDocument& /*doc*/ ); + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); + virtual bool VisitExit( const XMLElement& element ); + + virtual bool Visit( const XMLText& text ); + virtual bool Visit( const XMLComment& comment ); + virtual bool Visit( const XMLDeclaration& declaration ); + virtual bool Visit( const XMLUnknown& unknown ); + + /** + If in print to memory mode, return a pointer to + the XML file in memory. + */ + const char* CStr() const { + return _buffer.Mem(); + } + /** + If in print to memory mode, return the size + of the XML file in memory. (Note the size returned + includes the terminating null.) + */ + int CStrSize() const { + return _buffer.Size(); + } + /** + If in print to memory mode, reset the buffer to the + beginning. + */ + void ClearBuffer( bool resetToFirstElement = true ) { + _buffer.Clear(); + _buffer.Push(0); + _firstElement = resetToFirstElement; + } + +protected: + virtual bool CompactMode( const XMLElement& ) { return _compactMode; } + + /** Prints out the space before an element. You may override to change + the space and tabs used. A PrintSpace() override should call Print(). + */ + virtual void PrintSpace( int depth ); + virtual void Print( const char* format, ... ); + virtual void Write( const char* data, size_t size ); + virtual void Putc( char ch ); + + inline void Write(const char* data) { Write(data, strlen(data)); } + + void SealElementIfJustOpened(); + bool _elementJustOpened; + DynArray< const char*, 10 > _stack; + +private: + /** + Prepares to write a new node. This includes sealing an element that was + just opened, and writing any whitespace necessary if not in compact mode. + */ + void PrepareForNewNode( bool compactMode ); + void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. + + bool _firstElement; + FILE* _fp; + int _depth; + int _textDepth; + bool _processEntities; + bool _compactMode; + + enum { + ENTITY_RANGE = 64, + BUF_SIZE = 200 + }; + bool _entityFlag[ENTITY_RANGE]; + bool _restrictedEntityFlag[ENTITY_RANGE]; + + DynArray< char, 20 > _buffer; + + // Prohibit cloning, intentionally not implemented + XMLPrinter( const XMLPrinter& ); + XMLPrinter& operator=( const XMLPrinter& ); +}; + + +} // tinyxml2 + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // TINYXML2_INCLUDED diff --git a/modules/skybrowser/include.cmake b/modules/skybrowser/include.cmake new file mode 100644 index 0000000000..499ac872db --- /dev/null +++ b/modules/skybrowser/include.cmake @@ -0,0 +1,4 @@ +set(OPENSPACE_DEPENDENCIES + webbrowser + webgui +) diff --git a/modules/skybrowser/include/browser.h b/modules/skybrowser/include/browser.h new file mode 100644 index 0000000000..cb79d09428 --- /dev/null +++ b/modules/skybrowser/include/browser.h @@ -0,0 +1,109 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___BROWSER___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___BROWSER___H__ + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable : 4100) +#endif // _MSC_VER + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-parameter" +#endif // __clang__ + +#include + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif // __clang__ + +#ifdef _MSC_VER +#pragma warning (pop) +#endif // _MSC_VER + +namespace ghoul::opengl { class Texture; } + +namespace openspace { + +class BrowserInstance; +class RenderHandler; +class WebKeyboardHandler; + +class Browser { +public: + explicit Browser(const ghoul::Dictionary& dictionary); + virtual ~Browser(); + + bool initializeGL(); + bool deinitializeGL(); + + void render(); + void update(); + bool isReady() const; + + void updateBrowserSize(); + + glm::vec2 browserPixelDimensions() const; + float browserRatio() const; + void setCallbackDimensions(const std::function& function); + +protected: + properties::Vec2Property _browserPixeldimensions; + properties::StringProperty _url; + properties::TriggerProperty _reload; + + std::unique_ptr _texture; + + void executeJavascript(const std::string& script) const; + +private: + class RenderHandler : public WebRenderHandler { + public: + void draw() override; + void render() override; + + void setTexture(GLuint t); + }; + + std::unique_ptr _browserInstance; + CefRefPtr _renderHandler; + CefRefPtr _keyboardHandler; + + bool _isUrlDirty = false; + bool _isDimensionsDirty = false; + bool _shouldReload = false; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SKYBROWSER___BROWSER___H__ diff --git a/modules/skybrowser/include/renderableskytarget.h b/modules/skybrowser/include/renderableskytarget.h new file mode 100644 index 0000000000..64e04da304 --- /dev/null +++ b/modules/skybrowser/include/renderableskytarget.h @@ -0,0 +1,79 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___RENDERABLESKYTARGET___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___RENDERABLESKYTARGET___H__ + +#include + +#include +#include +#include + +namespace openspace::documentation { struct Documentation; } + +namespace openspace { + +class ScreenSpaceSkyBrowser; + +class RenderableSkyTarget : public RenderablePlane { +public: + explicit RenderableSkyTarget(const ghoul::Dictionary& dictionary); + + void initializeGL() override; + void deinitializeGL() override; + void render(const RenderData& data, RendererTasks& rendererTask) override; + void update(const UpdateData& data) override; + void bindTexture() override; // Empty function but has to be defined + + glm::ivec3 borderColor() const; + float opacity() const; + double animationSpeed() const; + double stopAnimationThreshold() const; + + void setDimensions(glm::vec2 dimensions); + void setColor(glm::ivec3 color); + void setOpacity(float opacity); + void setVerticalFov(double fov); + + // Display + void highlight(const glm::ivec3& addition); + void removeHighlight(const glm::ivec3& removal); + +private: + // Properties + properties::FloatProperty _crossHairSize; + properties::FloatProperty _showRectangleThreshold; + properties::FloatProperty _lineWidth; + properties::DoubleProperty _stopAnimationThreshold; + properties::DoubleProperty _animationSpeed; + + double _verticalFov = 10.0; + + glm::ivec3 _borderColor = glm::ivec3(230); + glm::vec2 _dimensions = glm::vec2(1.f); +}; +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SKYBROWSER___RENDERABLESKYTARGET___H__ diff --git a/modules/skybrowser/include/screenspaceskybrowser.h b/modules/skybrowser/include/screenspaceskybrowser.h new file mode 100644 index 0000000000..a63a04ce3f --- /dev/null +++ b/modules/skybrowser/include/screenspaceskybrowser.h @@ -0,0 +1,85 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___SCREENSPACESKYBROWSER___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___SCREENSPACESKYBROWSER___H__ + +#include +#include + +#include +#include +#include +#include + +namespace openspace { + +class ScreenSpaceSkyBrowser : public ScreenSpaceRenderable, public WwtCommunicator +{ +public: + explicit ScreenSpaceSkyBrowser(const ghoul::Dictionary& dictionary); + ~ScreenSpaceSkyBrowser(); + + bool initializeGL() override; + bool deinitializeGL() override; + glm::mat4 scaleMatrix() override; + void render() override; + void update() override; + + float opacity() const; + glm::vec2 size() const; + + void setVerticalFovWithScroll(float scroll); + void setOpacity(float opacity); + void setScreenSpaceSize(const glm::vec2& newSize); + void updateScreenSpaceSize(); + + glm::dvec2 fineTuneVector(glm::dvec2 drag); + void setIdInBrowser(); + + void updateTextureResolution(); + + // Copies rendered + void addRenderCopy(const glm::vec3& raePosition, int nCopies); + void removeRenderCopy(); + std::vector> renderCopies(); + void moveRenderCopy(int i, glm::vec3 raePosition); + +private: + properties::FloatProperty _textureQuality; + properties::BoolProperty _renderOnlyOnMaster; + std::vector> _renderCopies; + + void bindTexture() override; + + // Flags + bool _isSyncedWithWwt = false; + bool _textureDimensionsIsDirty = false; + bool _sizeIsDirty = false; + + glm::vec2 _size = glm::vec2(1.f, 1.f); +}; +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SKYBROWSER___SCREENSPACESKYBROWSER___H__ diff --git a/modules/skybrowser/include/targetbrowserpair.h b/modules/skybrowser/include/targetbrowserpair.h new file mode 100644 index 0000000000..b0f467f7f5 --- /dev/null +++ b/modules/skybrowser/include/targetbrowserpair.h @@ -0,0 +1,138 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___TARGETBROWSERPAIR___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___TARGETBROWSERPAIR___H__ + +#include +#include +#include +#include + +namespace openspace { + +class ScreenSpaceSkyBrowser; +class RenderableSkyTarget; +class ScreenSpaceRenderable; +class ImageData; +class SceneGraphNode; + +class TargetBrowserPair { +public: + TargetBrowserPair(SceneGraphNode* target, ScreenSpaceSkyBrowser* browser); + TargetBrowserPair& operator=(TargetBrowserPair other); + + // Target & Browser + void initialize(); + // Highlighting + void removeHighlight(const glm::ivec3& color); + void highlight(const glm::ivec3& color); + // Animation + void startAnimation(glm::dvec3 coordsEnd, double fovEnd); + void incrementallyAnimateToCoordinate(); + void startFading(float goal, float fadeTime); + void incrementallyFade(); + // Mouse interaction + void startFinetuningTarget(); + void fineTuneTarget(const glm::vec2& startMouse, const glm::vec2& translation); + void synchronizeAim(); + + // Browser + void sendIdToBrowser(); + void updateBrowserSize(); + std::vector> renderCopies(); + + // Target + void centerTargetOnScreen(); + double targetRoll(); + + bool hasFinishedFading() const; + bool isFacingCamera() const; + bool isUsingRadiusAzimuthElevation() const; + bool isEnabled() const; + + void setEnabled(bool enable); + void setOpacity(float opacity); + void setIsSyncedWithWwt(bool isSynced); + void setVerticalFov(double vfov); + void setEquatorialAim(const glm::dvec2& aim); + void setBorderColor(const glm::ivec3& color); + void setScreenSpaceSize(const glm::vec2& dimensions); + void setVerticalFovWithScroll(float scroll); + + double verticalFov() const; + glm::ivec3 borderColor() const; + glm::dvec2 targetDirectionEquatorial() const; + glm::dvec3 targetDirectionGalactic() const; + std::string browserGuiName() const; + std::string browserId() const; + std::string targetRenderableId() const; + std::string targetNodeId() const; + std::string selectedId(); + glm::vec2 size() const; + + SceneGraphNode* targetNode() const; + ScreenSpaceSkyBrowser* browser() const; + const std::deque& selectedImages() const; + + // WorldWide Telescope image handling + void setImageOrder(int i, int order); + void selectImage(const ImageData& image, int i); + void removeSelectedImage(int i); + void loadImageCollection(const std::string& collection); + void setImageOpacity(int i, float opacity); + void hideChromeInterface(bool shouldHide); + + friend bool operator==(const TargetBrowserPair& lhs, + const TargetBrowserPair& rhs); + friend bool operator!=(const TargetBrowserPair& lhs, + const TargetBrowserPair& rhs); + +private: + void aimTargetGalactic(glm::dvec3 direction); + + // Target and browser + RenderableSkyTarget* _targetRenderable = nullptr; + ScreenSpaceSkyBrowser* _browser = nullptr; + SceneGraphNode* _targetNode = nullptr; + + // Animation + skybrowser::Animation _fadeBrowser = skybrowser::Animation(0.f, 0.f, 0.0); + skybrowser::Animation _fadeTarget = skybrowser::Animation(0.f, 0.f, 0.0); + skybrowser::Animation _fovAnimation = skybrowser::Animation(0.0, 0.0, 0.0); + skybrowser::Animation _moveTarget = + skybrowser::Animation(glm::dvec3(0.0), glm::dvec3(0.0), 0.0); + bool _targetIsAnimating = false; + + // Dragging + glm::dvec3 _startTargetPosition = glm::dvec3(0.0); + + glm::dvec2 _equatorialAim = glm::dvec2(0.0); + glm::ivec3 _borderColor = glm::ivec3(255); + glm::vec2 _dimensions = glm::vec2(0.5f); +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SKYBROWSER___TARGETBROWSERPAIR___H__ diff --git a/modules/skybrowser/include/utility.h b/modules/skybrowser/include/utility.h new file mode 100644 index 0000000000..432793be4c --- /dev/null +++ b/modules/skybrowser/include/utility.h @@ -0,0 +1,242 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___UTILITY___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___UTILITY___H__ + +#include +#include +#include + +namespace openspace::skybrowser { +// Constants +constexpr const double ScreenSpaceZ = -2.1; +constexpr const glm::dvec3 NorthPole = { 0.0, 0.0, 1.0 }; +constexpr const double CelestialSphereRadius = 4 * distanceconstants::Parsec; + +// Conversion matrix - J2000 equatorial <-> galactic +// https://arxiv.org/abs/1010.3773v1 +const glm::dmat3 conversionMatrix = glm::dmat3({ + -0.054875539390, 0.494109453633, -0.867666135681, // col 0 + -0.873437104725, -0.444829594298, -0.198076389622, // col 1 + -0.483834991775, 0.746982248696, 0.455983794523 // col 2 + }); + +// Galactic coordinates are projected onto the celestial sphere +// Equatorial coordinates are unit length +// Conversion spherical <-> Cartesian +/** + * Converts from Cartesian coordinates to spherical coordinates with unit length. + * \param coords Cartesian coordinates + * \return Spherical coordinates with unit length in degrees + */ +glm::dvec2 cartesianToSpherical(const glm::dvec3& coords); +/** + * Converts from spherical coordinates to Cartesian coordinates with unit length. + * \param coords Spherical coordinates in degrees + * \return Cartesian coordinates with unit length + */ +glm::dvec3 sphericalToCartesian(const glm::dvec2& coords); + +// Conversion J2000 equatorial <-> galactic +/** + * Converts from Cartesian galactic coordinates to Cartesian equatorial coordinates in epoch + * J2000 with unit length. + * \param coords Cartesian galactic coordinates + * \return Cartesian equatorial coordinates in the epoch of J2000 with unit length + */ +glm::dvec3 galacticToEquatorial(const glm::dvec3& coords); +/** + * Converts from Cartesian equatorial coordinates to Cartesian galactic + * coordinates. The galactic coordinates vector has the length of the radius of the + * Celestial sphere. + * \param coords Cartesian equatorial coordinates + * \return Cartesian galactic coordinates placed on the Celestial sphere + */ +glm::dvec3 equatorialToGalactic(const glm::dvec3& coords); + +// Conversion to screenspace from local camera / pixels +/** + * Converts from local camera coordinates to screenspace coordinates. The screenspace + * coordinates are placed on the screenspace plane which has the z-coordinate as -2.1. + * \param coords Cartesian local camera coordinates + * \return Cartesian galactic coordinates placed on the Celestial sphere + */ +glm::dvec3 localCameraToScreenSpace3d(const glm::dvec3& coords); +/** + * Converts from pixel coordinates to screenspace coordinates in 2D. + * \param mouseCoordinate Pixel coordinate + * \return Cartesian ScreenSpace coordinate + */ +glm::vec2 pixelToScreenSpace2d(const glm::vec2& mouseCoordinate); + +// Conversion local camera space <-> galactic / equatorial +/** + * Converts from Cartesian equatorial coordinates in epoch J2000 to local camera space. + * \param coords Cartesian equatorial coordinates in epoch J2000 + * \return Local camera coordinates with unit length + */ +glm::dvec3 equatorialToLocalCamera(const glm::dvec3& coords); +/** + * Converts from Cartesian galactic coordinates to local camera space with unit length. + * \param coords Cartesian galactic coordinates + * \return Cartesian local camera coordinates with unit length + */ +glm::dvec3 galacticToLocalCamera(const glm::dvec3& coords); +/** + * Converts from Cartesian local camera coordinates to galactic coordinates. + * \param coords Cartesian local camera coordinates + * \return Cartesian galactic coordinates placed on the Celestial sphere + */ +glm::dvec3 localCameraToGalactic(const glm::dvec3& coords); +/** + * Converts from local camera coordinates to Cartesian equatorial coordinates in the epoch + * J2000. + * \param coords Cartesian local camera coordinates + * \return Cartesian equatorial coordinates with unit length + */ +glm::dvec3 localCameraToEquatorial(const glm::dvec3& coords); + +// Camera roll and direction +/** + * Returns the angle between the up direction of the OpenSpace camera and the equatorial + * North Pole direction. + * \return Angle in degrees between the OpenSpace camera's up direction vector and the + * equatorial North Pole direction. + */ +double targetRoll(const glm::dvec3& up, const glm::dvec3& forward); +/** + * Returns the view direction of the OpenSpace camera in galactic coordinates. + * \return View direction of the OpenSpace camera in Cartesian galactic coordinates. + */ +glm::dvec3 cameraDirectionGalactic(); +/** + * Returns the view direction of the OpenSpace camera in equatorial coordinates in epoch + * J2000. + * \return View direction of the OpenSpace camera in Cartesian equatorial coordinates in + * epoch J2000. + */ +glm::dvec3 cameraDirectionEquatorial(); + +// Window and field of view +/** + * Returns the window ratio r which is calculated as x / y. + * \return The window ratio x / y + */ +float windowRatio(); +/** + * Returns the vertical and horizontal field of view of the OpenSpace window. + * \return The horizontal and vertical field of view in degrees. + */ +glm::dvec2 fovWindow(); +/** + * Returns true if the Cartesian equatorial coordinate is in the current view of the + * camera. + * \param equatorial Cartesian equatorial coordinates in epoch J2000 + * \return True if the coordinates are in the camera's current field of view + */ +bool isCoordinateInView(const glm::dvec3& equatorial); + +// Animation for target and camera +/** + * Returns the angle between two vectors. + * \param start Cartesian vector + * \param end Cartesian vector + * \return Angle between two vectors in radians + */ +double angleBetweenVectors(const glm::dvec3& start, const glm::dvec3& end); +/** + * Returns a 4x4 matrix for an incremental rotation of a vector. The matrix should be used + * multiple times in order to animate. + * \param start Cartesian vector + * \param end Cartesian vector + * \param percentage Percentage of the angle between the vectors that the matrix should + * rotate + * \return 4x4 matrix for incremental rotation animation of a vector + */ +glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& end, + double percentage); +/** + * Returns the size in meters that for example a plane would need to have in order to + * display a specified field of view. + * \param fov The set field of view + * \param worldPosition The galactic position of the plane + * \return Field of view + */ +double sizeFromFov(double fov, glm::dvec3 worldPosition); + +template +class Animation { +public: + Animation(T start, T goal, double time) + : _start(start), _goal(goal) + { + _animationTime = std::chrono::milliseconds(static_cast(time * 1000)); + } + void start() { + _isStarted = true; + _startTime = std::chrono::system_clock::now(); + } + void stop() { + _isStarted = false; + } + bool isAnimating() const { + bool timeLeft = timeSpent().count() < _animationTime.count() ? true : false; + return timeLeft && _isStarted; + } + T getNewValue(); + glm::dmat4 getRotationMatrix(); + +private: + std::chrono::duration timeSpent() const { + using namespace std::chrono; + system_clock::time_point now = system_clock::now(); + std::chrono::duration timeSpent = now - _startTime; + return timeSpent; + } + double percentageSpent() const { + return timeSpent().count() / _animationTime.count(); + } + + double easeOutExpo(double x) { + double epsilon = std::numeric_limits::epsilon(); + return std::abs(x - 1.0) < epsilon ? 1.0 : 1.0 - pow(2.0, -10.0 * x); + } + + double easeInOutSine(double x) { + return -(cos(glm::pi() * x) - 1.0) / 2.0; + } + + // Animation + bool _isStarted = false; + double _lastPercentage = 0; + T _goal; + T _start; + std::chrono::milliseconds _animationTime = std::chrono::milliseconds(2000); + std::chrono::system_clock::time_point _startTime; +}; + +} // namespace openspace::skybrowser + +#endif // __OPENSPACE_MODULE_SKYBROWSER___UTILITY___H__ diff --git a/modules/skybrowser/include/wwtcommunicator.h b/modules/skybrowser/include/wwtcommunicator.h new file mode 100644 index 0000000000..c0e76c3185 --- /dev/null +++ b/modules/skybrowser/include/wwtcommunicator.h @@ -0,0 +1,114 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___WWTCOMMUNICATOR___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___WWTCOMMUNICATOR___H__ + +#include + +#include +#include +#include +#include +#include + +namespace openspace { + +class WwtCommunicator : public Browser { +public: + explicit WwtCommunicator(const ghoul::Dictionary& dictionary); + WwtCommunicator(const WwtCommunicator&) = default; + ~WwtCommunicator(); + + void update(); + void render(); + void initializeGL(); + void deinitializeGL(); + + // WorldWide Telescope communication + void displayImage(const std::string& url, int i); + void removeSelectedImage(int i); + void setImageOrder(int i, int order); + void loadImageCollection(const std::string& collection); + void setImageOpacity(int i, float opacity); + void hideChromeInterface(bool shouldHide); + + bool hasLoadedImages() const; + double verticalFov() const; + glm::ivec3 borderColor() const; + glm::dvec2 equatorialAim() const; + glm::dvec2 fieldsOfView() const; + const std::deque& getSelectedImages() const; + + void setHasLoadedImages(bool isLoaded); + void setVerticalFov(double vfov); + void setIsSyncedWithWwt(bool isSynced); + void setEquatorialAim(glm::dvec2 equatorial); + void setBorderColor(glm::ivec3 color); + void setTargetRoll(double roll); + + void highlight(const glm::ivec3& addition); + // The removal parameter decides what will be removed from the border color + void removeHighlight(const glm::ivec3& removal); + void updateBorderColor(); + void updateAim(); + +protected: + void setIdInBrowser(const std::string& id); + + double _verticalFov = 10.0f; + glm::ivec3 _borderColor = glm::ivec3(70); + glm::dvec2 _equatorialAim = glm::dvec2(0.0); + double _targetRoll = 0.0; + bool _hasLoadedImages = false; + std::deque _selectedImages; + +private: + void setWebpageBorderColor(glm::ivec3 color); + void sendMessageToWwt(const ghoul::Dictionary& msg); + + // WorldWide Telescope messages + ghoul::Dictionary moveCameraMessage(const glm::dvec2& celestCoords, double fov, + double roll, bool shouldMoveInstantly = true); + ghoul::Dictionary loadCollectionMessage(const std::string& url); + ghoul::Dictionary setForegroundMessage(const std::string& name); + ghoul::Dictionary addImageMessage(const std::string& id, const std::string& url); + ghoul::Dictionary removeImageMessage(const std::string& id); + ghoul::Dictionary setImageOpacityMessage(const std::string& id, double opacity); + ghoul::Dictionary setLayerOrderMessage(const std::string& id, int version); + + bool _isSyncedWithWwt = false; + bool _borderColorIsDirty = false; + bool _equatorialAimIsDirty = false; + int messageCounter = 0; + + // Time variables + // For capping the message passing to WWT + constexpr static const std::chrono::milliseconds TimeUpdateInterval = + std::chrono::milliseconds(10); + std::chrono::system_clock::time_point _lastUpdateTime; +}; +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SKYBROWSER___WWTCOMMUNICATOR___H__ diff --git a/modules/skybrowser/include/wwtdatahandler.h b/modules/skybrowser/include/wwtdatahandler.h new file mode 100644 index 0000000000..83a8e93fce --- /dev/null +++ b/modules/skybrowser/include/wwtdatahandler.h @@ -0,0 +1,88 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___WWTDATAHANDLER___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___WWTDATAHANDLER___H__ + +#include +#include +#include +#include + +namespace openspace::documentation { struct Documentation; } + +namespace openspace::wwt { + const std::string Thumbnail = "Thumbnail"; + const std::string Name = "Name"; + const std::string ImageSet = "ImageSet"; + const std::string Dec = "Dec"; + const std::string RA = "RA"; + const std::string Undefined = ""; + const std::string Folder = "Folder"; + const std::string Place = "Place"; + const std::string ThumbnailUrl = "ThumbnailUrl"; + const std::string Url = "Url"; + const std::string Credits = "Credits"; + const std::string CreditsUrl = "CreditsUrl"; + const std::string ZoomLevel = "ZoomLevel"; + const std::string DataSetType = "DataSetType"; + const std::string Sky = "Sky"; +} // namespace openspace::wwt + +namespace openspace { + +struct ImageData { + std::string name = wwt::Undefined; + std::string thumbnailUrl = wwt::Undefined; + std::string imageUrl = wwt::Undefined; + std::string credits = wwt::Undefined; + std::string creditsUrl = wwt::Undefined; + std::string collection = wwt::Undefined; + bool hasCelestialCoords = false; + float fov = 0.f; + glm::dvec2 equatorialSpherical = glm::dvec2(0.0); + glm::dvec3 equatorialCartesian = glm::dvec3(0.0); +}; + +class WwtDataHandler { +public: + WwtDataHandler() = default; + ~WwtDataHandler(); + + void loadImages(const std::string& root, const std::filesystem::path& directory); + int nLoadedImages() const; + const ImageData& getImage(int i) const; + +private: + void saveImageFromNode(tinyxml2::XMLElement* node, std::string collection); + void saveImagesFromXml(tinyxml2::XMLElement* root, std::string collection); + + // Images + std::vector _images; + std::vector _xmls; +}; +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SKYBROWSER___WWTDATAHANDLER___H__ + diff --git a/modules/skybrowser/shaders/target_fs.glsl b/modules/skybrowser/shaders/target_fs.glsl new file mode 100644 index 0000000000..3cf1d038e6 --- /dev/null +++ b/modules/skybrowser/shaders/target_fs.glsl @@ -0,0 +1,114 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + + +in vec4 vs_gPosition; +in vec3 vs_gNormal; +in float vs_screenSpaceDepth; +in vec2 vs_st; +in vec4 vs_position; + +uniform float crossHairSize; +uniform bool showRectangle; +uniform float lineWidth; +uniform vec2 dimensions; +uniform vec4 lineColor; +uniform float fov; + +uniform bool additiveBlending; +uniform float opacity = 1.0; +uniform vec3 multiplyColor; + +// A factor which states how much thicker vertical lines are rendered than horizontal +// This compensates for the optical illusion that vertical lines appear thinner +const float VerticalThickness = 1.1; + +float createLine(float lineCenter, float lineWidth, float coord) { + // Calculate edges of line + float startEdge = lineCenter - (lineWidth * 0.5); + float endEdge = lineCenter + (lineWidth * 0.5); + + return step(startEdge, coord) - step(endEdge, coord); +} + +float createFilledRectangle(float width, float height, vec2 coord) { + return createLine(0.5, width, coord.x) * createLine(0.5, height, coord.y); +} + +float createCrosshair(in float linewidth, in float ratio, in vec2 coord) { + const float Center = 0.5; + float crosshairVertical = createLine(Center, linewidth * VerticalThickness, coord.x); + float crosshairHorizontal = createLine(Center, linewidth, coord.y); + + return crosshairHorizontal + crosshairVertical; +} + +#include "fragment.glsl" + +Fragment getFragment() { + float ratio = dimensions.y / dimensions.x; + float rectangle = 0.0; + float maxWwtFov = 70; + + float crosshair = createCrosshair(lineWidth, ratio, vs_st); + float crossHairHeight = crossHairSize/maxWwtFov; + float crossHairWidth = crossHairHeight * ratio; + float crossHairBox = createFilledRectangle(crossHairHeight, crossHairWidth, vs_st); + crosshair *= crossHairBox; + + if (showRectangle) { + float height = (fov * 0.5)/maxWwtFov; + float width = height * ratio; + float outerEdge = createFilledRectangle(height, width, vs_st); + float lineWidthX = lineWidth * 2 * VerticalThickness; + float lineWidthY = lineWidth * 2; + float innerEdge = createFilledRectangle(height-lineWidthX, width-lineWidthY, vs_st); + rectangle = outerEdge - innerEdge; + } + + float result = clamp(crosshair + rectangle, 0.0, 1.0); + + Fragment frag; + frag.color = lineColor; + frag.color.a *= result; + + frag.color.rgb *= multiplyColor; + + frag.color.a *= opacity; + if (frag.color.a == 0.0) { + discard; + } + + frag.depth = vs_screenSpaceDepth; + + if (additiveBlending) { + frag.blend = BLEND_MODE_ADDITIVE; + } + + // G-Buffer + frag.gPosition = vs_gPosition; + frag.gNormal = vec4(vs_gNormal, 1.0); + + return frag; +} diff --git a/modules/skybrowser/shaders/target_vs.glsl b/modules/skybrowser/shaders/target_vs.glsl new file mode 100644 index 0000000000..497e19384a --- /dev/null +++ b/modules/skybrowser/shaders/target_vs.glsl @@ -0,0 +1,52 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + #version __CONTEXT__ + + #include "PowerScaling/powerScaling_vs.hglsl" + + layout(location = 0) in vec4 in_position; + layout(location = 1) in vec2 in_st; + + out vec4 vs_gPosition; + out vec3 vs_gNormal; + out float vs_screenSpaceDepth; + out vec2 vs_st; + + uniform mat4 modelViewProjectionTransform; + uniform mat4 modelViewTransform; + + void main() { + vec4 position = vec4(in_position.xyz * pow(10, in_position.w), 1); + vec4 positionClipSpace = modelViewProjectionTransform * position; + vec4 positionScreenSpace = z_normalization(positionClipSpace); + + gl_Position = positionScreenSpace; + + // G-Buffer + vs_gNormal = vec3(0.0); + vs_gPosition = vec4(modelViewTransform * position); // Must be in SGCT eye space; + + vs_st = in_st; + vs_screenSpaceDepth = positionScreenSpace.w; + } diff --git a/modules/skybrowser/skybrowsermodule.cpp b/modules/skybrowser/skybrowsermodule.cpp new file mode 100644 index 0000000000..225856ea9a --- /dev/null +++ b/modules/skybrowser/skybrowsermodule.cpp @@ -0,0 +1,447 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "skybrowsermodule_lua.inl" + +namespace { + constexpr const openspace::properties::Property::PropertyInfo AllowRotationInfo = { + "AllowCameraRotation", + "Allow Camera Rotation", + "Toggles if the camera should rotate to look at the sky target if it is going " + "outside of the current field of view." + }; + + constexpr const openspace::properties::Property::PropertyInfo CameraRotSpeedInfo = { + "CameraRotationSpeed", + "Camera Rotation Speed", + "The speed of the rotation of the camera when the camera rotates to look at a " + "coordinate which is outside of the field of view." + }; + + constexpr const openspace::properties::Property::PropertyInfo TargetSpeedInfo = { + "TargetAnimationSpeed", + "Target Animation Speed", + "This determines the speed of the animation of the sky target." + }; + + constexpr const openspace::properties::Property::PropertyInfo BrowserSpeedInfo = { + "BrowserAnimationSpeed", + "Field Of View Animation Speed", + "This determines the speed of the animation of the field of view in the browser." + }; + + struct [[codegen::Dictionary(SkyBrowserModule)]] Parameters { + + // [[codegen::verbatim(AllowRotationInfo.description)]] + std::optional allowCameraRotation; + + // [[codegen::verbatim(CameraRotSpeedInfo.description)]] + std::optional cameraRotSpeed; + + // [[codegen::verbatim(TargetSpeedInfo.description)]] + std::optional targetSpeed; + + // [[codegen::verbatim(BrowserSpeedInfo.description)]] + std::optional browserSpeed; + }; + + #include "skybrowsermodule_codegen.cpp" +} // namespace + +namespace openspace { +SkyBrowserModule::SkyBrowserModule() + : OpenSpaceModule(SkyBrowserModule::Name) + , _allowCameraRotation(AllowRotationInfo, true) + , _cameraRotationSpeed(CameraRotSpeedInfo, 0.5, 0.0, 1.0) + , _targetAnimationSpeed(TargetSpeedInfo, 0.2, 0.0, 1.0) + , _browserAnimationSpeed(BrowserSpeedInfo, 5.0, 0.0, 10.0) +{ + addProperty(_allowCameraRotation); + addProperty(_cameraRotationSpeed); + addProperty(_targetAnimationSpeed); + addProperty(_browserAnimationSpeed); + + // Set callback functions + global::callback::mouseButton->emplace(global::callback::mouseButton->begin(), + [&](MouseButton button, MouseAction action, KeyModifier modifier) -> bool { + if (action == MouseAction::Press) { + _cameraRotation.stop(); + return false; + } + else { + return false; + } + } + ); + + global::callback::preSync->emplace_back([this]() { + // Disable browser and targets when camera is outside of solar system + bool camWasInSolarSystem = _isCameraInSolarSystem; + glm::dvec3 cameraPos = global::navigationHandler->camera()->positionVec3(); + _isCameraInSolarSystem = glm::length(cameraPos) < SolarSystemRadius; + bool vizModeChanged = _isCameraInSolarSystem != camWasInSolarSystem; + + // Visualization mode changed. Start fading + if (vizModeChanged && !_isCameraInSolarSystem) { + // Camera moved into the solar system + _isFading = true; + _goal = Transparency::Transparent; + + float transparency = [](Transparency goal) { + switch (goal) { + case Transparency::Transparent: + return 0.f; + + case Transparency::Opaque: + return 1.f; + } + }(_goal); + + std::for_each( + _targetsBrowsers.begin(), + _targetsBrowsers.end(), + [&](const std::unique_ptr& pair) { + pair->startFading(transparency, 2.f); + } + ); + } + // Fade pairs if the camera moved in or out the solar system + if (_isFading) { + incrementallyFadeBrowserTargets(_goal); + } + if (_isCameraInSolarSystem) { + std::for_each( + _targetsBrowsers.begin(), + _targetsBrowsers.end(), + [&](const std::unique_ptr& pair) { + pair->synchronizeAim(); + } + ); + incrementallyAnimateTargets(); + } + if (_cameraRotation.isAnimating() && _allowCameraRotation) { + incrementallyRotateCamera(); + } + }); +} + +void SkyBrowserModule::internalInitialize(const ghoul::Dictionary& dict) { + const Parameters p = codegen::bake(dict); + + // Register ScreenSpaceRenderable + ghoul::TemplateFactory* fScreenSpaceRenderable = + FactoryManager::ref().factory(); + ghoul_assert(fScreenSpaceRenderable, "ScreenSpaceRenderable factory was not created"); + + + // Register ScreenSpaceSkyBrowser + fScreenSpaceRenderable->registerClass("ScreenSpaceSkyBrowser"); + + // Register ScreenSpaceRenderable + ghoul::TemplateFactory* fRenderable = + FactoryManager::ref().factory(); + ghoul_assert(fRenderable, "Renderable factory was not created"); + + // Register ScreenSpaceSkyTarget + fRenderable->registerClass("RenderableSkyTarget"); + + // Create data handler dynamically to avoid the linking error that + // came up when including the include file in the module header file + _dataHandler = std::make_unique(); +} + +void SkyBrowserModule::addTargetBrowserPair(const std::string& targetId, const std::string& browserId) { + if (!global::renderEngine->scene()) { + return; + } + + SceneGraphNode* target = global::renderEngine->scene()->sceneGraphNode(targetId); + ScreenSpaceSkyBrowser* browser = dynamic_cast( + global::renderEngine->screenSpaceRenderable(browserId) + ); + + // Ensure pair has both target and browser + if (browser && target) { + _targetsBrowsers.push_back(std::make_unique(target, browser)); + } +} + +void SkyBrowserModule::removeTargetBrowserPair(const std::string& id) { + TargetBrowserPair* found = getPair(id); + if (!found) { + return; + } + + auto it = std::remove_if( + _targetsBrowsers.begin(), + _targetsBrowsers.end(), + [&](const std::unique_ptr& pair) { + return *found == *(pair.get()); + } + ); + + _targetsBrowsers.erase(it, _targetsBrowsers.end()); + _mouseOnPair = nullptr; +} + +void SkyBrowserModule::lookAtTarget(const std::string& id) { + TargetBrowserPair* pair = getPair(id); + if (pair) { + startRotatingCamera(pair->targetDirectionGalactic()); + } +} + +void SkyBrowserModule::setHoverCircle(SceneGraphNode* circle) { + _hoverCircle = circle; +} + +void SkyBrowserModule::moveHoverCircle(int i) { + const ImageData& image = _dataHandler->getImage(i); + + // Only move and show circle if the image has coordinates + if (_hoverCircle && image.hasCelestialCoords && _isCameraInSolarSystem) { + // Make circle visible + _hoverCircle->renderable()->property("Enabled")->set(true); + + // Set the exact target position + // Move it slightly outside of the celestial sphere so it doesn't overlap with + // the target + glm::dvec3 pos = skybrowser::equatorialToGalactic(image.equatorialCartesian); + pos *= skybrowser::CelestialSphereRadius * 1.1; + // Uris for properties + std::string id = _hoverCircle->identifier(); + std::string positionUri = "Scene." + id + ".Translation.Position"; + std::string setValue = "openspace.setPropertyValueSingle('"; + + openspace::global::scriptEngine->queueScript( + setValue + positionUri + "', " + ghoul::to_string(pos) + ");", + scripting::ScriptEngine::RemoteScripting::Yes + ); + } +} + +void SkyBrowserModule::disableHoverCircle() { + if (_hoverCircle && _hoverCircle->renderable()) { + _hoverCircle->renderable()->property("Enabled")->set(false); + } +} + +void SkyBrowserModule::loadImages(const std::string& root, + const std::filesystem::path& directory) { + _dataHandler->loadImages(root, directory); +} + +int SkyBrowserModule::nLoadedImages() { + return _dataHandler->nLoadedImages(); +} + +const std::unique_ptr& SkyBrowserModule::getWwtDataHandler() const { + return _dataHandler; +} + +std::vector>& SkyBrowserModule::getPairs() { + return _targetsBrowsers; +} + +int SkyBrowserModule::nPairs() { + return static_cast(_targetsBrowsers.size()); +} + +TargetBrowserPair* SkyBrowserModule::getPair(const std::string& id) { + auto it = std::find_if( + _targetsBrowsers.begin(), + _targetsBrowsers.end(), + [&](const std::unique_ptr& pair) { + bool foundBrowser = pair->browserId() == id; + bool foundTarget = pair->targetRenderableId() == id; + bool foundTargetNode = pair->targetNodeId() == id; + return foundBrowser || foundTarget || foundTargetNode; + } + ); + if (it == std::end(_targetsBrowsers)) { + return nullptr; + } + else { + return it->get(); + } +} + +void SkyBrowserModule::startRotatingCamera(glm::dvec3 endAnimation) { + // Save coordinates to rotate to in galactic world coordinates + glm::dvec3 start = skybrowser::cameraDirectionGalactic(); + double angle = skybrowser::angleBetweenVectors(start, endAnimation); + double time = angle / _cameraRotationSpeed; + _cameraRotation = skybrowser::Animation(start, endAnimation, time); + _cameraRotation.start(); +} + +void SkyBrowserModule::incrementallyRotateCamera() { + if(_cameraRotation.isAnimating()) { + glm::dmat4 rotMat = _cameraRotation.getRotationMatrix(); + // Rotate + global::navigationHandler->camera()->rotate(glm::quat_cast(rotMat)); + } +} + +void SkyBrowserModule::incrementallyFadeBrowserTargets(Transparency goal) +{ + bool isAllFinished = true; + for (std::unique_ptr& pair : _targetsBrowsers) { + if (pair->isEnabled()) { + bool isPairFinished = pair->hasFinishedFading(); + if (!isPairFinished) { + pair->incrementallyFade(); + } + else if (isPairFinished && goal == Transparency::Transparent) { + pair->setEnabled(false); + pair->setOpacity(1.0); + + } + isAllFinished &= isPairFinished; + } + } + + // The transition is over when the fade is finished + if (isAllFinished) { + _isFading = false; + } +} + +void SkyBrowserModule::incrementallyAnimateTargets() { + for (std::unique_ptr& pair : _targetsBrowsers) { + if (pair->isEnabled()) { + pair->incrementallyAnimateToCoordinate(); + } + } +} + +double SkyBrowserModule::targetAnimationSpeed() const { + return _targetAnimationSpeed; +} + +double SkyBrowserModule::browserAnimationSpeed() const { + return _browserAnimationSpeed; +} + +void SkyBrowserModule::setSelectedBrowser(const std::string& id) { + TargetBrowserPair* found = getPair(id); + if (found) { + _selectedBrowser = id; + } +} + +std::string SkyBrowserModule::selectedBrowserId() const { + return _selectedBrowser; +} + +std::string SkyBrowserModule::selectedTargetId() { + TargetBrowserPair* found = getPair(_selectedBrowser); + if (found) { + return found->targetRenderableId(); + } + else { + return ""; + } +} + +glm::ivec3 SkyBrowserModule::highlight() const { + return _highlightAddition; +} + +bool SkyBrowserModule::isCameraInSolarSystem() const { + return _isCameraInSolarSystem; +} + +bool SkyBrowserModule::isSelectedPairUsingRae() { + TargetBrowserPair* found = getPair(_selectedBrowser); + if (found) { + return found->isUsingRadiusAzimuthElevation(); + } + else { + return false; + } +} + +bool SkyBrowserModule::isSelectedPairFacingCamera() { + TargetBrowserPair* found = getPair(_selectedBrowser); + if (found) { + return found->isFacingCamera(); + } + else { + return false; + } +} + +scripting::LuaLibrary SkyBrowserModule::luaLibrary() const { + return { + "skybrowser", + { + codegen::lua::StartSetup, + codegen::lua::InitializeBrowser, + codegen::lua::SendOutIdsToBrowsers, + codegen::lua::GetListOfImages, + codegen::lua::SetHoverCircle, + codegen::lua::MoveCircleToHoverImage, + codegen::lua::DisableHoverCircle, + codegen::lua::LoadImagesToWWT, + codegen::lua::SelectImage, + codegen::lua::RemoveSelectedImageInBrowser, + codegen::lua::AdjustCamera, + codegen::lua::SetSelectedBrowser, + codegen::lua::GetTargetData, + codegen::lua::CreateTargetBrowserPair, + codegen::lua::RemoveTargetBrowserPair, + codegen::lua::SetOpacityOfImageLayer, + codegen::lua::CenterTargetOnScreen, + codegen::lua::SetImageLayerOrder, + codegen::lua::AddPairToSkyBrowserModule, + codegen::lua::SetEquatorialAim, + codegen::lua::SetVerticalFov, + codegen::lua::SetBorderColor, + codegen::lua::TranslateScreenSpaceRenderable, + codegen::lua::AddRenderCopy, + codegen::lua::SetScreenSpaceSize, + codegen::lua::RemoveRenderCopy, + codegen::lua::StartFinetuningTarget, + codegen::lua::FinetuneTargetPosition, + codegen::lua::ScrollOverBrowser + } + }; +} + +} // namespace openspace diff --git a/modules/skybrowser/skybrowsermodule.h b/modules/skybrowser/skybrowsermodule.h new file mode 100644 index 0000000000..486b73c9be --- /dev/null +++ b/modules/skybrowser/skybrowsermodule.h @@ -0,0 +1,146 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SKYBROWSER___SKYBROWSERMODULE___H__ +#define __OPENSPACE_MODULE_SKYBROWSER___SKYBROWSERMODULE___H__ + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace openspace { + +class ScreenSpaceImageLocal; +class WwtDataHandler; +class TargetBrowserPair; +class SceneGraphNode; +class ImageData; + +enum class Transparency { + Transparent, + Opaque +}; + +enum class MouseInteraction { + Hover, + Drag, + FineTune, +}; + +class SkyBrowserModule : public OpenSpaceModule { +public: + constexpr static const char* Name = "SkyBrowser"; + const double SolarSystemRadius = 30.0 * distanceconstants::AstronomicalUnit; + + SkyBrowserModule(); + + std::vector>& getPairs(); + int nPairs(); + TargetBrowserPair* getPair(const std::string& id); + const std::unique_ptr& getWwtDataHandler() const; + std::string selectedBrowserId() const; + std::string selectedTargetId(); + glm::ivec3 highlight() const; + + void setSelectedBrowser(const std::string& id); + void setSelectedObject(); // Manage mouse interactions + void setHoverCircle(SceneGraphNode* circle); + + // Rotation, animation, placement + void lookAtTarget(const std::string& id); + void startRotatingCamera(glm::dvec3 endAnimation); // Pass in galactic coordinate + void incrementallyRotateCamera(); + void incrementallyFadeBrowserTargets(Transparency goal); + void incrementallyAnimateTargets(); + double targetAnimationSpeed() const; + double browserAnimationSpeed() const; + + bool isCameraInSolarSystem() const; + bool isSelectedPairFacingCamera(); + bool isSelectedPairUsingRae(); + + // Managing the target browser pairs + void removeTargetBrowserPair(const std::string& browserId); + void addTargetBrowserPair(const std::string& targetId, const std::string& browserId); + + // Hover circle + void moveHoverCircle(int i); + void disableHoverCircle(); + + // Image collection handling + void loadImages(const std::string& root, const std::filesystem::path& directory); + int nLoadedImages(); + + // Mouse interaction + void handleMouseClick(const MouseButton& button); + + scripting::LuaLibrary luaLibrary() const override; + //std::vector documentations() const override; + +protected: + void internalInitialize(const ghoul::Dictionary& dict) override; + +private: + properties::BoolProperty _allowCameraRotation; + properties::DoubleProperty _cameraRotationSpeed; + properties::DoubleProperty _targetAnimationSpeed; + properties::DoubleProperty _browserAnimationSpeed; + glm::ivec3 _highlightAddition = glm::ivec3(35); // Highlight object when mouse hovers + + // The browsers and targets + std::vector> _targetsBrowsers; + TargetBrowserPair* _mouseOnPair = nullptr; + SceneGraphNode* _hoverCircle = nullptr; + std::string _selectedBrowser = ""; // Currently selected browser + + // Fading + Transparency _goal = Transparency::Opaque; + + // Flags + bool _isCameraInSolarSystem = true; // Visualization modes + bool _isFading = false; + + // Mouse interaction + MouseInteraction _interactionMode; + glm::vec2 _mousePosition; // Current mouse position in screen space coordinates + glm::vec2 _startMousePosition; + glm::vec2 _startDragPosition; + glm::dvec3 _startTargetPosition; + + // Animation of rotation of camera to look at coordinate galactic coordinates + skybrowser::Animation _cameraRotation = + skybrowser::Animation(glm::dvec3(0.0), glm::dvec3(0.0), 0.0); + + // Data handler for the image collections + std::unique_ptr _dataHandler; +}; +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SKYBROWSER___SKYBROWSERMODULE___H__ diff --git a/modules/skybrowser/skybrowsermodule_lua.inl b/modules/skybrowser/skybrowsermodule_lua.inl new file mode 100644 index 0000000000..03d08c7e2e --- /dev/null +++ b/modules/skybrowser/skybrowsermodule_lua.inl @@ -0,0 +1,690 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + constexpr const char _loggerCat[] = "SkyBrowserModule"; + + using namespace openspace; + +/** +* Takes an index to an image and selects that image in the currently +* selected sky browser. +* \param i Index of image +*/ +[[codegen::luawrap]] void selectImage(int i) { + // Load image + SkyBrowserModule* module = global::moduleEngine->module(); + + if (module->isCameraInSolarSystem()) { + TargetBrowserPair* selected = module->getPair(module->selectedBrowserId()); + if (selected) { + const ImageData& image = module->getWwtDataHandler()->getImage(i); + // Load image into browser + std::string str = image.name; + str.erase(std::remove_if(str.begin(), str.end(), [](char c) { + // Check if character is ASCII - if it isn't, remove + return !(c >= 0 && c < 128); + }), + str.end()); + LINFO("Loading image " + str); + selected->selectImage(image, i); + + bool isInView = skybrowser::isCoordinateInView(image.equatorialCartesian); + // If the coordinate is not in view, rotate camera + if (image.hasCelestialCoords && !isInView) { + module->startRotatingCamera( + skybrowser::equatorialToGalactic( + image.equatorialCartesian * skybrowser::CelestialSphereRadius + ) + ); + } + } + } +} +/** +* Takes an identifier to a screen space renderable and adds it to the module. +* \param id Identifier +*/ +[[codegen::luawrap]] void setHoverCircle(std::string id) { + SkyBrowserModule* module = global::moduleEngine->module(); + + SceneGraphNode* circle = global::renderEngine->scene()->sceneGraphNode(id); + module->setHoverCircle(circle); +} +/** +* Moves the hover circle to the coordinate specified by the image index. +* \param i Index of image +*/ +[[codegen::luawrap]] void moveCircleToHoverImage(int i) { + // Load image + SkyBrowserModule* module = global::moduleEngine->module(); + module->moveHoverCircle(i); +} +/** +* Disables the hover circle, if there is one added to the sky browser +* module. +*/ +[[codegen::luawrap]] void disableHoverCircle() { + SkyBrowserModule* module = global::moduleEngine->module(); + module->disableHoverCircle(); +} +/** +* Takes an identifier to a sky browser or a sky target, an image index +* and the order which it should have in the selected image list. The +* image is then changed to have this order. +* \param id Identifier +* \param i Image index +* \param order Order of image +*/ +[[codegen::luawrap]] void setImageLayerOrder(std::string id, int i, int order) { + + SkyBrowserModule* module = global::moduleEngine->module(); + + if (module->getPair(id)) { + module->getPair(id)->setImageOrder(i, order); + } +} +/** +* Takes an identifier to a sky browser or target and loads the WWT image +* collection to that browser. +* \param id Identifier +*/ +[[codegen::luawrap]] void loadImagesToWWT(std::string id) { + // Load images from url + LINFO("Connection established to WorldWide Telescope application in " + id); + LINFO("Loading image collections to " + id); + + // Load the collections here because here we know that the browser can execute + // javascript + std::string root = "https://raw.githubusercontent.com/WorldWideTelescope/" + "wwt-web-client/master/assets/webclient-explore-root.wtml"; + + SkyBrowserModule* module = global::moduleEngine->module(); + + if (module->getPair(id)) { + module->getPair(id)->hideChromeInterface(true); + module->getPair(id)->loadImageCollection(root); + } +} +/** +* Starts the setup process of the sky browers. This function calls +* the lua function 'sendOutIdsToBrowsers' in all nodes in the cluster. +*/ +[[codegen::luawrap]] void startSetup() { + // This is called when the sky_browser website is connected to OpenSpace + // Set all border colors to the border color in the master node + if (global::windowDelegate->isMaster()) { + SkyBrowserModule* module = global::moduleEngine->module(); + std::vector>& pairs = module->getPairs(); + for (std::unique_ptr& pair : pairs) { + std::string id = pair->browserId(); + glm::ivec3 color = pair->borderColor(); + std::string script = fmt::format( + "openspace.skybrowser.setBorderColor('{}', {}, {}, {})", + id, + color.r, + color.g, + color.b + ); + global::scriptEngine->queueScript( + script, + scripting::ScriptEngine::RemoteScripting::Yes + ); + } + } + + // To ensure each node in a cluster calls its own instance of the wwt application + // Do not send this script to the other nodes + global::scriptEngine->queueScript( + "openspace.skybrowser.sendOutIdsToBrowsers();", + scripting::ScriptEngine::RemoteScripting::No + ); +} +/** +* Sends all sky browsers' identifiers to their respective CEF browser. +*/ +[[codegen::luawrap]] void sendOutIdsToBrowsers() { + // This is called when the sky_browser website is connected to OpenSpace + // Send out identifiers to the browsers + SkyBrowserModule* module = global::moduleEngine->module(); + std::vector>& pairs = module->getPairs(); + for (std::unique_ptr& pair : pairs) { + pair->sendIdToBrowser(); + } +} +/** +* Takes an identifier to a sky browser and starts the initialization +* for that browser. That means that the browser starts to try to connect +* to the AAS WorldWide Telescope application by sending it messages. And +* that the target matches its appearance to its corresponding browser. +* \param id Identifier +*/ +[[codegen::luawrap]] void initializeBrowser(std::string id) { + // Initialize browser with ID and its corresponding target + LINFO("Initializing sky browser " + id); + SkyBrowserModule* module = global::moduleEngine->module(); + TargetBrowserPair* found = module->getPair(id); + if (found) { + found->setIsSyncedWithWwt(true); + found->initialize(); + } +} +/** +* Takes the identifier of the sky target and a sky browser and adds them +* to the sky browser module. +* \param targetId Identifier of target (either SceneGraphNode or Renderable) +* \param browserId Identifier of browser +*/ +[[codegen::luawrap]] void addPairToSkyBrowserModule(std::string targetId, std::string browserId) { + SkyBrowserModule* module = global::moduleEngine->module(); + + LINFO("Add browser " + browserId + " to sky browser module"); + LINFO("Add target " + targetId + " to sky browser module"); + + module->addTargetBrowserPair(targetId, browserId); +} +/** +* Returns a list of all the loaded AAS WorldWide Telescope images that +* have been loaded. Each image has a name, thumbnail url, equatorial +* spherical coordinates RA and Dec, equatorial Cartesian coordinates, +* if the image has celestial coordinates, credits text, credits url +* and the identifier of the image which is a unique number. +*/ + +[[codegen::luawrap]] ghoul::Dictionary getListOfImages() { + // Send image list to GUI + SkyBrowserModule* module = global::moduleEngine->module(); + + // If no data has been loaded yet, download the data from the web! + if (module->nLoadedImages() == 0) { + std::string root = "https://raw.githubusercontent.com/WorldWideTelescope/" + "wwt-web-client/master/assets/webclient-explore-root.wtml"; + + std::filesystem::path directory = absPath("${MODULE_SKYBROWSER}/wwtimagedata/"); + + module->loadImages(root, directory); + } + + // Create Lua table to send to the GUI + ghoul::Dictionary list; + + for (int i = 0; i < module->nLoadedImages(); i++) { + const ImageData& img = module->getWwtDataHandler()->getImage(i); + using namespace std::string_literals; + + // Push ("Key", value) + ghoul::Dictionary image; + image.setValue("name", img.name); + image.setValue("thumbnail", img.thumbnailUrl); + image.setValue("url", img.imageUrl); + image.setValue("ra", img.equatorialSpherical.x); + image.setValue("dec", img.equatorialSpherical.y); + image.setValue("fov", static_cast(img.fov)); + image.setValue("cartesianDirection", img.equatorialCartesian); + image.setValue("hasCelestialCoords", img.hasCelestialCoords); + image.setValue("credits", img.credits); + image.setValue("creditsUrl", img.creditsUrl); + image.setValue("identifier", std::to_string(i)); + + // Index for current ImageData + // Set table for the current ImageData + list.setValue(std::to_string(i + 1), image); + } + + return list; +} +/** +* Returns a table of data regarding the current view and the sky browsers +* and targets. +* \return Dictionary of data regarding the current targets +*/ +[[codegen::luawrap]] ghoul::Dictionary getTargetData() { + using namespace std::string_literals; + SkyBrowserModule* module = global::moduleEngine->module(); + ghoul::Dictionary data; + + // The current viewport data for OpenSpace + ghoul::Dictionary openSpace; + + // Camera directions + glm::dvec3 cartesianCam = skybrowser::cameraDirectionEquatorial(); + glm::dvec2 sphericalCam = skybrowser::cartesianToSpherical(cartesianCam); + + // Calculate the smallest FOV of vertical and horizontal + glm::dvec2 fovs = skybrowser::fovWindow(); + double FOV = std::min(fovs.x, fovs.y); + + // Set window data + openSpace.setValue("windowHFOV", FOV); + openSpace.setValue("cartesianDirection", cartesianCam); + openSpace.setValue("ra", sphericalCam.x); + openSpace.setValue("dec", sphericalCam.y); + openSpace.setValue("selectedBrowserId", module->selectedBrowserId()); + openSpace.setValue("selectedTargetId", module->selectedTargetId()); + openSpace.setValue("isFacingCamera", module->isSelectedPairFacingCamera()); + openSpace.setValue("isUsingRadiusAzimuthElevation", module->isSelectedPairUsingRae()); + openSpace.setValue("cameraInSolarSystem", module->isCameraInSolarSystem()); + // Set table for the current ImageData + data.setValue("OpenSpace", openSpace); + + // Pass data for all the browsers and the corresponding targets + if (module->isCameraInSolarSystem()) { + std::vector>& pairs = module->getPairs(); + + for (std::unique_ptr& pair : pairs) { + std::string id = pair->browserId(); + // Convert deque to vector so ghoul can read it + std::vector selectedImagesVector; + const std::deque selectedImages = pair->selectedImages(); + std::for_each( + selectedImages.begin(), + selectedImages.end(), + [&](int i) { + selectedImagesVector.push_back(i); + } + ); + + glm::dvec2 spherical = pair->targetDirectionEquatorial(); + glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical); + + ghoul::Dictionary target; + // Set ("Key", value) + target.setValue("id", id); + target.setValue("name", pair->browserGuiName()); + target.setValue("FOV", static_cast(pair->verticalFov())); + target.setValue("selectedImages", selectedImagesVector); + target.setValue("cartesianDirection", cartesian); + target.setValue("ra", spherical.x); + target.setValue("dec", spherical.y); + target.setValue("roll", pair->targetRoll()); + target.setValue("color", pair->borderColor()); + target.setValue("size", glm::dvec2(pair->size())); + std::vector> copies = pair->renderCopies(); + ghoul::Dictionary copiesData; + for (int i = 0; i < copies.size(); i++) { + copiesData.setValue(copies[i].first, copies[i].second); + } + // Set table for the current target + target.setValue("renderCopies", copiesData); + data.setValue(id, target); + } + } + + return data; +} +/** +* Takes an identifier to a sky browser or sky target. Rotates the camera +* so that the target is placed in the center of the view. +* \param id +*/ +[[codegen::luawrap]] void adjustCamera(std::string id) { + SkyBrowserModule* module = global::moduleEngine->module(); + + if (module->isCameraInSolarSystem()) { + module->lookAtTarget(id); + } +} +/** +* Takes an identifier to a sky browser or sky target, an index to an image +* and a value for the opacity. +* \param id Identifier +* \param i Image index +* \param opacity +*/ +[[codegen::luawrap]] void setOpacityOfImageLayer(std::string id, int i, double opacity) { + SkyBrowserModule* module = global::moduleEngine->module(); + TargetBrowserPair* found = module->getPair(id); + if (found) { + found->setImageOpacity(i, opacity); + } +} +/** +* Takes an identifier to a sky browser and animates its corresponding +* target to the center of the current view. +* \param id Identifier +*/ +[[codegen::luawrap]] void centerTargetOnScreen(std::string id) { + SkyBrowserModule* module = global::moduleEngine->module(); + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->centerTargetOnScreen(); + } +} +/** +* Takes an identifier to a sky browser or target. Sets that sky browser +* currently selected. +* \param id +*/ +[[codegen::luawrap]] void setSelectedBrowser(std::string id) { + SkyBrowserModule* module = global::moduleEngine->module(); + module->setSelectedBrowser(id); +} +/** +* Creates a sky browser and a target. +*/ +[[codegen::luawrap]] void createTargetBrowserPair() { + SkyBrowserModule* module = global::moduleEngine->module(); + + int noOfPairs = module->nPairs(); + std::string nameBrowser = "Sky Browser " + std::to_string(noOfPairs); + std::string nameTarget = "Sky Target " + std::to_string(noOfPairs); + std::string idBrowser = "SkyBrowser" + std::to_string(noOfPairs); + std::string idTarget = "SkyTarget" + std::to_string(noOfPairs); + // Determine starting point on screen for the target + glm::vec3 positionBrowser = { -3.f, -3.f, -2.1f }; + glm::vec3 positionTarget = { 0.9f, 0.4f, -2.1f }; + glm::dvec3 galacticTarget = skybrowser::localCameraToGalactic(positionTarget); + std::string guiPath = "/Sky Browser"; + std::string url = "https://data.openspaceproject.com/dist/skybrowser/page/"; + double fov = 70.0; + double size = skybrowser::sizeFromFov(fov, galacticTarget); + + const std::string browser = "{" + "Identifier = '" + idBrowser + "'," + "Type = 'ScreenSpaceSkyBrowser'," + "Name = '" + nameBrowser + "'," + "Url = '" + url + "'," + "FaceCamera = false," + "CartesianPosition = " + ghoul::to_string(positionBrowser) + + "}"; + + const std::string target = "{" + "Identifier = '" + idTarget + "'," + "Type = 'SkyTarget'," + "Name = '" + nameTarget + "'," + "Transform = {" + "Translation = {" + "Type = 'StaticTranslation'," + "Position = {" + + std::to_string(galacticTarget.x) + ", " + + std::to_string(galacticTarget.y) + ", " + + std::to_string(galacticTarget.z) + ", " + "}," + "}," + "Rotation = {" + "Type = 'StaticRotation'," + "Rotation = {0.0, 0.0, 0.0}" + "}" + "}," + "Renderable = {" + "Identifier = 'RenderableSkyTarget'," + "Type = 'RenderableSkyTarget'," + "Size = " + std::to_string(size) + "," + "VerticalFieldOfView = " + std::to_string(fov) + "," + "Origin = 'Center'," + "Billboard = true," + "Opacity = 0.99" + "}," + "GUI = {" + "Name = 'Sky Target', " + "Path = '/SkyBrowser', " + "}" + "}"; + + global::scriptEngine->queueScript( + "openspace.addScreenSpaceRenderable(" + browser + ");", + scripting::ScriptEngine::RemoteScripting::No + ); + + global::scriptEngine->queueScript( + "openspace.addSceneGraphNode(" + target + ");", + scripting::ScriptEngine::RemoteScripting::No + ); + + global::scriptEngine->queueScript( + "openspace.skybrowser.addPairToSkyBrowserModule('" + idTarget + "','" + + idBrowser + "');", + scripting::ScriptEngine::RemoteScripting::No + ); + + global::scriptEngine->queueScript( + "openspace.skybrowser.setSelectedBrowser('" + idBrowser + "');", + scripting::ScriptEngine::RemoteScripting::No + ); +} +/** +* Takes in identifier to a sky browser or target and removes them. +* \param id Identifier +*/ +[[codegen::luawrap]] void removeTargetBrowserPair(std::string id) { + SkyBrowserModule* module = global::moduleEngine->module(); + TargetBrowserPair* found = module->getPair(id); + if (found) { + std::string browser = found->browserId(); + std::string target = found->targetNodeId(); + + module->removeTargetBrowserPair(id); + + // Remove from engine + global::scriptEngine->queueScript( + "openspace.removeScreenSpaceRenderable('" + browser + "');", + scripting::ScriptEngine::RemoteScripting::Yes + ); + + global::scriptEngine->queueScript( + "openspace.removeSceneGraphNode('" + target + "');", + scripting::ScriptEngine::RemoteScripting::Yes + ); + } +} +/** +* Takes an identifier to a sky browser or sky target and the [x, y] +* starting position and the [x, y] translation vector. +* \param id Identifier +* \param startX Starting x-position +* \param startY Starting y-position +* \param transX Translation x-value +* \param transY Translation y-value +*/ +[[codegen::luawrap]] void translateScreenSpaceRenderable(std::string id, float startX, + float startY, float transX, + float transY) { + ScreenSpaceRenderable* renderable = global::renderEngine->screenSpaceRenderable(id); + + if (renderable) { + renderable->translate(glm::vec2(transX, transY), glm::vec2(startX, startY)); + } +} +/** +* Takes an identifier to a sky browser or target and an index to an +* image. Removes that image from that sky browser. +* \param id Identifier +* \i Index of image +*/ +[[codegen::luawrap]] void removeSelectedImageInBrowser(std::string id, int i) { + // Get browser + SkyBrowserModule* module = global::moduleEngine->module(); + const ImageData& image = module->getWwtDataHandler()->getImage(i); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->removeSelectedImage(i); + } +} +/** +* Takes the identifier of a sky browser or a sky target and equatorial +* coordinates Right Ascension and Declination. The target will animate to +* this coordinate and the browser will display the coordinate. +* \param id Identifier +* \param ra Right Ascension +* \param dec Declination +*/ +[[codegen::luawrap]] void setEquatorialAim(std::string id, double ra, double dec) { + // Get module + SkyBrowserModule* module = global::moduleEngine->module(); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->setEquatorialAim(glm::dvec2(ra, dec)); + } +} +/** +* Takes an identifier to a sky browser or a sky target and a vertical +* field of view. Changes the field of view as specified by the input. +* \param id Identifier +* \param vfov Vertical Field of View +*/ +[[codegen::luawrap]] void setVerticalFov(std::string id, float vfov) { + // Get module + SkyBrowserModule* module = global::moduleEngine->module(); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->setVerticalFov(vfov); + } +} + +/** +* Takes an identifier to a sky browser or a sky target and a vertical +* field of view. Changes the field of view as specified by the input. +* \param id Identifier +* \param vfov Vertical Field of View +*/ +[[codegen::luawrap]] void scrollOverBrowser(std::string id, float scroll) { + // Get module + SkyBrowserModule* module = global::moduleEngine->module(); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->setVerticalFovWithScroll(scroll); + } +} +/** +* Takes an identifier to a sky browser or a sky target and a rgb color +* in the ranges [0, 255]. +* \param id Identifier +* \param r Red +* \param g Green +* \param b Blue +*/ +[[codegen::luawrap]] void setBorderColor(std::string id, int r, int g, int b) { + glm::ivec3 color{ r, g, b }; + // Get module + SkyBrowserModule* module = global::moduleEngine->module(); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->setBorderColor(color); + } +} +/** +* Sets the screen space size of the sky browser to the numbers specified +* by the input [x, y]. +* \param id +* \param sizeX Size on the x-axis +* \param sizeY Size on the y-axis +*/ +[[codegen::luawrap]] void setScreenSpaceSize(std::string id, float sizeX, float sizeY) { + // Get module + SkyBrowserModule* module = global::moduleEngine->module(); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->setScreenSpaceSize(glm::vec2(sizeX, sizeY)); + } +} +/** +* Takes an identifier to a sky browser and adds a rendered copy to it. +* \param id Identifier +* \param raePosition Position in radius, azimuth, elevation coordinates +* \param nCopies Number of copies +*/ +[[codegen::luawrap]] void addRenderCopy(std::string id, + int nCopies = 1, glm::vec3 raePosition = glm::vec3(2.1f, 0.f, 0.f)) { + // Get module + SkyBrowserModule* module = global::moduleEngine->module(); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->browser()->addRenderCopy(raePosition, nCopies); + } +} +/** +* Takes an identifier to a sky browser and removes the latest added +* rendered copy to it. +* \param id Identifier +*/ +[[codegen::luawrap]] void removeRenderCopy(std::string id) { + // Get module + SkyBrowserModule* module = global::moduleEngine->module(); + + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->browser()->removeRenderCopy(); + } +} + +/** +* Starts the finetuning of the target +* rendered copy to it. +* \param id Identifier to browser +*/ +[[codegen::luawrap]] void startFinetuningTarget(std::string id) { + // Get module + + SkyBrowserModule* module = global::moduleEngine->module(); + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + pair->startFinetuningTarget(); + } +} + +/** +* Finetunes the target depending on a mouse drag. +* rendered copy to it. +* \param id Identifier to browser +* \param start Start pixel position of drag +* \param end Current pixel position of mouse during drag +*/ +[[codegen::luawrap]] void finetuneTargetPosition(std::string id, glm::vec2 start, + glm::vec2 end) { + // Get module + + SkyBrowserModule* module = global::moduleEngine->module(); + TargetBrowserPair* pair = module->getPair(id); + if (pair) { + glm::vec2 startScreenSpace = skybrowser::pixelToScreenSpace2d(start); + glm::vec2 endScreenSpace = skybrowser::pixelToScreenSpace2d(end); + glm::vec2 translation = endScreenSpace - startScreenSpace; + pair->fineTuneTarget(startScreenSpace, translation); + } +} + +#include "skybrowsermodule_lua_codegen.cpp" + +} // namespace + diff --git a/modules/skybrowser/src/browser.cpp b/modules/skybrowser/src/browser.cpp new file mode 100644 index 0000000000..615f558ff4 --- /dev/null +++ b/modules/skybrowser/src/browser.cpp @@ -0,0 +1,219 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + constexpr const char* _loggerCat = "Browser"; + + const openspace::properties::Property::PropertyInfo DimensionsInfo = { + "Dimensions", + "Browser Dimensions", + "Set the dimensions of the web browser window." + }; + + const openspace::properties::Property::PropertyInfo UrlInfo = { + "Url", + "URL", + "The URL to load" + }; + + const openspace::properties::Property::PropertyInfo ReloadInfo = { + "Reload", + "Reload", + "Reload the web browser" + }; + + struct [[codegen::Dictionary(Browser)]] Parameters { + // [[codegen::verbatim(DimensionsInfo.description)]] + std::optional dimensions; + + // [[codegen::verbatim(UrlInfo.description)]] + std::optional url; + + // [[codegen::verbatim(ReloadInfo.description)]] + std::optional reload; + }; + +#include "browser_codegen.cpp" + +} // namespace + +namespace openspace { + +void Browser::RenderHandler::draw() {} + +void Browser::RenderHandler::render() {} + +void Browser::RenderHandler::setTexture(GLuint t) { + _texture = t; +} + +Browser::Browser(const ghoul::Dictionary& dictionary) + : _url(UrlInfo) + , _browserPixeldimensions(DimensionsInfo, glm::vec2(500.f), glm::vec2(10.f), glm::vec2(3000.f)) + , _reload(ReloadInfo) +{ + if (dictionary.hasValue(UrlInfo.identifier)) { + _url = dictionary.value(UrlInfo.identifier); + } + // Handle target dimension property + const Parameters p = codegen::bake(dictionary); + _url = p.url.value_or(_url); + _browserPixeldimensions = p.dimensions.value_or(_browserPixeldimensions); + + glm::vec2 windowDimensions = global::windowDelegate->currentSubwindowSize(); + _browserPixeldimensions = windowDimensions; + + _url.onChange([this]() { _isUrlDirty = true; }); + _browserPixeldimensions.onChange([this]() { _isDimensionsDirty = true; }); + _reload.onChange([this]() { _shouldReload = true; }); + + // Create browser and render handler + _renderHandler = new RenderHandler(); + _keyboardHandler = new WebKeyboardHandler(); + _browserInstance = std::make_unique( + _renderHandler.get(), + _keyboardHandler.get() + ); + + WebBrowserModule* webBrowser = global::moduleEngine->module(); + if (webBrowser) { + webBrowser->addBrowser(_browserInstance.get()); + } +} + +Browser::~Browser() {} + +bool Browser::initializeGL() { + _texture = std::make_unique( + glm::uvec3(glm::ivec2(_browserPixeldimensions.value()), 1), + GL_TEXTURE_2D + ); + + _renderHandler->setTexture(*_texture); + + _browserInstance->initialize(); + _browserInstance->loadUrl(_url); + return isReady(); +} + +bool Browser::deinitializeGL() { + _renderHandler->setTexture(0); + + _texture = nullptr; + + LDEBUG(fmt::format("Deinitializing browser: {}", _url.value())); + + _browserInstance->close(true); + + WebBrowserModule* webBrowser = global::moduleEngine->module(); + if (webBrowser) { + webBrowser->removeBrowser(_browserInstance.get()); + _browserInstance.reset(); + } + else { + LWARNING("Could not find WebBrowserModule"); + } + + return true; +} + +void Browser::render() { + if (!_renderHandler->isTextureReady()) { + return; + } + _renderHandler->updateTexture(); +} + +void Browser::update() { + if (_isUrlDirty) { + _browserInstance->loadUrl(_url); + _isUrlDirty = false; + } + if (_isDimensionsDirty) { + if (_browserPixeldimensions.value().x > 0 && + _browserPixeldimensions.value().y > 0) + { + _browserInstance->reshape(_browserPixeldimensions.value()); + _isDimensionsDirty = false; + } + } + + if (_shouldReload) { + _browserInstance->reloadBrowser(); + _shouldReload = false; + } +} + +bool Browser::isReady() const { + return _texture.get(); +} + +glm::vec2 Browser::browserPixelDimensions() const { + return _browserPixeldimensions.value(); +} + +// Updates the browser size to match the size of the texture +void Browser::updateBrowserSize() { + _browserPixeldimensions = _texture->dimensions(); +} + +float Browser::browserRatio() const { + return static_cast(_texture->dimensions().x) / + static_cast(_texture->dimensions().y); +} + +void Browser::setCallbackDimensions( + const std::function& function) +{ + _browserPixeldimensions.onChange([&]() { + function(_browserPixeldimensions.value()); + }); +} + +void Browser::executeJavascript(const std::string& script) const { + // Make sure that the browser has a main frame + const bool browserExists = _browserInstance && _browserInstance->getBrowser(); + const bool frameIsLoaded = browserExists && + _browserInstance->getBrowser()->GetMainFrame(); + + if (frameIsLoaded) { + _browserInstance->getBrowser()->GetMainFrame()->ExecuteJavaScript( + script, + _browserInstance->getBrowser()->GetMainFrame()->GetURL(), + 0 + ); + } +} +} // namespace openspace diff --git a/modules/skybrowser/src/renderableskytarget.cpp b/modules/skybrowser/src/renderableskytarget.cpp new file mode 100644 index 0000000000..86570065c4 --- /dev/null +++ b/modules/skybrowser/src/renderableskytarget.cpp @@ -0,0 +1,277 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma optimize("", off) +namespace { + constexpr const char* _loggerCat = "RenderableSkyTarget"; + + enum BlendMode { + Normal = 0, + Additive + }; + + constexpr const openspace::properties::Property::PropertyInfo crossHairSizeInfo = + { + "CrosshairSize", + "Crosshair Size", + "Determines the size of the crosshair. The size is determined in fov (degrees). " + }; + + constexpr const openspace::properties::Property::PropertyInfo RectangleThresholdInfo = + { + "RectangleThreshold", + "Rectangle Threshold", + "When the field of view is larger than the rectangle threshold, a rectangle will" + "be rendered in the target." + }; + + constexpr const openspace::properties::Property::PropertyInfo AnimationSpeedInfo = { + "AnimationSpeed", + "Animation Speed", + "The factor which is multiplied with the animation speed of the target." + }; + + constexpr const openspace::properties::Property::PropertyInfo AnimationThresholdInfo = + { + "AnimationThreshold", + "Animation Threshold", + "The threshold for when the target is determined to have appeared at its " + "destination. Angle in radians between the destination and the target position " + "in equatorial Cartesian coordinate system." + }; + + constexpr const openspace::properties::Property::PropertyInfo LineWidthInfo = { + "LineWidth", + "Line Width", + "The thickness of the line of the target. The larger number, the thicker line." + }; + + struct [[codegen::Dictionary(RenderableSkyTarget)]] Parameters { + // [[codegen::verbatim(crossHairSizeInfo.description)]] + std::optional crossHairSize; + + // [[codegen::verbatim(RectangleThresholdInfo.description)]] + std::optional rectangleThreshold; + + // [[codegen::verbatim(AnimationSpeedInfo.description)]] + std::optional animationSpeed; + + // [[codegen::verbatim(AnimationThresholdInfo.description)]] + std::optional animationThreshold; + + // [[codegen::verbatim(LineWidthInfo.description)]] + std::optional lineWidth; + }; + +#include "renderableskytarget_codegen.cpp" +} //namespace + +namespace openspace { + RenderableSkyTarget::RenderableSkyTarget(const ghoul::Dictionary& dictionary) + : RenderablePlane(dictionary) + , _crossHairSize(crossHairSizeInfo, 2.f, 1.f, 10.f) + , _showRectangleThreshold(RectangleThresholdInfo, 5.f, 0.1f, 70.f) + , _stopAnimationThreshold(AnimationThresholdInfo, 5.0f, 1.f, 10.f) + , _animationSpeed(AnimationSpeedInfo, 5.0, 0.1, 10.0) + , _lineWidth(LineWidthInfo, 13.f, 1.f, 100.f) + , _borderColor(220, 220, 220) + { + // Handle target dimension property + const Parameters p = codegen::bake(dictionary); + _crossHairSize = p.crossHairSize.value_or(_crossHairSize); + _showRectangleThreshold = p.rectangleThreshold.value_or(_showRectangleThreshold); + _stopAnimationThreshold = p.crossHairSize.value_or(_stopAnimationThreshold); + _animationSpeed = p.animationSpeed.value_or(_animationSpeed); + + addProperty(_crossHairSize); + addProperty(_showRectangleThreshold); + addProperty(_stopAnimationThreshold); + addProperty(_animationSpeed); + addProperty(_lineWidth); +} + +void RenderableSkyTarget::bindTexture() {} + +void RenderableSkyTarget::initializeGL() { + glGenVertexArrays(1, &_quad); // generate array + glGenBuffers(1, &_vertexPositionBuffer); // generate buffer + createPlane(); + + std::string ProgramName = identifier() + "Shader"; + + _shader = BaseModule::ProgramObjectManager.request( + ProgramName, + [&]() -> std::unique_ptr { + return global::renderEngine->buildRenderProgram( + ProgramName, + absPath("${MODULE_SKYBROWSER}/shaders/target_vs.glsl"), + absPath("${MODULE_SKYBROWSER}/shaders/target_fs.glsl") + ); + } + ); +} + +void RenderableSkyTarget::deinitializeGL() { + RenderablePlane::deinitializeGL(); +} + +void RenderableSkyTarget::setColor(glm::ivec3 color) { + _borderColor = std::move(color); +} + +glm::ivec3 RenderableSkyTarget::borderColor() const { + return _borderColor; +} + + +void RenderableSkyTarget::render(const RenderData& data, RendererTasks&) { + ZoneScoped + bool showRectangle = _verticalFov > _showRectangleThreshold; + + glm::vec4 color = { glm::vec3(_borderColor) / 255.f, _opacity.value() }; + + _shader->activate(); + _shader->setUniform("opacity", _opacity); + + _shader->setUniform("crossHairSize", _crossHairSize); + _shader->setUniform("showRectangle", showRectangle); + _shader->setUniform("lineWidth", _lineWidth * 0.0001f); + _shader->setUniform("dimensions", _dimensions); + _shader->setUniform("lineColor", color); + _shader->setUniform("fov", static_cast(_verticalFov)); + + glm::dvec3 objectPositionWorld = glm::dvec3( + glm::translate( + glm::dmat4(1.0), + data.modelTransform.translation) * glm::dvec4(0.0, 0.0, 0.0, 1.0) + ); + + glm::dvec3 normal = glm::normalize(data.camera.positionVec3() - objectPositionWorld); + glm::dvec3 newRight = glm::normalize( + glm::cross(data.camera.lookUpVectorWorldSpace(), normal) + ); + glm::dvec3 newUp = glm::cross(normal, newRight); + + glm::dmat4 cameraOrientedRotation = glm::dmat4(1.0); + cameraOrientedRotation[0] = glm::dvec4(newRight, 0.0); + cameraOrientedRotation[1] = glm::dvec4(newUp, 0.0); + cameraOrientedRotation[2] = glm::dvec4(normal, 0.0); + + const glm::dmat4 rotationTransform = _billboard ? + cameraOrientedRotation : + glm::dmat4(data.modelTransform.rotation); + + const glm::dmat4 modelTransform = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + rotationTransform * + glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) * + glm::dmat4(1.0); + const glm::dmat4 modelViewTransform = + data.camera.combinedViewMatrix() * modelTransform; + + _shader->setUniform("modelViewProjectionTransform", + data.camera.projectionMatrix() * glm::mat4(modelViewTransform)); + + _shader->setUniform("modelViewTransform", + glm::mat4(data.camera.combinedViewMatrix() * glm::dmat4(modelViewTransform))); + + _shader->setUniform("multiplyColor", _multiplyColor); + + bool additiveBlending = (_blendMode == static_cast(BlendMode::Additive)); + if (additiveBlending) { + glDepthMask(false); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + } + + glBindVertexArray(_quad); + glEnable(GL_LINE_SMOOTH); + glDrawArrays(GL_TRIANGLES, 0, 6); + glDisable(GL_LINE_SMOOTH); + glBindVertexArray(0); + + if (additiveBlending) { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDepthMask(true); + } + + _shader->deactivate(); +} + +void RenderableSkyTarget::update(const UpdateData& data) { + RenderablePlane::update(data); + +} + +void RenderableSkyTarget::setDimensions(glm::vec2 dimensions) { + // To avoid flooring of the size of the target, multiply by factor of 100 + // Object size is really the pixel size so this calculation is not exact + _dimensions = glm::ivec2(dimensions * 100.f); +} + +void RenderableSkyTarget::highlight(const glm::ivec3& addition) { + _borderColor += addition; +} + +void RenderableSkyTarget::removeHighlight(const glm::ivec3& removal) { + _borderColor -= removal; +} + +float RenderableSkyTarget::opacity() const { + return _opacity; +} + +double RenderableSkyTarget::animationSpeed() const { + return _animationSpeed; +} + +double RenderableSkyTarget::stopAnimationThreshold() const { + return _stopAnimationThreshold * 0.0001; +} + +void RenderableSkyTarget::setOpacity(float opacity) { + _opacity = opacity; +} + +void RenderableSkyTarget::setVerticalFov(double fov) { + _verticalFov = fov; +} +} // namespace openspace diff --git a/modules/skybrowser/src/screenspaceskybrowser.cpp b/modules/skybrowser/src/screenspaceskybrowser.cpp new file mode 100644 index 0000000000..488d2cf8a3 --- /dev/null +++ b/modules/skybrowser/src/screenspaceskybrowser.cpp @@ -0,0 +1,338 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + constexpr const char* _loggerCat = "ScreenSpaceSkyBrowser"; + + constexpr const openspace::properties::Property::PropertyInfo TextureQualityInfo = { + "TextureQuality", + "Quality of Texture", + "A parameter to set the resolution of the texture. 1 is full resolution and " + "slower frame rate. Lower value means lower resolution of texture and faster " + "frame rate." + }; + + constexpr const openspace::properties::Property::PropertyInfo RenderCopyInfo = { + "RenderCopy", + "RAE Position Of A Copy Of The Sky Browser", + "Render a copy of this sky browser at an additional position. This copy will not " + "be interactive. The position is in RAE (Radius, Azimuth, Elevation) coordinates." + }; + + constexpr const openspace::properties::Property::PropertyInfo RenderOnMasterInfo = { + "RenderOnlyOnMaster", + "Render Only On Master", + "Render the interactive sky browser only on the master node (this setting won't " + "affect the copies). This setting allows mouse interactions in a dome environment." + }; + + struct [[codegen::Dictionary(ScreenSpaceSkyBrowser)]] Parameters { + // [[codegen::verbatim(TextureQualityInfo.description)]] + std::optional textureQuality; + + // [[codegen::verbatim(RenderOnMasterInfo.description)]] + std::optional renderOnlyOnMaster; + }; + +#include "screenspaceskybrowser_codegen.cpp" +} // namespace + +glm::ivec3 randomBorderColor(glm::ivec3 highlight) { + // Generate a random border color with sufficient lightness and a n + std::random_device rd; + // Hue is in the unit degrees [0, 360] + std::uniform_real_distribution hue(0.f, 360.f); + + // Value in saturation are in the unit percent [0,1] + float value = 0.9f; // Brightness + float saturation = 0.5f; + glm::ivec3 rgbColor; + glm::ivec3 highlighted; + do { + glm::vec3 hsvColor = glm::vec3(hue(rd), saturation, value); + rgbColor = glm::ivec3(glm::rgbColor(hsvColor) * 255.f); + highlighted = rgbColor + highlight; + } while (highlighted.x < 255 && highlighted.y < 255 && highlighted.z < 255); + + return rgbColor; +} + +namespace openspace { + + ScreenSpaceSkyBrowser::ScreenSpaceSkyBrowser(const ghoul::Dictionary& dictionary) + : ScreenSpaceRenderable(dictionary) + , WwtCommunicator(dictionary) + , _textureQuality(TextureQualityInfo, 0.5f, 0.25f, 1.f) + , _renderOnlyOnMaster(RenderOnMasterInfo, false) +{ + _identifier = makeUniqueIdentifier(_identifier); + + // Handle target dimension property + const Parameters p = codegen::bake(dictionary); + _textureQuality = p.textureQuality.value_or(_textureQuality); + _renderOnlyOnMaster = p.renderOnlyOnMaster.value_or(_renderOnlyOnMaster); + + addProperty(_url); + addProperty(_browserPixeldimensions); + addProperty(_reload); + addProperty(_textureQuality); + addProperty(_renderOnlyOnMaster); + + _textureQuality.onChange([this]() { + _textureDimensionsIsDirty = true; + }); + + // Ensure that the browser is placed at the z-coordinate of the screen space plane + glm::vec2 screenPosition = _cartesianPosition.value(); + _cartesianPosition = glm::vec3(screenPosition, skybrowser::ScreenSpaceZ); + + if (global::windowDelegate->isMaster()) { + SkyBrowserModule* module = global::moduleEngine->module(); + _borderColor = randomBorderColor(module->highlight()); + } + _scale = _size.y * 0.5; +} + +ScreenSpaceSkyBrowser::~ScreenSpaceSkyBrowser() { + SkyBrowserModule* module = global::moduleEngine->module(); + + if (module && module->getPair(identifier())) { + module->removeTargetBrowserPair(identifier()); + } +} + +bool ScreenSpaceSkyBrowser::initializeGL() { + WwtCommunicator::initializeGL(); + ScreenSpaceRenderable::initializeGL(); + updateTextureResolution(); + return true; +} + +glm::dvec2 ScreenSpaceSkyBrowser::fineTuneVector(glm::dvec2 drag) { + // Fine tuning of target + glm::dvec2 wwtFov = fieldsOfView(); + glm::dvec2 openSpaceFOV = skybrowser::fovWindow(); + + glm::dvec2 browserDim = screenSpaceDimensions(); + glm::dvec2 angleResult = wwtFov * (drag / browserDim); + glm::dvec2 resultRelativeOs = angleResult / openSpaceFOV; + + // Convert to screen space coordinate system + glm::dvec2 convertToScreenSpace{ (2.f * skybrowser::windowRatio()), 2.f }; + glm::dvec2 result = - convertToScreenSpace * resultRelativeOs; + return result; +} + +void ScreenSpaceSkyBrowser::setIdInBrowser() { + WwtCommunicator::setIdInBrowser(identifier()); +} + +void ScreenSpaceSkyBrowser::updateTextureResolution() { + // Scale texture depending on the height of the window + // Set texture size to the actual pixel size it covers + glm::vec2 pixels = glm::vec2(global::windowDelegate->currentSubwindowSize()); + + // If the scale is 1, it covers half the window. Hence multiplication with 2 + float newResY = pixels.y * 2.f * _scale; + float ratio = _size.x / _size.y; + float newResX = newResY * ratio; + glm::vec2 newSize = glm::vec2(newResX , newResY) * _textureQuality.value(); + + _browserPixeldimensions = glm::ivec2(newSize); + _texture->setDimensions(glm::ivec3(newSize, 1)); + _objectSize = glm::ivec3(_texture->dimensions()); +} + +void ScreenSpaceSkyBrowser::addRenderCopy(const glm::vec3& raePosition, int nCopies) { + int start = _renderCopies.size(); + for (int i = 0; i < nCopies; i++) { + openspace::properties::Property::PropertyInfo info = RenderCopyInfo; + float azimuth = i * glm::two_pi() / nCopies; + glm::vec3 position = raePosition + glm::vec3(0.f, azimuth, 0.f); + std::string id = "RenderCopy" + std::to_string(start + i); + info.identifier = id.c_str(); + _renderCopies.push_back( + std::make_unique( + info, + position, + glm::vec3(0.f, -glm::pi(), -glm::half_pi()), + glm::vec3(10.f, glm::pi(), glm::half_pi()) + ) + ); + addProperty(_renderCopies.back().get()); + } +} + +void ScreenSpaceSkyBrowser::removeRenderCopy() { + if (_renderCopies.size() > 0) { + removeProperty(_renderCopies.back().get()); + _renderCopies.pop_back(); + } +} + +std::vector> ScreenSpaceSkyBrowser::renderCopies() +{ + std::vector> vec; + std::for_each( + _renderCopies.begin(), + _renderCopies.end(), + [&](const std::unique_ptr& copy) { + std::pair pair = { + copy.get()->identifier(), + glm::dvec3(copy.get()->value()) + }; + vec.push_back(pair); + }); + return vec; +} + +void ScreenSpaceSkyBrowser::moveRenderCopy(int i, glm::vec3 raePosition) { + if (i < _renderCopies.size() && i >= 0) { + _renderCopies[i].get()->set(raePosition); + } +} + +bool ScreenSpaceSkyBrowser::deinitializeGL() { + ScreenSpaceRenderable::deinitializeGL(); + WwtCommunicator::deinitializeGL(); + + return true; +} + +void ScreenSpaceSkyBrowser::render() { + WwtCommunicator::render(); + + // If the sky browser only should be rendered on master, don't use the + // global rotation + if (_renderOnlyOnMaster && global::windowDelegate->isMaster()) { + draw( + translationMatrix() * + localRotationMatrix() * + scaleMatrix() + ); + } + else if(!_renderOnlyOnMaster) { + draw( + globalRotationMatrix() * + translationMatrix() * + localRotationMatrix() * + scaleMatrix() + ); + } + + // Render a copy that is not interactive + for (const std::unique_ptr& copy : _renderCopies) { + glm::vec3 spherical = sphericalToCartesian(raeToSpherical(copy.get()->value())); + glm::mat4 localRotation = glm::inverse(glm::lookAt( + glm::vec3(0.f), + glm::normalize(spherical), + glm::vec3(0.f, 1.f, 0.f) + )); + draw( + globalRotationMatrix() * + glm::translate(glm::mat4(1.f), spherical) * + localRotation * + scaleMatrix() + ); + } +} + +void ScreenSpaceSkyBrowser::update() { + // Texture of window is 1x1 when minimized + bool isWindow = global::windowDelegate->currentSubwindowSize() != glm::ivec2(1); + bool isWindowResized = global::windowDelegate->windowHasResized(); + if ((isWindowResized && isWindow) || _textureDimensionsIsDirty) { + updateTextureResolution(); + _textureDimensionsIsDirty = false; + } + if (_sizeIsDirty) { + updateScreenSpaceSize(); + _sizeIsDirty = false; + } + + WwtCommunicator::update(); + ScreenSpaceRenderable::update(); +} + +void ScreenSpaceSkyBrowser::setVerticalFovWithScroll(float scroll) { + // Make scroll more sensitive the smaller the FOV + double x = _verticalFov; + double zoomFactor = atan(x / 50.0) + exp(x / 40.0) - 0.99999999999999999999999999999; + double zoom = scroll > 0.0 ? -zoomFactor : zoomFactor; + _verticalFov = std::clamp(_verticalFov + zoom, 0.0, 70.0); +} + +void ScreenSpaceSkyBrowser::bindTexture() { + _texture->bind(); +} + +glm::mat4 ScreenSpaceSkyBrowser::scaleMatrix() { + // To ensure the plane has the right ratio + // The _scale tells us how much of the windows height the + // browser covers: e.g. a browser that covers 0.25 of the + // height of the window will have scale = 0.25 + + glm::mat4 scale = glm::scale( + glm::mat4(1.f), + glm::vec3(browserRatio() * _scale, _scale, 1.f) + ); + return scale; +} + +void ScreenSpaceSkyBrowser::setOpacity(float opacity) { + _opacity = opacity; +} + +void ScreenSpaceSkyBrowser::setScreenSpaceSize(const glm::vec2& newSize) { + _size = newSize; + _sizeIsDirty = true; +} + +void ScreenSpaceSkyBrowser::updateScreenSpaceSize() { + _scale = abs(_size.y) * 0.5f; + updateTextureResolution(); +} + +float ScreenSpaceSkyBrowser::opacity() const { + return _opacity; +} + +glm::vec2 ScreenSpaceSkyBrowser::size() const { + return _size; +} +} // namespace openspace diff --git a/modules/skybrowser/src/targetbrowserpair.cpp b/modules/skybrowser/src/targetbrowserpair.cpp new file mode 100644 index 0000000000..f0589918a1 --- /dev/null +++ b/modules/skybrowser/src/targetbrowserpair.cpp @@ -0,0 +1,365 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace openspace { + +TargetBrowserPair::TargetBrowserPair(SceneGraphNode* targetNode, + ScreenSpaceSkyBrowser* browser) + : _targetNode(targetNode), _browser(browser) +{ + ghoul_assert(browser != nullptr, "Sky browser is null pointer!"); + ghoul_assert(targetNode != nullptr, "Sky target is null pointer!"); + + _targetRenderable = dynamic_cast(_targetNode->renderable()); +} + +TargetBrowserPair& TargetBrowserPair::operator=(TargetBrowserPair other) { + std::swap(_targetNode, other._targetNode); + std::swap(_browser, other._browser); + return *this; +} + +void TargetBrowserPair::setImageOrder(int i, int order) { + _browser->setImageOrder(i, order); +} + +void TargetBrowserPair::removeHighlight(const glm::ivec3& color) { + _targetRenderable->removeHighlight(color); + _browser->removeHighlight(color); +} + +void TargetBrowserPair::highlight(const glm::ivec3& color) { + _browser->highlight(color); + _targetRenderable->highlight(color); +} + +void TargetBrowserPair::aimTargetGalactic(glm::dvec3 direction) { + std::string id = _targetNode->identifier(); + // Uris for properties + std::string positionUri = "Scene." + id + ".Translation.Position"; + glm::dvec3 positionCelestial = glm::normalize(direction) * + skybrowser::CelestialSphereRadius; + std::string setValue = "openspace.setPropertyValueSingle('"; + + openspace::global::scriptEngine->queueScript( + setValue + positionUri + "', " + ghoul::to_string(positionCelestial) + ");", + scripting::ScriptEngine::RemoteScripting::Yes + ); +} + +void TargetBrowserPair::startFinetuningTarget() { + _startTargetPosition = _targetNode->worldPosition(); +} + +// The fine tune of the target is a way to "drag and drop" the target with right click +// drag on the sky browser window. This is to be able to drag the target around when it +// has a very small field of view +void TargetBrowserPair::fineTuneTarget(const glm::vec2& startMouse, + const glm::vec2& translation) +{ + glm::vec2 fineTune = _browser->fineTuneVector(translation); + glm::vec2 endMouse = startMouse + fineTune; + + // Translation world + glm::dvec3 startWorld = skybrowser::localCameraToGalactic( + glm::vec3(startMouse, skybrowser::ScreenSpaceZ) + ); + glm::dvec3 endWorld = skybrowser::localCameraToGalactic( + glm::vec3(endMouse, skybrowser::ScreenSpaceZ) + ); + + glm::dvec3 translationWorld = endWorld - startWorld; + aimTargetGalactic(_startTargetPosition + translationWorld); +} + +void TargetBrowserPair::synchronizeAim() { + if (!_moveTarget.isAnimating()) { + _browser->setEquatorialAim(targetDirectionEquatorial()); + _browser->setTargetRoll(targetRoll()); + _targetRenderable->setVerticalFov(_browser->verticalFov()); + } +} + +void TargetBrowserPair::setEnabled(bool enable) { + _browser->setEnabled(enable); + _targetRenderable->property("Enabled")->set(false); +} + +void TargetBrowserPair::setOpacity(float opacity) +{ + _browser->property("Opacity")->set(opacity); + _targetRenderable->property("Opacity")->set(opacity); +} + +bool TargetBrowserPair::isEnabled() const { + return _targetRenderable->isEnabled() || _browser->isEnabled(); +} + +void TargetBrowserPair::initialize() { + _targetRenderable->setColor(_browser->borderColor()); + _targetRenderable->setDimensions(_browser->screenSpaceDimensions()); + _browser->updateBorderColor(); +} + +glm::ivec3 TargetBrowserPair::borderColor() const { + return _browser->borderColor(); +} + +glm::dvec2 TargetBrowserPair::targetDirectionEquatorial() const { + glm::dvec3 cartesian = skybrowser::galacticToEquatorial( + glm::normalize(_targetNode->worldPosition()) + ); + return skybrowser::cartesianToSpherical(cartesian); +} + +glm::dvec3 TargetBrowserPair::targetDirectionGalactic() const { + return glm::normalize(_targetNode->worldPosition()); +} + +std::string TargetBrowserPair::browserGuiName() const { + return _browser->guiName(); +} + +std::string TargetBrowserPair::browserId() const { + return _browser->identifier(); +} + +std::string TargetBrowserPair::targetRenderableId() const { + return _targetRenderable->identifier(); +} + +std::string TargetBrowserPair::targetNodeId() const { + return _targetNode->identifier(); +} + +glm::vec2 TargetBrowserPair::size() const { + return _browser->size(); +} + +double TargetBrowserPair::verticalFov() const { + return _browser->verticalFov(); +} + +const std::deque& TargetBrowserPair::selectedImages() const { + return _browser->getSelectedImages(); +} + +void TargetBrowserPair::selectImage(const ImageData& image, int i) { + // Load image into browser + _browser->displayImage(image.imageUrl, i); + + // If the image has coordinates, move the target + if (image.hasCelestialCoords) { + + // Animate the target to the image coordinate position + // unlock(); + glm::dvec3 galactic = skybrowser::equatorialToGalactic(image.equatorialCartesian); + startAnimation(galactic * skybrowser::CelestialSphereRadius, image.fov); + } +} + +void TargetBrowserPair::removeSelectedImage(int i) { + _browser->removeSelectedImage(i); +} + +void TargetBrowserPair::loadImageCollection(const std::string& collection) { + _browser->loadImageCollection(collection); +} + +void TargetBrowserPair::setImageOpacity(int i, float opacity) { + _browser->setImageOpacity(i, opacity); +} + +void TargetBrowserPair::hideChromeInterface(bool shouldHide) { + _browser->hideChromeInterface(shouldHide); +} + +void TargetBrowserPair::sendIdToBrowser() { + _browser->setIdInBrowser(); +} + +void TargetBrowserPair::updateBrowserSize() { + _browser->updateBrowserSize(); +} + +std::vector> TargetBrowserPair::renderCopies() +{ + return _browser->renderCopies(); +} + +void TargetBrowserPair::setIsSyncedWithWwt(bool isSynced) { + _browser->setIsSyncedWithWwt(isSynced); +} + +void TargetBrowserPair::setVerticalFov(double vfov) { + _browser->setVerticalFov(vfov); + _targetRenderable->setVerticalFov(vfov); +} + +void TargetBrowserPair::setEquatorialAim(const glm::dvec2& aim) { + _equatorialAim = aim; + aimTargetGalactic( + skybrowser::equatorialToGalactic(skybrowser::sphericalToCartesian(aim)) + ); + _browser->setEquatorialAim(aim); +} + +void TargetBrowserPair::setBorderColor(const glm::ivec3& color) { + _borderColor = color; + _targetRenderable->setColor(color); + _browser->setBorderColor(color); +} + +void TargetBrowserPair::setScreenSpaceSize(const glm::vec2& dimensions) { + _browser->setScreenSpaceSize(dimensions); + _targetRenderable->setDimensions(dimensions); +} + +void TargetBrowserPair::setVerticalFovWithScroll(float scroll) { + _browser->setVerticalFovWithScroll(scroll); +} + +void TargetBrowserPair::incrementallyAnimateToCoordinate() { + // Animate the target before the field of view starts to animate + if (_moveTarget.isAnimating()) { + aimTargetGalactic(_moveTarget.getNewValue()); + } + else if (!_moveTarget.isAnimating() && _targetIsAnimating) { + // Set the finished position + aimTargetGalactic(_moveTarget.getNewValue()); + _fovAnimation.start(); + _targetIsAnimating = false; + } + if (_fovAnimation.isAnimating()) { + _browser->setVerticalFov(_fovAnimation.getNewValue()); + _targetRenderable->setVerticalFov(_browser->verticalFov()); + } +} + +void TargetBrowserPair::startFading(float goal, float fadeTime) { + _fadeTarget = skybrowser::Animation(_targetRenderable->opacity(), goal, fadeTime); + _fadeBrowser = skybrowser::Animation(_browser->opacity(), goal, fadeTime); + _fadeTarget.start(); + _fadeBrowser.start(); +} + +void TargetBrowserPair::startAnimation(glm::dvec3 galacticCoords, double fovEnd) { + SkyBrowserModule* module = global::moduleEngine->module(); + double fovSpeed = module->browserAnimationSpeed(); + // The speed is given degrees /sec + double fovTime = abs(_browser->verticalFov() - fovEnd) / fovSpeed; + // Fov animation + _fovAnimation = skybrowser::Animation(_browser->verticalFov(), fovEnd, fovTime); + + // Target animation + glm::dvec3 start = glm::normalize(_targetNode->worldPosition()) * + skybrowser::CelestialSphereRadius; + double targetSpeed = module->targetAnimationSpeed(); + double angle = skybrowser::angleBetweenVectors(start, galacticCoords); + _moveTarget = skybrowser::Animation(start, galacticCoords, angle / targetSpeed); + _moveTarget.start(); + _targetIsAnimating = true; +} + +void TargetBrowserPair::centerTargetOnScreen() { + // Get camera direction in celestial spherical coordinates + glm::dvec3 viewDirection = skybrowser::cameraDirectionGalactic(); + // Keep the current fov + float currentFov = verticalFov(); + startAnimation(viewDirection, currentFov); +} + +double TargetBrowserPair::targetRoll() +{ + // To remove the lag effect when moving the camera while having a locked + // target, send the locked coordinates to wwt + glm::dvec3 normal = glm::normalize( + _targetNode->worldPosition() - + global::navigationHandler->camera()->positionVec3() + ); + glm::dvec3 right = glm::normalize( + glm::cross( + global::navigationHandler->camera()->lookUpVectorWorldSpace(), + normal + ) + ); + glm::dvec3 up = glm::normalize(glm::cross(normal, right)); + return skybrowser::targetRoll(up, normal); +} + +bool TargetBrowserPair::hasFinishedFading() const { + return !_fadeBrowser.isAnimating() && !_fadeTarget.isAnimating(); +} + +bool TargetBrowserPair::isFacingCamera() const { + return _browser->isFacingCamera(); +} + +bool TargetBrowserPair::isUsingRadiusAzimuthElevation() const { + return _browser->isUsingRaeCoords(); +} + +SceneGraphNode* TargetBrowserPair::targetNode() const { + return _targetNode; +} + +ScreenSpaceSkyBrowser* TargetBrowserPair::browser() const { + return _browser; +} + +void TargetBrowserPair::incrementallyFade() +{ + if (_fadeBrowser.isAnimating()) { + _browser->setOpacity(_fadeBrowser.getNewValue()); + } + if (_fadeTarget.isAnimating()) { + _targetRenderable->setOpacity(_fadeTarget.getNewValue()); + } +} + +bool operator==(const TargetBrowserPair& lhs, const TargetBrowserPair& rhs) { + return lhs._targetNode == rhs._targetNode && lhs._browser == rhs._browser; +} + +bool operator!=(const TargetBrowserPair& lhs, const TargetBrowserPair& rhs) { + return !(lhs == rhs); +} +} // namespace openspace diff --git a/modules/skybrowser/src/utility.cpp b/modules/skybrowser/src/utility.cpp new file mode 100644 index 0000000000..b0f381e758 --- /dev/null +++ b/modules/skybrowser/src/utility.cpp @@ -0,0 +1,269 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ +#include + +#include +#include +#include +#include +#include +#include + +namespace openspace::skybrowser { + +// Converts from spherical coordinates in the unit of degrees to cartesian coordianates +glm::dvec3 sphericalToCartesian(const glm::dvec2& coords) { + glm::dvec2 coordsRadians = glm::radians(coords); + + glm::dvec3 cartesian = glm::dvec3( + cos(coordsRadians.x) * cos(coordsRadians.y), + sin(coordsRadians.x) * cos(coordsRadians.y), + sin(coordsRadians.y) + ); + + return cartesian; +} + +// Converts from cartesian coordianates to spherical in the unit of degrees +glm::dvec2 cartesianToSpherical(const glm::dvec3& coord) { + // Equatorial coordinates RA = right ascension, Dec = declination + double ra = atan2(coord.y, coord.x); + double dec = atan2(coord.z, glm::sqrt((coord.x * coord.x) + (coord.y * coord.y))); + + ra = ra > 0 ? ra : ra + (2.0 * glm::pi()); + + glm::dvec2 celestialCoords{ ra, dec }; + + return glm::degrees(celestialCoords); +} + +glm::dvec3 galacticToEquatorial(const glm::dvec3& coords) { + return glm::transpose(conversionMatrix) * glm::normalize(coords); +} + +glm::dvec3 equatorialToGalactic(const glm::dvec3& coords) { + // On the unit sphere + glm::dvec3 rGalactic = conversionMatrix * glm::normalize(coords); + return rGalactic; +} + +glm::dvec3 localCameraToScreenSpace3d(const glm::dvec3& coords) { + // Ensure that if the coord is behind the camera, + // the converted coordinate will be there too + double zCoord = coords.z > 0 ? -ScreenSpaceZ : ScreenSpaceZ; + + // Calculate screen space coords x and y + double tanX = coords.x / coords.z; + double tanY = coords.y / coords.z; + + glm::dvec3 screenSpace = glm::dvec3(zCoord * tanX, zCoord * tanY, zCoord); + + return screenSpace; +} + +glm::dvec3 localCameraToGalactic(const glm::dvec3& coords) { + glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); + glm::dvec4 coordsVec4 = glm::dvec4(coords, 1.0) ; + glm::dmat4 camMat = glm::inverse( + global::navigationHandler->camera()->combinedViewMatrix() + ); + // Subtract gamera position to get the view direction + glm::dvec3 galactic = glm::dvec3(camMat * coordsVec4) - camPos; + + return glm::normalize(galactic) * skybrowser::CelestialSphereRadius; +} + +glm::dvec3 localCameraToEquatorial(const glm::dvec3& coords) { + // Calculate the galactic coordinate of the target direction + // projected onto the celestial sphere + glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); + glm::dvec3 galactic = camPos + skybrowser::localCameraToGalactic(coords); + + return skybrowser::galacticToEquatorial(galactic); +} + +glm::dvec3 equatorialToLocalCamera(const glm::dvec3& coords) { + // Transform equatorial J2000 to galactic coord with infinite radius + glm::dvec3 galactic = equatorialToGalactic(coords) * CelestialSphereRadius; + glm::dvec3 localCamera = galacticToLocalCamera(galactic); + return localCamera; +} + +glm::dvec3 galacticToLocalCamera(const glm::dvec3& coords) { + // Transform vector to camera's local coordinate system + glm::dmat4 camMat = global::navigationHandler->camera()->combinedViewMatrix(); + glm::dvec3 viewDirectionLocal = camMat * glm::dvec4(coords, 1.0); + + return glm::normalize(viewDirectionLocal); +} + +double targetRoll(const glm::dvec3& up, const glm::dvec3& forward) { + glm::dvec3 upJ2000 = skybrowser::galacticToEquatorial(up); + glm::dvec3 forwardJ2000 = skybrowser::galacticToEquatorial(forward); + + glm::dvec3 crossUpNorth = glm::cross(upJ2000, NorthPole); + double dotNorthUp = glm::dot(NorthPole, upJ2000); + double dotCrossUpNorthForward = glm::dot(crossUpNorth, forwardJ2000); + + return glm::degrees(atan2(dotCrossUpNorthForward, dotNorthUp)); +} + +glm::dvec3 cameraDirectionEquatorial() { + // Get the view direction of the screen in cartesian J2000 coordinates + return galacticToEquatorial(cameraDirectionGalactic()); +} + +glm::dvec3 cameraDirectionGalactic() { + // Get the view direction of the screen in galactic coordinates + glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); + glm::dvec3 view = global::navigationHandler->camera()->viewDirectionWorldSpace(); + glm::dvec3 galCoord = camPos + (skybrowser::CelestialSphereRadius * view); + + return galCoord; +} + +float windowRatio() { + glm::vec2 windowRatio = global::windowDelegate->currentWindowSize(); + return windowRatio.x / windowRatio.y; +} + +bool isCoordinateInView(const glm::dvec3& equatorial) { + // Check if image coordinate is within current FOV + glm::dvec3 localCamera = equatorialToLocalCamera(equatorial); + glm::dvec3 coordsScreen = localCameraToScreenSpace3d(localCamera); + double r = static_cast(windowRatio()); + + bool isCoordInView = abs(coordsScreen.x) < r && abs(coordsScreen.y) < 1.f && + coordsScreen.z < 0; + + return isCoordInView; +} + +// Transforms a pixel coordinate to a screen space coordinate +glm::vec2 pixelToScreenSpace2d(const glm::vec2& mouseCoordinate) { + glm::vec2 size = glm::vec2(global::windowDelegate->currentWindowSize()); + // Change origin to middle of the window + glm::vec2 screenSpacePos = mouseCoordinate - (size / 2.0f); + // Ensure the upper right corner is positive on the y axis + screenSpacePos *= glm::vec2(1.0f, -1.0f); + // Transform pixel coordinates to screen space coordinates [-1,1][-ratio, ratio] + screenSpacePos /= (0.5f * size.y); + return screenSpacePos; +} + +// The horizontal and vertical fov of the OpenSpace window +glm::dvec2 fovWindow() { + // OpenSpace FOV + glm::dvec2 windowDim = glm::dvec2(global::windowDelegate->currentWindowSize()); + double windowRatio = windowDim.y / windowDim.x; + double hFov = global::windowDelegate->getHorizFieldOfView(); + glm::dvec2 OpenSpaceFOV = glm::dvec2(hFov, hFov * windowRatio); + return OpenSpaceFOV; +} + +double angleBetweenVectors(const glm::dvec3& start, const glm::dvec3& end) { + // Find smallest angle between the two vectors + double cos = glm::dot(glm::normalize(start), glm::normalize(end)); + // Ensure cos is within defined interval [-1,1] + return std::acos(std::clamp(cos, -1.0, 1.0)); +} + +glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& end, + double percentage) +{ + double smallestAngle = angleBetweenVectors(start, end); + // Calculate rotation this frame + double rotationAngle = smallestAngle * percentage; + + // Create the rotation matrix + glm::dvec3 rotationAxis = glm::normalize(glm::cross(start, end)); + return glm::rotate(rotationAngle, rotationAxis); +} +double sizeFromFov(double fov, glm::dvec3 worldPosition) { + + // Calculate the size with trigonometry + // /| + // /_| Adjacent is the horizontal line, opposite the vertical + // \ | Calculate for half the triangle first, then multiply with 2 + // \| + double adjacent = glm::length(worldPosition); + double opposite = 2 * adjacent * glm::tan(glm::radians(fov * 0.5)); + return opposite; +} + +float Animation::getNewValue() { + if (!isAnimating()) { + return _goal; + } + else { + float percentage = static_cast(percentageSpent()); + float diff = (_goal - _start) * easeOutExpo(percentage); + return _start + diff; + } +} + +double Animation::getNewValue() { + if (!isAnimating()) { + return _goal; + } + else { + double percentage = percentageSpent(); + double diff = (_goal - _start) * easeOutExpo(percentage); + return _start + diff; + } +} + +glm::dmat4 Animation::getRotationMatrix() { + if (!isAnimating()) { + return glm::dmat4(1.0); + } + double percentage = easeInOutSine(percentageSpent()); + double increment = percentage - _lastPercentage; + _lastPercentage = percentage; + + glm::dmat4 rotMat = skybrowser::incrementalAnimationMatrix( + glm::normalize(_start), + glm::normalize(_goal), + increment + ); + return rotMat; +} + +glm::dvec3 Animation::getNewValue() { + if (!isAnimating()) { + return _goal; + } + glm::dmat4 rotMat = skybrowser::incrementalAnimationMatrix( + glm::normalize(_start), + glm::normalize(_goal), + easeOutExpo(percentageSpent()) + ); + // Rotate direction + return glm::dvec3(rotMat * glm::dvec4(_start, 1.0));; +} +} // namespace openspace + + + + diff --git a/modules/skybrowser/src/wwtcommunicator.cpp b/modules/skybrowser/src/wwtcommunicator.cpp new file mode 100644 index 0000000000..2aaef0e890 --- /dev/null +++ b/modules/skybrowser/src/wwtcommunicator.cpp @@ -0,0 +1,314 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +namespace { + constexpr const char* _loggerCat = "WwtCommunicator"; +} // namespace + +namespace openspace { + +WwtCommunicator::WwtCommunicator(const ghoul::Dictionary& dictionary) + : Browser(dictionary) {} + +WwtCommunicator::~WwtCommunicator() {} + +void WwtCommunicator::displayImage(const std::string& url, int i) { + // Ensure there are no duplicates + auto it = std::find(_selectedImages.begin(), _selectedImages.end(), i); + if (it == _selectedImages.end()) { + // Push newly selected image to front + _selectedImages.push_front(i); + // Index of image is used as layer ID as it is unique in the image data set + sendMessageToWwt(addImageMessage(std::to_string(i), url)); + sendMessageToWwt(setImageOpacityMessage(std::to_string(i), 1.0)); + } +} + +void WwtCommunicator::removeSelectedImage(int i) { + // Remove from selected list + auto it = std::find(_selectedImages.begin(), _selectedImages.end(), i); + + if (it != std::end(_selectedImages)) { + _selectedImages.erase(it); + sendMessageToWwt(removeImageMessage(std::to_string(i))); + } +} + +void WwtCommunicator::sendMessageToWwt(const ghoul::Dictionary& msg) { + std::string script = "sendMessageToWWT(" + ghoul::formatJson(msg) + ");"; + executeJavascript(script); +} + +const std::deque& WwtCommunicator::getSelectedImages() const { + return _selectedImages; +} + +void WwtCommunicator::setTargetRoll(double roll) +{ + _targetRoll = roll; +} + +void WwtCommunicator::setVerticalFov(double vfov) { + _verticalFov = vfov; + _equatorialAimIsDirty = true; +} + +void WwtCommunicator::setWebpageBorderColor(glm::ivec3 color) { + std::string stringColor = std::to_string(color.x) + "," + + std::to_string(color.y) + "," + std::to_string(color.z); + std::string script = "document.body.style.backgroundColor = 'rgb(" + + stringColor + ")';"; + executeJavascript(script); +} + +void WwtCommunicator::setIsSyncedWithWwt(bool isSynced) { + _isSyncedWithWwt = isSynced; +} + +void WwtCommunicator::setEquatorialAim(glm::dvec2 equatorial) { + _equatorialAim = std::move(equatorial); + _equatorialAimIsDirty = true; +} + +void WwtCommunicator::setBorderColor(glm::ivec3 color) { + _borderColor = std::move(color); + _borderColorIsDirty = true; +} + +void WwtCommunicator::highlight(const glm::ivec3& addition) { + setWebpageBorderColor(_borderColor + addition); +} + +void WwtCommunicator::removeHighlight(const glm::ivec3& removal) { + setWebpageBorderColor(_borderColor - removal); +} + +void WwtCommunicator::updateBorderColor() { + setWebpageBorderColor(_borderColor); +} + +void WwtCommunicator::updateAim() { + // Message WorldWide Telescope current view + ghoul::Dictionary message = moveCameraMessage( + _equatorialAim, + _verticalFov, + _targetRoll + ); + sendMessageToWwt(message); +} + +glm::dvec2 WwtCommunicator::fieldsOfView() const { + glm::dvec2 browserFov = glm::dvec2(verticalFov() * browserRatio(), verticalFov()); + + return browserFov; +} + +bool WwtCommunicator::hasLoadedImages() const { + return _hasLoadedImages; +} + +glm::dvec2 WwtCommunicator::equatorialAim() const { + return _equatorialAim; +} + +void WwtCommunicator::setImageOrder(int i, int order) { + // Find in selected images list + auto current = std::find( + _selectedImages.begin(), + _selectedImages.end(), + i + ); + auto target = std::begin(_selectedImages) + order; + + // Make sure the image was found in the list + if (current != std::end(_selectedImages) && target != std::end(_selectedImages)) { + // Swap the two images + std::iter_swap(current, target); + } + + int reverseOrder = _selectedImages.size() - order - 1; + ghoul::Dictionary message = setLayerOrderMessage(std::to_string(i), reverseOrder); + sendMessageToWwt(message); +} + +void WwtCommunicator::loadImageCollection(const std::string& collection) { + sendMessageToWwt(loadCollectionMessage(collection)); + _hasLoadedImages = true; +} + +void WwtCommunicator::setImageOpacity(int i, float opacity) { + ghoul::Dictionary msg = setImageOpacityMessage(std::to_string(i), opacity); + sendMessageToWwt(msg); +} + +void WwtCommunicator::hideChromeInterface(bool shouldHide) { + std::string script = "sendMessageToWWT({event : \"modify_settings\", " + "settings : [[\"hideAllChrome\", true]], target: \"app\"});"; + executeJavascript(script); +} + +void WwtCommunicator::update() { + Browser::update(); + // Cap how messages are passed + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + std::chrono::system_clock::duration timeSinceLastUpdate = now - _lastUpdateTime; + + if (timeSinceLastUpdate > TimeUpdateInterval) { + if (_equatorialAimIsDirty) { + updateAim(); + _equatorialAimIsDirty = false; + } + if (_borderColorIsDirty) { + updateBorderColor(); + _borderColorIsDirty = false; + } + _lastUpdateTime = std::chrono::system_clock::now(); + } +} + +void WwtCommunicator::render() { + Browser::render(); +} + +void WwtCommunicator::initializeGL() { + Browser::initializeGL(); +} + +void WwtCommunicator::deinitializeGL() { + Browser::deinitializeGL(); +} + +void WwtCommunicator::setHasLoadedImages(bool isLoaded) { + _hasLoadedImages = isLoaded; +} + +void WwtCommunicator::setIdInBrowser(const std::string& id) { + // Send ID to it's browser + executeJavascript("setId('" + id + "')"); +} + +glm::ivec3 WwtCommunicator::borderColor() const { + return _borderColor; +} + +double WwtCommunicator::verticalFov() const { + return _verticalFov; +} + +// WWT messages +ghoul::Dictionary WwtCommunicator::moveCameraMessage(const glm::dvec2& celestCoords, + double fov, double roll, + bool shouldMoveInstantly) +{ + using namespace std::string_literals; + ghoul::Dictionary msg; + + msg.setValue("event", "center_on_coordinates"s); + msg.setValue("ra", celestCoords.x); + msg.setValue("dec", celestCoords.y); + msg.setValue("fov", fov); + msg.setValue("roll", roll); + msg.setValue("instant", shouldMoveInstantly); + + return msg; +} + +ghoul::Dictionary WwtCommunicator::loadCollectionMessage(const std::string& url) { + using namespace std::string_literals; + ghoul::Dictionary msg; + msg.setValue("event", "load_image_collection"s); + msg.setValue("url", url); + msg.setValue("loadChildFolders", true); + + return msg; +} + +ghoul::Dictionary WwtCommunicator::setForegroundMessage(const std::string& name) { + using namespace std::string_literals; + ghoul::Dictionary msg; + msg.setValue("event", "set_foreground_by_name"s); + msg.setValue("name", name); + + return msg; +} + +ghoul::Dictionary WwtCommunicator::addImageMessage(const std::string& id, + const std::string& url) +{ + using namespace std::string_literals; + ghoul::Dictionary msg; + msg.setValue("event", "image_layer_create"s); + msg.setValue("id", id); + msg.setValue("url", url); + msg.setValue("mode", "preloaded"s); + msg.setValue("goto", false); + + return msg; +} + +ghoul::Dictionary WwtCommunicator::removeImageMessage(const std::string& imageId) { + using namespace std::string_literals; + ghoul::Dictionary msg; + msg.setValue("event", "image_layer_remove"s); + msg.setValue("id", imageId); + + return msg; +} + +ghoul::Dictionary WwtCommunicator::setImageOpacityMessage(const std::string& imageId, + double opacity) +{ + using namespace std::string_literals; + ghoul::Dictionary msg; + msg.setValue("event", "image_layer_set"s); + msg.setValue("id", imageId); + msg.setValue("setting", "opacity"s); + msg.setValue("value", opacity); + + return msg; +} + +ghoul::Dictionary WwtCommunicator::setLayerOrderMessage(const std::string& id, int order) { + // The lower the layer order, the more towards the back the image is placed + // 0 is the background + using namespace std::string_literals; + ghoul::Dictionary msg; + msg.setValue("event", "image_layer_order"s); + msg.setValue("id", id); + msg.setValue("order", order); + msg.setValue("version", messageCounter); + + messageCounter++; + + return msg; +} +} // namespace openspace diff --git a/modules/skybrowser/src/wwtdatahandler.cpp b/modules/skybrowser/src/wwtdatahandler.cpp new file mode 100644 index 0000000000..dc0281f462 --- /dev/null +++ b/modules/skybrowser/src/wwtdatahandler.cpp @@ -0,0 +1,378 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2022 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + constexpr const char* _loggerCat = "WwtDataHandler"; +} //namespace + +namespace openspace { + +bool hasAttribute(const tinyxml2::XMLElement* element, const std::string_view& name) { + return element->FindAttribute(std::string(name).c_str()); +} + +std::string attribute(const tinyxml2::XMLElement* element, const std::string& name) { + if (hasAttribute(element, name)) { + return element->FindAttribute(name.c_str())->Value(); + } + return wwt::Undefined; +} + +// Parsing and downloading of wtml files +bool downloadFile(const std::string& url, const std::filesystem::path& fileDestination) { + // Get the web page and save to file + HttpFileDownload wtmlRoot( + url, + fileDestination, + HttpFileDownload::Overwrite::Yes + ); + wtmlRoot.start(std::chrono::milliseconds(10000)); + return wtmlRoot.wait(); +} + +bool directoryExists(const std::filesystem::path& path) { + return std::filesystem::exists(path) && std::filesystem::is_directory(path); +} + +std::string createSearchableString(std::string str) { + // Remove white spaces and all special characters + str.erase( + std::remove_if( + str.begin(), + str.end(), + [](char c) { + const bool isNumberOrLetter = std::isdigit(c) || std::isalpha(c); + return !isNumberOrLetter; + } + ), + str.end() + ); + // Make the word lower case + std::transform( + str.begin(), + str.end(), + str.begin(), + [](char c) { + return std::tolower(c); + } + ); + return str; +} + +tinyxml2::XMLElement* getDirectChildNode(tinyxml2::XMLElement* node, + const std::string& name) +{ + while (node && node->Name() != name) { + node = node->FirstChildElement(); + } + return node; +} + +tinyxml2::XMLElement* getChildNode(tinyxml2::XMLElement* node, + const std::string& name) +{ + tinyxml2::XMLElement* child = node->FirstChildElement(); + tinyxml2::XMLElement* imageSet = nullptr; + + // Traverse the children and look at all their first child to find ImageSet + while (child) { + imageSet = getDirectChildNode(child, name); + // Found + if (imageSet) { + break; + } + child = child->NextSiblingElement(); + } + return imageSet; +} + +std::string getChildNodeContentFromImageSet(tinyxml2::XMLElement* imageSet, + const std::string& elementName) +{ + // Find the thumbnail image url + // The thumbnail is the last node so traverse backwards for speed + tinyxml2::XMLElement* imageSetChild = imageSet->FirstChildElement( + elementName.c_str() + ); + + if (imageSetChild && imageSetChild->GetText()) { + return imageSetChild->GetText(); + } + return wwt::Undefined; +} + +std::string getUrlFromPlace(tinyxml2::XMLElement* place) { + // If the place has a thumbnail url, return it + if (hasAttribute(place, wwt::Thumbnail)) { + return attribute(place, wwt::Thumbnail); + } + + // If the place doesn't have a thumbnail url data attribute, + // Load the image set it stores instead + tinyxml2::XMLElement* imageSet = getChildNode(place, wwt::ImageSet); + + // If there is an imageSet, collect thumbnail url + if (imageSet) { + return getChildNodeContentFromImageSet(imageSet, wwt::ThumbnailUrl); + } + // If it doesn't contain an ImageSet, it doesn't have an url + return wwt::Undefined; +} + + +void parseWtmlsFromDisc(std::vector& _xmls, + const std::filesystem::path& directory) +{ + for (const auto& entry : std::filesystem::directory_iterator(directory)) { + tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument(); + std::string path = entry.path().u8string(); + tinyxml2::XMLError successCode = document->LoadFile(path.c_str()); + + if (successCode == tinyxml2::XMLError::XML_SUCCESS) { + _xmls.push_back(document); + } + } +} + +bool downloadAndParseWtmlFilesFromUrl(std::vector& _xmls, + const std::filesystem::path& directory, const std::string& url, + const std::string& fileName) +{ + // Look for WWT image data folder, create folder if it doesn't exist + if (!directoryExists(directory)) { + std::string newDir = directory.string(); + // Remove the '/' at the end + newDir.pop_back(); + LINFO("Creating directory" + newDir); + std::filesystem::create_directory(newDir); + } + + // Download file from url + std::filesystem::path file = directory.string() + fileName + ".aspx"; + if (!downloadFile(url, file)) { + LINFO( + fmt::format("Couldn't download file '{}' to directory '{}'", url, directory) + ); + return false; + } + + // Parse file to XML + using namespace tinyxml2; + tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument(); + doc->LoadFile(file.string().c_str()); + + // Search XML file for folders with urls + XMLElement* root = doc->RootElement(); + XMLElement* element = root->FirstChildElement(wwt::Folder.c_str()); + const bool folderExists = element; + const bool folderContainNoUrls = folderExists && !hasAttribute(element, wwt::Url); + + // If the file contains no folders, or there are folders but without urls, + // stop recursion + if (!folderExists || folderContainNoUrls) { + _xmls.push_back(doc); + LINFO("Saving " + url); + return true; + } + + // Iterate through all the folders in the XML file + while (element && std::string(element->Value()) == wwt::Folder) { + // If folder contains urls, download and parse those urls + if (hasAttribute(element, wwt::Url) && hasAttribute(element, wwt::Name)) { + std::string url = attribute(element, wwt::Url); + std::string fileName = attribute(element, wwt::Name); + downloadAndParseWtmlFilesFromUrl(_xmls, directory, url, fileName); + } + element = element->NextSiblingElement(); + } + return true; +} + +WwtDataHandler::~WwtDataHandler() { + // Call destructor of all allocated xmls + _xmls.clear(); +} + +void WwtDataHandler::loadImages(const std::string& root, + const std::filesystem::path& directory) +{ + // Collect the wtml files, either by reading from disc or from a url + if (directoryExists(directory) && !std::filesystem::is_empty(directory)) { + parseWtmlsFromDisc(_xmls, directory); + LINFO("Loading images from directory"); + } + else { + downloadAndParseWtmlFilesFromUrl(_xmls, directory, root, "root"); + LINFO("Loading images from url"); + } + + // Traverse through the collected wtml documents and collect the images + for (tinyxml2::XMLDocument* doc : _xmls) { + tinyxml2::XMLElement* root = doc->FirstChildElement(); + std::string collectionName = attribute(root, wwt::Name); + saveImagesFromXml(root, collectionName); + } + + // Sort images in alphabetical order + std::sort( + _images.begin(), + _images.end(), + [](ImageData& a, ImageData& b) { + // If the first character in the names are lowercase, make it upper case + if (std::islower(a.name[0])) { + // convert string to upper case + a.name[0] = ::toupper(a.name[0]); + } + if (std::islower(b.name[0])) { + b.name[0] = ::toupper(b.name[0]); + } + return a.name < b.name; + } + ); + + LINFO(fmt::format("Loaded {} WorldWide Telescope images.", _images.size())); +} + +int WwtDataHandler::nLoadedImages() const { + return _images.size(); +} + +const ImageData& WwtDataHandler::getImage(const int i) const { + ghoul_assert(i < _images.size(), "Index outside of image vector boundaries!"); + return _images[i]; +} + +void WwtDataHandler::saveImageFromNode(tinyxml2::XMLElement* node, + std::string collection) +{ + // Collect the image set of the node. The structure is different depending on if + // it is a Place or an ImageSet + std::string thumbnailUrl = { wwt::Undefined }; + tinyxml2::XMLElement* imageSet{ nullptr }; + std::string type = std::string(node->Name()); + + if (type == wwt::ImageSet) { + thumbnailUrl = getChildNodeContentFromImageSet(node, wwt::ThumbnailUrl); + imageSet = node; + } + else if (type == wwt::Place) { + thumbnailUrl = getUrlFromPlace(node); + imageSet = getChildNode(node, wwt::ImageSet); + } + + // Only collect the images that have a thumbnail image, that are sky images and + // that have an image + const bool hasThumbnailUrl = thumbnailUrl != wwt::Undefined; + const bool isSkyImage = attribute(node, wwt::DataSetType) == wwt::Sky; + const bool hasImageUrl = imageSet ? hasAttribute(imageSet, wwt::Url) : false; + + if (!(hasThumbnailUrl && isSkyImage && hasImageUrl)) { + return; + } + + // Collect name, image url and credits + std::string name = attribute(node, wwt::Name); + std::string imageUrl = attribute(imageSet, wwt::Url); + std::string credits = getChildNodeContentFromImageSet(imageSet, wwt::Credits); + std::string creditsUrl = getChildNodeContentFromImageSet( + imageSet, wwt::CreditsUrl + ); + + // Collect equatorial coordinates. All-sky surveys do not have this kind of + // coordinate + bool hasCelestialCoords = hasAttribute(node, wwt::RA) && + hasAttribute(node, wwt::Dec); + glm::dvec2 equatorialSpherical{ 0.0 }; + glm::dvec3 equatorialCartesian{ 0.0 }; + + if (hasCelestialCoords) { + // The RA from WWT is in the unit hours: + // to convert to degrees, multiply with 360 (deg) /24 (h) = 15 + double ra = 15.0 * std::stod(attribute(node, wwt::RA)); + double dec = std::stod(attribute(node, wwt::Dec)); + equatorialSpherical = { ra, dec }; + equatorialCartesian = skybrowser::sphericalToCartesian( + equatorialSpherical + ); + } + + // Collect field of view. The WWT definition of ZoomLevel is: VFOV = ZoomLevel / 6 + float fov = 0.f; + if (hasAttribute(node, wwt::ZoomLevel)) { + fov = std::stof(attribute(node, wwt::ZoomLevel)) / 6.0f; + } + + ImageData image = { + name, + thumbnailUrl, + imageUrl, + credits, + creditsUrl, + collection, + hasCelestialCoords, + fov, + equatorialSpherical, + equatorialCartesian, + }; + + _images.push_back(image); +} + +void WwtDataHandler::saveImagesFromXml(tinyxml2::XMLElement* root, + std::string collection) +{ + // Get direct child of node called Place + using namespace tinyxml2; + XMLElement* node = root->FirstChildElement(); + + // Iterate through all siblings of node. If sibling is folder, open recursively. + // If sibling is image, save it. + while (node) { + const std::string name = node->Name(); + // If node is an image or place, load it + if (name == wwt::ImageSet || name == wwt::Place) { + saveImageFromNode(node, collection); + } + // If node is another folder, open recursively + else if (name == wwt::Folder) { + std::string newCollectionName = collection + "/"; + newCollectionName += attribute(node, wwt::Name); + + saveImagesFromXml(node, newCollectionName); + } + node = node->NextSiblingElement(); + } +} +} // namespace openspace diff --git a/modules/webbrowser/include/screenspacebrowser.h b/modules/webbrowser/include/screenspacebrowser.h index 66a6f39c43..417706e9a8 100644 --- a/modules/webbrowser/include/screenspacebrowser.h +++ b/modules/webbrowser/include/screenspacebrowser.h @@ -72,6 +72,11 @@ public: void update() override; bool isReady() const override; +protected: + properties::Vec2Property _dimensions; + std::unique_ptr _browserInstance; + std::unique_ptr _texture; + private: class ScreenSpaceRenderHandler : public WebRenderHandler { public: @@ -81,21 +86,19 @@ private: void setTexture(GLuint t); }; + CefRefPtr _renderHandler; + +private: void bindTexture() override; properties::StringProperty _url; - properties::Vec2Property _dimensions; properties::TriggerProperty _reload; - CefRefPtr _renderHandler; CefRefPtr _keyboardHandler; - std::unique_ptr _browserInstance; - std::unique_ptr _texture; - + bool _isUrlDirty = false; bool _isDimensionsDirty = false; }; - } // namespace openspace #endif // __OPENSPACE_MODULE_WEBBROWSER___SCREEN_SPACE_BROWSER___H__ diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index cca003d0b9..97a4415473 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -1116,6 +1116,7 @@ void RenderEngine::removeScreenSpaceRenderable(ScreenSpaceRenderable* s) { if (it != global::screenSpaceRenderables->end()) { global::eventEngine->publishEvent(s); + s->deinitializeGL(); s->deinitialize(); global::screenSpaceRootPropertyOwner->removePropertySubOwner(s); global::screenSpaceRenderables->erase(it); diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index 4c422279c6..710213f095 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -152,84 +152,6 @@ namespace { return glm::mod(value - min, max - min) + min; } - glm::vec3 sanitizeSphericalCoordinates(glm::vec3 spherical) { - const float r = spherical.x; - float phi = spherical.z; - - // Sanitize coordinates. - float theta = wrap(spherical.y, 0.f, glm::two_pi()); - if (theta > glm::pi()) { - theta = glm::two_pi() - theta; - phi += glm::pi(); - } - - return glm::vec3(r, theta, phi); - } - - glm::vec3 sphericalToCartesian(glm::vec3 spherical) { - // First convert to ISO convention spherical coordinates according to - // https://en.wikipedia.org/wiki/Spherical_coordinate_system - // (radius, theta, phi), where theta is the polar angle from the z axis, - // and phi is the azimuth. - - const glm::vec3 sanitized = sanitizeSphericalCoordinates(std::move(spherical)); - const float x = sanitized[0] * sin(sanitized[1]) * cos(sanitized[2]); - const float y = sanitized[0] * sin(sanitized[1]) * sin(sanitized[2]); - const float z = sanitized[0] * cos(sanitized[1]); - - // Now, convert rotate the coordinate system, so that z maps to y, - // and y maps to -z. We want the pole to be in y instead of z. - return glm::vec3(x, -z, y); - } - - glm::vec3 cartesianToSpherical(const glm::vec3& cartesian) { - // Rotate cartesian coordinates. - glm::vec3 rotated = glm::vec3(cartesian.x, cartesian.z, -cartesian.y); - - const float r = sqrt( - pow(rotated.x, 2.f) + pow(rotated.y, 2.f) + pow(rotated.z, 2.f) - ); - const float theta = acos(rotated.z/r); - const float phi = atan2(rotated.y, rotated.x); - return sanitizeSphericalCoordinates(glm::vec3(r, theta, phi)); - } - - // Radius, azimiuth, elevation to spherical coordinates. - glm::vec3 raeToSpherical(glm::vec3 rae) { - //return rae; - const float r = rae.x; - - // Polar angle, theta, is elevation + pi/2. - const float theta = rae.z + glm::half_pi(); - - // Azimuth in ISO spherical coordiantes (phi) is angle from x, - // as opposed to from negative y on screen. - const float phi = rae.y - glm::half_pi(); - - return glm::vec3(r, theta, phi); - } - - // Spherical coordinates to radius, azimuth and elevation. - glm::vec3 sphericalToRae(glm::vec3 spherical) { - //return spherical; - const float r = spherical.x; - - // Azimuth on screen is angle from negative y, as opposed to from x. - float azimuth = spherical.z + glm::half_pi(); - - // Elevation is polar angle - pi/2 - float elevation = wrap( - spherical.y - glm::half_pi(), - -glm::pi(), - glm::pi() - ); - - return glm::vec3( - r, - wrap(azimuth, -glm::pi(), glm::pi()), - wrap(elevation, -glm::pi(), glm::pi()) - ); - } struct [[codegen::Dictionary(ScreenSpaceRenderable)]] Parameters { // The type of the Screenspace renderable that is to be created. The available @@ -494,6 +416,18 @@ bool ScreenSpaceRenderable::isEnabled() const { return _enabled; } +bool ScreenSpaceRenderable::isUsingRaeCoords() const { + return _useRadiusAzimuthElevation; +} + +bool ScreenSpaceRenderable::isFacingCamera() const { + return _faceCamera; +} + +void ScreenSpaceRenderable::setEnabled(bool isEnabled) { + _enabled = isEnabled; +} + float ScreenSpaceRenderable::depth() { return _useRadiusAzimuthElevation ? _raePosition.value().x : @@ -539,20 +473,60 @@ glm::mat4 ScreenSpaceRenderable::scaleMatrix() { glm::mat4 scale = glm::scale( glm::mat4(1.f), - glm::vec3(_scale, _scale * textureRatio, 1.f) + glm::vec3(_scale, textureRatio*_scale, 1.f) ); - // Simulate orthographic projection by distance to plane. - if (!_usePerspectiveProjection) { - float distance = _useRadiusAzimuthElevation ? - _raePosition.value().x : - -_cartesianPosition.value().z; - scale = glm::scale(scale, glm::vec3(distance)); - } - return scale; } +glm::vec2 ScreenSpaceRenderable::screenSpacePosition() { + return glm::vec2(_cartesianPosition.value()); +} + +glm::vec2 ScreenSpaceRenderable::screenSpaceDimensions() { + float ratio = static_cast(_objectSize.x) / static_cast(_objectSize.y); + return glm::vec2(2.f * _scale * ratio, 2.f * _scale); +} + +glm::vec2 ScreenSpaceRenderable::upperRightCornerScreenSpace() { + return screenSpacePosition() + (screenSpaceDimensions() / 2.0f); +} + +glm::vec2 ScreenSpaceRenderable::lowerLeftCornerScreenSpace() { + return screenSpacePosition() - (screenSpaceDimensions() / 2.0f); +} + +bool ScreenSpaceRenderable::isIntersecting(glm::vec2 coord) { + bool isUnderTopBorder = coord.x < upperRightCornerScreenSpace().x; + bool isLeftToRightBorder = coord.y < upperRightCornerScreenSpace().y; + bool isRightToLeftBorder = coord.x > lowerLeftCornerScreenSpace().x; + bool isOverBottomBorder = coord.y > lowerLeftCornerScreenSpace().y; + + return isUnderTopBorder && isLeftToRightBorder && + isRightToLeftBorder && isOverBottomBorder; +} + +void ScreenSpaceRenderable::translate(glm::vec2 translation, glm::vec2 position) { + glm::mat4 translationMatrix = glm::translate( + glm::mat4(1.f), + glm::vec3(translation, 0.0f) + ); + glm::vec4 origin = glm::vec4(position, _cartesianPosition.value().z, 1.0f); + _cartesianPosition = translationMatrix * origin; +} + +void ScreenSpaceRenderable::setCartesianPosition(const glm::vec3& position) { + _cartesianPosition = position; +} + +void ScreenSpaceRenderable::setRaeFromCartesianPosition(const glm::vec3& position) { + _raePosition = cartesianToRae(position); +} + +glm::vec3 ScreenSpaceRenderable::raePosition() const { + return _raePosition; +} + glm::mat4 ScreenSpaceRenderable::globalRotationMatrix() { // We do not want the screen space planes to be affected by // 1) The global rotation of the view applied in the render engine @@ -587,6 +561,14 @@ glm::mat4 ScreenSpaceRenderable::localRotationMatrix() { return rotation * glm::mat4(glm::quat(glm::vec3(pitch, yaw, roll))); } +glm::vec3 ScreenSpaceRenderable::raeToCartesian(const glm::vec3& rae) const { + return sphericalToCartesian(raeToSpherical(rae)); +} + +glm::vec3 ScreenSpaceRenderable::cartesianToRae(const glm::vec3& cartesian) const { + return sphericalToRae(cartesianToSpherical(cartesian)); +} + glm::mat4 ScreenSpaceRenderable::translationMatrix() { glm::vec3 translation = _useRadiusAzimuthElevation ? sphericalToCartesian(raeToSpherical(_raePosition)) : @@ -625,8 +607,87 @@ void ScreenSpaceRenderable::draw(glm::mat4 modelTransform) { void ScreenSpaceRenderable::unbindTexture() {} +glm::vec3 ScreenSpaceRenderable::sanitizeSphericalCoordinates(glm::vec3 spherical) const { + const float r = spherical.x; + float phi = spherical.z; + + // Sanitize coordinates. + float theta = wrap(spherical.y, 0.f, glm::two_pi()); + if (theta > glm::pi()) { + theta = glm::two_pi() - theta; + phi += glm::pi(); + } + + return glm::vec3(r, theta, phi); +} + +glm::vec3 ScreenSpaceRenderable::sphericalToCartesian(glm::vec3 spherical) const { + // First convert to ISO convention spherical coordinates according to + // https://en.wikipedia.org/wiki/Spherical_coordinate_system + // (radius, theta, phi), where theta is the polar angle from the z axis, + // and phi is the azimuth. + + const glm::vec3 sanitized = sanitizeSphericalCoordinates(std::move(spherical)); + const float x = sanitized[0] * sin(sanitized[1]) * cos(sanitized[2]); + const float y = sanitized[0] * sin(sanitized[1]) * sin(sanitized[2]); + const float z = sanitized[0] * cos(sanitized[1]); + + // Now, convert rotate the coordinate system, so that z maps to y, + // and y maps to -z. We want the pole to be in y instead of z. + return glm::vec3(x, -z, y); +} + +glm::vec3 ScreenSpaceRenderable::cartesianToSpherical(const glm::vec3& cartesian) const { + // Rotate cartesian coordinates. + glm::vec3 rotated = glm::vec3(cartesian.x, cartesian.z, -cartesian.y); + + const float r = sqrt( + pow(rotated.x, 2.f) + pow(rotated.y, 2.f) + pow(rotated.z, 2.f) + ); + const float theta = acos(rotated.z / r); + const float phi = atan2(rotated.y, rotated.x); + return sanitizeSphericalCoordinates(glm::vec3(r, theta, phi)); +} + +// Radius, azimiuth, elevation to spherical coordinates. +glm::vec3 ScreenSpaceRenderable::raeToSpherical(glm::vec3 rae) const { + //return rae; + const float r = rae.x; + + // Polar angle, theta, is elevation + pi/2. + const float theta = rae.z + glm::half_pi(); + + // Azimuth in ISO spherical coordiantes (phi) is angle from x, + // as opposed to from negative y on screen. + const float phi = rae.y - glm::half_pi(); + + return glm::vec3(r, theta, phi); +} + +// Spherical coordinates to radius, azimuth and elevation. +glm::vec3 ScreenSpaceRenderable::sphericalToRae(glm::vec3 spherical) const { + //return spherical; + const float r = spherical.x; + + // Azimuth on screen is angle from negative y, as opposed to from x. + float azimuth = spherical.z + glm::half_pi(); + + // Elevation is polar angle - pi/2 + float elevation = wrap( + spherical.y - glm::half_pi(), + -glm::pi(), + glm::pi() + ); + + return glm::vec3( + r, + wrap(azimuth, -glm::pi(), glm::pi()), + wrap(elevation, -glm::pi(), glm::pi()) + ); +} + + float ScreenSpaceRenderable::opacity() const { return _opacity * _fade; } - } // namespace openspace