From ee800cee89c92ae9abebe57a4bf205310bc67aa1 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 23 Sep 2019 13:08:23 -0400 Subject: [PATCH 01/42] Fixed star rendering cuts on cubemap borders. --- .../digitaluniverse/shaders/billboard_fs.glsl | 2 +- .../digitaluniverse/shaders/billboard_gs.glsl | 19 +-- modules/space/shaders/star_ge.glsl | 109 ++++-------------- 3 files changed, 38 insertions(+), 92 deletions(-) diff --git a/modules/digitaluniverse/shaders/billboard_fs.glsl b/modules/digitaluniverse/shaders/billboard_fs.glsl index 3ca590e5a5..d2859f1162 100644 --- a/modules/digitaluniverse/shaders/billboard_fs.glsl +++ b/modules/digitaluniverse/shaders/billboard_fs.glsl @@ -25,7 +25,7 @@ #include "fragment.glsl" flat in vec4 gs_colorMap; -in float vs_screenSpaceDepth; +flat in float vs_screenSpaceDepth; in vec2 texCoord; in float ta; diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index cb955fbc33..4ee3047d28 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -55,7 +55,7 @@ flat in float dvarScaling[]; flat out vec4 gs_colorMap; out vec2 texCoord; -out float vs_screenSpaceDepth; +flat out float vs_screenSpaceDepth; out float ta; const double PARSEC = 0.308567756e17LF; @@ -171,17 +171,22 @@ void main() { // Build primitive - texCoord = corners[3]; - gl_Position = thirdPosition; - EmitVertex(); + texCoord = corners[0]; gl_Position = initialPosition; EmitVertex(); - texCoord = corners[2]; - gl_Position = crossCorner; - EmitVertex(); + texCoord = corners[1]; gl_Position = secondPosition; EmitVertex(); + + texCoord = corners[3]; + gl_Position = thirdPosition; + EmitVertex(); + + texCoord = corners[2]; + gl_Position = crossCorner; + EmitVertex(); + EndPrimitive(); } \ No newline at end of file diff --git a/modules/space/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl index dcb36a5711..d12d51d146 100644 --- a/modules/space/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -83,13 +83,7 @@ void main() { dvec4 dpos = modelMatrix * dvec4(vs_position); dvec4 clipTestPos = cameraViewProjectionMatrix * dpos; - clipTestPos /= clipTestPos.w; - if ((clipTestPos.x < -1.0 || clipTestPos.x > 1.0) || - (clipTestPos.y < -1.0 || clipTestPos.y > 1.0)) - { - return; - } - + ge_bvLumAbsMagAppMag = vs_bvLumAbsMagAppMag[0]; ge_velocity = vs_velocity[0]; ge_speed = vs_speed[0]; @@ -156,96 +150,43 @@ void main() { dvec3 scaledUp = dvec3(0.0); vec4 bottomLeftVertex, bottomRightVertex, topLeftVertex, topRightVertex; - // if (distanceToStarInParsecs > 1800.0) { - // scaledRight = scaleMultiply * invariantRight * 0.5f; - // scaledUp = scaleMultiply * invariantUp * 0.5f; - // } else { - dvec3 normal = normalize(eyePosition - dpos.xyz); - dvec3 newRight = normalize(cross(cameraUp, normal)); - dvec3 newUp = cross(normal, newRight); - scaledRight = scaleMultiply * newRight; - scaledUp = scaleMultiply * newUp; - //} - + dvec3 normal = normalize(eyePosition - dpos.xyz); + dvec3 newRight = normalize(cross(cameraUp, normal)); + dvec3 newUp = cross(normal, newRight); + scaledRight = scaleMultiply * newRight; + scaledUp = scaleMultiply * newUp; + bottomLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); gs_screenSpaceDepth = bottomLeftVertex.w; - topRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); + topRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * + dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - // Testing size: - // vec3 tmpPos = vec3(eyePositionDelta); - // vec4 falseBottomLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(tmpPos - scaledRight - scaledUp, dpos.w))); + bottomRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * + dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - // vec4 falseTopRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(tmpPos + scaledUp + scaledRight, dpos.w))); - // vec2 halfViewSize = vec2(screenSize.x, screenSize.y) * 0.5f; - // vec2 topRight = falseTopRightVertex.xy/falseTopRightVertex.w; - // vec2 bottomLeft = falseBottomLeftVertex.xy/falseBottomLeftVertex.w; - - // Complete algebra - // topRight = ((topRight + vec2(1.0)) * halfViewSize) - vec2(0.5); - // bottomLeft = ((bottomLeft + vec2(1.0)) * halfViewSize) - vec2(0.5); - //vec2 sizes = abs(topRight - bottomLeft); - - // Optimized version - // vec2 sizes = abs(halfViewSize * (topRight - bottomLeft)); - - // float height = sizes.y; - // float width = sizes.x; - - // if ((height > billboardSize) || - // (width > billboardSize)) { - // float correctionScale = height > billboardSize ? billboardSize / height : - // billboardSize / width; - - // scaledRight *= correctionScale; - // scaledUp *= correctionScale; - // bottomLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); - // gs_screenSpaceDepth = bottomLeftVertex.w; - // topRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - - - // bottomRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - - // topLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); - - // } else { - // if (width < 2.0f) { - // float maxVar = 2.0f; - // float minVar = 1.0f; - // float var = (height + width); - // float ta = ( (var - minVar)/(maxVar - minVar) ); - // if (ta == 0.0f) - // return; - // } - // float minSize = 30.f; - // if ((width < minSize) || (height < minSize)) - // return; - bottomRightVertex = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - topLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * + topLeftVertex = z_normalization(vec4(cameraViewProjectionMatrix * dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); - // } - + // Build primitive - gl_Position = topLeftVertex; - psfCoords = vec2(-1.0, 1.0); - EmitVertex(); + gl_Position = bottomLeftVertex; psfCoords = vec2(-1.0, -1.0); EmitVertex(); - gl_Position = topRightVertex; - psfCoords = vec2(1.0, 1.0); - EmitVertex(); + gl_Position = bottomRightVertex; psfCoords = vec2(1.0, -1.0); EmitVertex(); + + gl_Position = topLeftVertex; + psfCoords = vec2(-1.0, 1.0); + EmitVertex(); + + gl_Position = topRightVertex; + psfCoords = vec2(1.0, 1.0); + EmitVertex(); + EndPrimitive(); + } From 2694810e27a50ca34319e21f140794ddf9d3ef39 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 23 Sep 2019 13:12:07 -0400 Subject: [PATCH 02/42] Clean up. --- modules/space/shaders/star_ge.glsl | 2 -- 1 file changed, 2 deletions(-) diff --git a/modules/space/shaders/star_ge.glsl b/modules/space/shaders/star_ge.glsl index d12d51d146..80ba2dd4f1 100644 --- a/modules/space/shaders/star_ge.glsl +++ b/modules/space/shaders/star_ge.glsl @@ -82,8 +82,6 @@ void main() { vs_position = gl_in[0].gl_Position; // in object space dvec4 dpos = modelMatrix * dvec4(vs_position); - dvec4 clipTestPos = cameraViewProjectionMatrix * dpos; - ge_bvLumAbsMagAppMag = vs_bvLumAbsMagAppMag[0]; ge_velocity = vs_velocity[0]; ge_speed = vs_speed[0]; From ab52b812f9ae98e4d273bca4a25cf7637770f2a1 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 25 Sep 2019 16:03:34 -0400 Subject: [PATCH 03/42] Improved geometry shader performance. --- .../digitaluniverse/shaders/billboard_fs.glsl | 4 +++ .../digitaluniverse/shaders/billboard_gs.glsl | 28 +++++++++++++------ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/modules/digitaluniverse/shaders/billboard_fs.glsl b/modules/digitaluniverse/shaders/billboard_fs.glsl index 3ca590e5a5..4d08f6e912 100644 --- a/modules/digitaluniverse/shaders/billboard_fs.glsl +++ b/modules/digitaluniverse/shaders/billboard_fs.glsl @@ -39,6 +39,10 @@ Fragment getFragment() { vec4 textureColor = texture(spriteTexture, texCoord); + if (textureColor.a == 0.f || gs_colorMap.a == 0.f) { + discard; + } + vec4 fullColor = vec4(1.0); if (hasColorMap) { diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index cb955fbc33..d83e53b10f 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -159,16 +159,26 @@ void main() { } } - initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); - vs_screenSpaceDepth = initialPosition.w; - secondPosition = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - thirdPosition = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); + // initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * + // dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); + // vs_screenSpaceDepth = initialPosition.w; + // secondPosition = z_normalization(vec4(cameraViewProjectionMatrix * + // dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); + // crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * + // dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); + // thirdPosition = z_normalization(vec4(cameraViewProjectionMatrix * + // dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); + // Saving one matrix multiplication: + dvec4 dposClip = cameraViewProjectionMatrix * dpos; + dvec4 scaledRightClip = cameraViewProjectionMatrix * dvec4(scaledRight, 0.0); + dvec4 scaledUpClip = cameraViewProjectionMatrix * dvec4(scaledUp, 0.0); + + initialPosition = z_normalization(vec4(dposClip - scaledRightClip - scaledUpClip)); + vs_screenSpaceDepth = initialPosition.w; + secondPosition = z_normalization(vec4(dposClip + scaledRightClip - scaledUpClip)); + crossCorner = z_normalization(vec4(dposClip + scaledUpClip + scaledRightClip)); + thirdPosition = z_normalization(vec4(dposClip + scaledUpClip - scaledRightClip)); // Build primitive texCoord = corners[3]; From 5eb99492931df807fa60fe28f61dc63829b23347 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Thu, 26 Sep 2019 11:38:41 -0400 Subject: [PATCH 04/42] Improved performance of RenderableBillboardsClod. --- data/assets/scene/digitaluniverse/2dF.asset | 4 +- data/assets/scene/digitaluniverse/2mass.asset | 4 +- data/assets/scene/digitaluniverse/6dF.asset | 4 +- data/assets/scene/digitaluniverse/abell.asset | 4 +- .../scene/digitaluniverse/quasars.asset | 4 +- data/assets/scene/digitaluniverse/sdss.asset | 4 +- .../scene/digitaluniverse/superclusters.asset | 4 +- data/assets/scene/digitaluniverse/tully.asset | 4 +- .../rendering/renderablebillboardscloud.cpp | 10 ++-- .../digitaluniverse/shaders/billboard_fs.glsl | 3 +- .../digitaluniverse/shaders/billboard_gs.glsl | 58 ++++++++----------- 11 files changed, 49 insertions(+), 54 deletions(-) diff --git a/data/assets/scene/digitaluniverse/2dF.asset b/data/assets/scene/digitaluniverse/2dF.asset index 2b09ab91ff..2da1fb619d 100644 --- a/data/assets/scene/digitaluniverse/2dF.asset +++ b/data/assets/scene/digitaluniverse/2dF.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "2dF Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_2dF_textures", - Version = 1 + Version = 2 }) local speck = asset.syncedResource({ @@ -24,7 +24,7 @@ local object = { Color = { 1.0, 1.0, 1.0 }, Opacity = 1.0, File = speck .. "/2dF.speck", - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", ColorMap = speck .. "/2dF.cmap", ColorOption = { "redshift", "proximity" }, ColorRange = { { 0.0, 0.075 }, { 1.0, 25.0 } }, diff --git a/data/assets/scene/digitaluniverse/2mass.asset b/data/assets/scene/digitaluniverse/2mass.asset index b27311229a..c27557c282 100644 --- a/data/assets/scene/digitaluniverse/2mass.asset +++ b/data/assets/scene/digitaluniverse/2mass.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "2MASS Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_2mass_textures", - Version = 1 + Version = 2 }) local speck = asset.syncedResource({ @@ -24,7 +24,7 @@ local object = { Color = { 1.0, 0.4, 0.2 }, Opacity = 1.0, File = speck .. "/2MASS.speck", - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", ColorMap = speck .. "/lss.cmap", ColorOption = { "redshift", "prox5Mpc" }, ColorRange = { { 0.0, 0.075 }, { 1.0, 50.0 } }, diff --git a/data/assets/scene/digitaluniverse/6dF.asset b/data/assets/scene/digitaluniverse/6dF.asset index 3f9b74256c..2843b142d4 100644 --- a/data/assets/scene/digitaluniverse/6dF.asset +++ b/data/assets/scene/digitaluniverse/6dF.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "6dF Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_6dF_textures", - Version = 1 + Version = 2 }) local speck = asset.syncedResource({ @@ -24,7 +24,7 @@ local object = { Color = { 1.0, 1.0, 0.0 }, Opacity = 1.0, File = speck .. "/6dF.speck", - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", ColorMap = speck .. "/6dF.cmap", ColorOption = { "redshift", "proximity" }, ColorRange = { { 0.0, 0.075 }, { 1.0, 10.0 } }, diff --git a/data/assets/scene/digitaluniverse/abell.asset b/data/assets/scene/digitaluniverse/abell.asset index 673f2f57ac..287eab6c52 100644 --- a/data/assets/scene/digitaluniverse/abell.asset +++ b/data/assets/scene/digitaluniverse/abell.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "Abell Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_abell_textures", - Version = 1 + Version = 2 }) local speck = asset.syncedResource({ @@ -25,7 +25,7 @@ local object = { Opacity = 1.0, --ColorMap = speck .. "/abell.cmap", File = speck .. "/abell.speck", - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", LabelFile = speck .. "/abell.label", TextColor = { 0.0, 0.8, 0.0, 1.0 }, TextSize = 22, diff --git a/data/assets/scene/digitaluniverse/quasars.asset b/data/assets/scene/digitaluniverse/quasars.asset index b24f034f7d..be9b11e59b 100644 --- a/data/assets/scene/digitaluniverse/quasars.asset +++ b/data/assets/scene/digitaluniverse/quasars.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "Quasars Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_quasars_textures", - Version = 1 + Version = 2 }) local speck = asset.syncedResource({ @@ -24,7 +24,7 @@ local object = { Color = { 1.0, 0.4, 0.2 }, Opacity = 0.95, File = speck .. "/quasars.speck", - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", Unit = "Mpc", ScaleFactor = 540.9, -- Fade in value in the same unit as "Unit" diff --git a/data/assets/scene/digitaluniverse/sdss.asset b/data/assets/scene/digitaluniverse/sdss.asset index 38563ed859..56d92df264 100644 --- a/data/assets/scene/digitaluniverse/sdss.asset +++ b/data/assets/scene/digitaluniverse/sdss.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "Sloan Digital Sky Survey Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_sloandss_textures", - Version = 1 + Version = 2 }) local speck = asset.syncedResource({ @@ -28,7 +28,7 @@ local object = { ColorMap = speck .. "/SDSSgals.cmap", ColorOption = { "redshift", "proximity" }, ColorRange = { { 0.0, 0.075 }, { 1.0, 50.0 } }, - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", Unit = "Mpc", -- Fade in value in the same unit as "Unit" FadeInDistances = { 220.0, 650.0 }, diff --git a/data/assets/scene/digitaluniverse/superclusters.asset b/data/assets/scene/digitaluniverse/superclusters.asset index d51868d921..5ce754caa7 100644 --- a/data/assets/scene/digitaluniverse/superclusters.asset +++ b/data/assets/scene/digitaluniverse/superclusters.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "Galaxy Superclusters Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_superclusters_textures", - Version = 1 + Version = 2 }) local speck = asset.syncedResource({ @@ -25,7 +25,7 @@ local object = { Color = { 1.0, 1.0, 1.0 }, Opacity = 0.65, File = speck .. "/superclust.speck", - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", LabelFile = speck .. "/superclust.label", TextColor = { 0.9, 0.9, 0.9, 1.0 }, ScaleFactor = 531.0, diff --git a/data/assets/scene/digitaluniverse/tully.asset b/data/assets/scene/digitaluniverse/tully.asset index 59d750c728..e8e515e22b 100644 --- a/data/assets/scene/digitaluniverse/tully.asset +++ b/data/assets/scene/digitaluniverse/tully.asset @@ -6,7 +6,7 @@ local textures = asset.syncedResource({ Name = "Tully Textures", Type = "HttpSynchronization", Identifier = "digitaluniverse_tully_textures", - Version = 2 + Version = 3 }) local speck = asset.syncedResource({ @@ -25,7 +25,7 @@ local tullyPoints = { Opacity = 0.99, ScaleFactor = 500.0, File = speck .. "/tully.speck", - Texture = textures .. "/point3.png", + Texture = textures .. "/point3A.png", --ColorMap = speck .. "/tully.cmap", ColorMap = speck .. "/lss.cmap", --ColorOption = { "proximity" }, diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index da42b36210..00b27c1516 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -814,21 +814,23 @@ void RenderableBillboardsCloud::renderBillboards(const RenderData& data, _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); _program->setUniform( _uniformCache.cameraLookup, - data.camera.lookUpVectorWorldSpace() + glm::vec3(data.camera.lookUpVectorWorldSpace()) ); _program->setUniform(_uniformCache.renderOption, _renderOption.value()); _program->setUniform(_uniformCache.modelMatrix, modelMatrix); _program->setUniform( _uniformCache.cameraViewProjectionMatrix, - glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix() + glm::mat4( + glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix() + ) ); _program->setUniform(_uniformCache.minBillboardSize, _billboardMinSize); // in pixels _program->setUniform(_uniformCache.maxBillboardSize, _billboardMaxSize); // in pixels _program->setUniform(_uniformCache.color, _pointColor); _program->setUniform(_uniformCache.alphaValue, _opacity); _program->setUniform(_uniformCache.scaleFactor, _scaleFactor); - _program->setUniform(_uniformCache.up, orthoUp); - _program->setUniform(_uniformCache.right, orthoRight); + _program->setUniform(_uniformCache.up, glm::vec3(orthoUp)); + _program->setUniform(_uniformCache.right, glm::vec3(orthoRight)); _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); _program->setUniform( diff --git a/modules/digitaluniverse/shaders/billboard_fs.glsl b/modules/digitaluniverse/shaders/billboard_fs.glsl index 4d08f6e912..0db1fa3fe4 100644 --- a/modules/digitaluniverse/shaders/billboard_fs.glsl +++ b/modules/digitaluniverse/shaders/billboard_fs.glsl @@ -39,7 +39,8 @@ Fragment getFragment() { vec4 textureColor = texture(spriteTexture, texCoord); - if (textureColor.a == 0.f || gs_colorMap.a == 0.f) { + if (textureColor.a == 0.f || gs_colorMap.a == 0.f || + ta == 0.f || fadeInValue == 0.f) { discard; } diff --git a/modules/digitaluniverse/shaders/billboard_gs.glsl b/modules/digitaluniverse/shaders/billboard_gs.glsl index d83e53b10f..a534d0f29f 100644 --- a/modules/digitaluniverse/shaders/billboard_gs.glsl +++ b/modules/digitaluniverse/shaders/billboard_gs.glsl @@ -30,16 +30,16 @@ layout(points) in; layout(triangle_strip, max_vertices = 4) out; uniform float scaleFactor; -uniform dvec3 up; -uniform dvec3 right; +uniform vec3 up; +uniform vec3 right; uniform dvec3 cameraPosition; // in world space (no SGCT View was considered) -uniform dvec3 cameraLookUp; // in world space (no SGCT View was considered) +uniform vec3 cameraLookUp; // in world space (no SGCT View was considered) uniform int renderOption; uniform vec2 screenSize; uniform float maxBillboardSize; uniform float minBillboardSize; -uniform dmat4 cameraViewProjectionMatrix; +uniform mat4 cameraViewProjectionMatrix; uniform dmat4 modelMatrix; uniform float correctionSizeFactor; @@ -94,11 +94,11 @@ void main() { dvec4 dpos = dvec4(dvec3(pos.xyz) * unit, 1.0); dpos = modelMatrix * dpos; - double scaleMultiply = exp(scaleFactor * 0.10); + float scaleMultiply = exp(scaleFactor * 0.10f); scaleMultiply = hasDvarScaling ? dvarScaling[0] * scaleMultiply : scaleMultiply; - dvec3 scaledRight = dvec3(0.0); - dvec3 scaledUp = dvec3(0.0); + vec3 scaledRight = vec3(0.f); + vec3 scaledUp = vec3(0.f); vec4 initialPosition, secondPosition, thirdPosition, crossCorner; @@ -106,15 +106,15 @@ void main() { scaledRight = scaleMultiply * right * 0.5f; scaledUp = scaleMultiply * up * 0.5f; } else if (renderOption == 1) { - dvec3 normal = normalize(cameraPosition - dpos.xyz); - dvec3 newRight = normalize(cross(cameraLookUp, normal)); - dvec3 newUp = cross(normal, newRight); + vec3 normal = vec3(normalize(cameraPosition - dpos.xyz)); + vec3 newRight = normalize(cross(cameraLookUp, normal)); + vec3 newUp = cross(normal, newRight); if (!enabledRectSizeControl) { double distCamera = length(cameraPosition - dpos.xyz); float expVar = float(-distCamera) / pow(10.f, correctionSizeEndDistance); - double factorVar = double(pow(10, correctionSizeFactor)); - scaleMultiply *= 1.0 / (1.0 + factorVar * double(exp(expVar))); + float factorVar = pow(10.f, correctionSizeFactor); + scaleMultiply *= 1.f / (1.f + factorVar * exp(expVar)); } scaledRight = scaleMultiply * newRight * 0.5f; @@ -122,11 +122,13 @@ void main() { } if (enabledRectSizeControl) { - initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); + initialPosition = z_normalization(cameraViewProjectionMatrix * + vec4(vec3(dpos.xyz) - scaledRight - scaledUp, dpos.w)); + vs_screenSpaceDepth = initialPosition.w; - crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * - dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); + + crossCorner = z_normalization(cameraViewProjectionMatrix * + vec4(vec3(dpos.xyz) + scaledUp + scaledRight, dpos.w)); // Testing size for rectangular viewport: vec2 halfViewSize = vec2(screenSize.x, screenSize.y) * 0.5f; @@ -158,27 +160,17 @@ void main() { } } } - - // initialPosition = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz - scaledRight - scaledUp, dpos.w))); - // vs_screenSpaceDepth = initialPosition.w; - // secondPosition = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz + scaledRight - scaledUp, dpos.w))); - // crossCorner = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz + scaledUp + scaledRight, dpos.w))); - // thirdPosition = z_normalization(vec4(cameraViewProjectionMatrix * - // dvec4(dpos.xyz + scaledUp - scaledRight, dpos.w))); // Saving one matrix multiplication: - dvec4 dposClip = cameraViewProjectionMatrix * dpos; - dvec4 scaledRightClip = cameraViewProjectionMatrix * dvec4(scaledRight, 0.0); - dvec4 scaledUpClip = cameraViewProjectionMatrix * dvec4(scaledUp, 0.0); + vec4 dposClip = cameraViewProjectionMatrix * vec4(dpos); + vec4 scaledRightClip = cameraViewProjectionMatrix * vec4(scaledRight, 0.0); + vec4 scaledUpClip = cameraViewProjectionMatrix * vec4(scaledUp, 0.0); - initialPosition = z_normalization(vec4(dposClip - scaledRightClip - scaledUpClip)); + initialPosition = z_normalization(dposClip - scaledRightClip - scaledUpClip); vs_screenSpaceDepth = initialPosition.w; - secondPosition = z_normalization(vec4(dposClip + scaledRightClip - scaledUpClip)); - crossCorner = z_normalization(vec4(dposClip + scaledUpClip + scaledRightClip)); - thirdPosition = z_normalization(vec4(dposClip + scaledUpClip - scaledRightClip)); + secondPosition = z_normalization(dposClip + scaledRightClip - scaledUpClip); + crossCorner = z_normalization(dposClip + scaledUpClip + scaledRightClip); + thirdPosition = z_normalization(dposClip + scaledUpClip - scaledRightClip); // Build primitive texCoord = corners[3]; From b591af3c2a1697b919c73e5ecc7dceddb24ea044 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 11 Oct 2019 18:11:22 -0400 Subject: [PATCH 05/42] Initial tests for performance improvements. --- modules/galaxy/shaders/galaxyraycast.glsl | 19 ++++++++------- shaders/framebuffer/raycastframebuffer.frag | 26 ++++++++++----------- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/modules/galaxy/shaders/galaxyraycast.glsl b/modules/galaxy/shaders/galaxyraycast.glsl index a16188aa5d..dab687e3ca 100644 --- a/modules/galaxy/shaders/galaxyraycast.glsl +++ b/modules/galaxy/shaders/galaxyraycast.glsl @@ -29,17 +29,18 @@ uniform float absorptionMultiply#{id} = 50.0; uniform float emissionMultiply#{id} = 1500.0; uniform sampler3D galaxyTexture#{id}; -void sample#{id}(vec3 samplePos, +void sample#{id}( + vec3 samplePos, vec3 dir, inout vec3 accumulatedColor, inout vec3 accumulatedAlpha, - inout float stepSize) - { + inout float stepSize + ) { vec3 aspect = aspect#{id}; stepSize = maxStepSize#{id} / length(dir / aspect); //Early ray termination on black parts of the data - vec3 normalizedPos = samplePos*2.0 - 1.0; + vec3 normalizedPos = samplePos * 2.f - 1.f; if (normalizedPos.x * normalizedPos.x + normalizedPos.y * normalizedPos.y > 0.7) { return; } @@ -51,12 +52,12 @@ void sample#{id}(vec3 samplePos, sampledColor = sampledColor*sampledColor; // Fudge for the dust "spreading" - sampledColor.a = clamp(sampledColor.a, 0.0, 1.0); - sampledColor.a = pow(sampledColor.a, 0.7); + sampledColor.a = clamp(sampledColor.a, 0.f, 1.f); + sampledColor.a = pow(sampledColor.a, 0.7f); // Absorption probability float scaledDensity = sampledColor.a * stepSize * absorptionMultiply#{id}; - vec3 alphaTint = vec3(0.3, 0.54, 0.85); + vec3 alphaTint = vec3(0.3f, 0.54f, 0.85f); vec3 absorption = alphaTint * scaledDensity; // Extinction @@ -67,10 +68,10 @@ void sample#{id}(vec3 samplePos, accumulatedColor.rgb += sampledColor.rgb * stepSize * emissionMultiply#{id} * opacityCoefficient#{id}; - vec3 oneMinusFrontAlpha = vec3(1.0) - accumulatedAlpha; + vec3 oneMinusFrontAlpha = vec3(1.f) - accumulatedAlpha; accumulatedAlpha += oneMinusFrontAlpha * sampledColor.rgb * opacityCoefficient#{id}; } float stepSize#{id}(vec3 samplePos, vec3 dir) { - return maxStepSize#{id} * length(dir * 1.0 / aspect#{id}); + return maxStepSize#{id} * length(dir * 1.f / aspect#{id}); } diff --git a/shaders/framebuffer/raycastframebuffer.frag b/shaders/framebuffer/raycastframebuffer.frag index 6a949b4cc9..b5a972cff8 100644 --- a/shaders/framebuffer/raycastframebuffer.frag +++ b/shaders/framebuffer/raycastframebuffer.frag @@ -45,7 +45,7 @@ uniform vec2 windowSize; out vec4 finalColor; #define ALPHA_LIMIT 0.99 -#define RAYCAST_MAX_STEPS 1000 +#define RAYCAST_MAX_STEPS 480 #include <#{getEntryPath}> @@ -55,7 +55,7 @@ void main() { vec4 exitColorTexture = texture(exitColorTexture, texCoord); // If we don't have an exit, discard the ray - if (exitColorTexture.a < 1.0 || exitColorTexture.rgb == vec3(0.0)) { + if (exitColorTexture.a < 1.f || exitColorTexture.rgb == vec3(0.f)) { discard; } @@ -63,13 +63,13 @@ void main() { vec3 exitPos = exitColorTexture.rgb; float exitDepth = denormalizeFloat(texture(exitDepthTexture, texCoord).x); - float jitterFactor = 0.5 + 0.5 * rand(gl_FragCoord.xy); // should be between 0.5 and 1.0 + float jitterFactor = 0.5f + 0.5f * rand(gl_FragCoord.xy); // should be between 0.5 and 1.0 vec3 entryPos; float entryDepth; getEntry(entryPos, entryDepth); // If we don't have an entry, discard the ray - if (entryPos == vec3(0.0)) { + if (entryPos == vec3(0.f)) { discard; } @@ -80,21 +80,21 @@ void main() { float raycastDepth = length(diff); float geoDepth = denormalizeFloat(texelFetch(mainDepthTexture, ivec2(gl_FragCoord), 0).x); - float geoRatio = clamp((geoDepth - entryDepth) / (exitDepth - entryDepth), 0.0, 1.0); + float geoRatio = clamp((geoDepth - entryDepth) / (exitDepth - entryDepth), 0.f, 1.f); raycastDepth = geoRatio * raycastDepth; - float currentDepth = 0.0; + float currentDepth = 0.f; float nextStepSize = stepSize#{id}(position, direction); float currentStepSize; - float previousJitterDistance = 0.0; + float previousJitterDistance = 0.f; int nSteps = 0; int sampleIndex = 0; - float opacityDecay = 1.0; + float opacityDecay = 1.f; - vec3 accumulatedColor = vec3(0.0); - vec3 accumulatedAlpha = vec3(0.0); + vec3 accumulatedColor = vec3(0.f); + vec3 accumulatedAlpha = vec3(0.f); for (nSteps = 0; @@ -102,7 +102,7 @@ void main() { accumulatedAlpha.b < ALPHA_LIMIT) && nSteps < RAYCAST_MAX_STEPS; ++nSteps) { - if (nextStepSize < raycastDepth / 10000000000.0) { + if (nextStepSize < raycastDepth / 10000000000.f) { break; } @@ -110,7 +110,7 @@ void main() { currentDepth += currentStepSize; float jitteredStepSize = currentStepSize * jitterFactor; - vec3 jitteredPosition = position + direction*jitteredStepSize; + vec3 jitteredPosition = position + direction * jitteredStepSize; position += direction * currentStepSize; sample#{id}(jitteredPosition, direction, accumulatedColor, accumulatedAlpha, nextStepSize); @@ -122,7 +122,7 @@ void main() { nextStepSize = min(nextStepSize, maxStepSize); } - finalColor = vec4(accumulatedColor, (accumulatedAlpha.r + accumulatedAlpha.g + accumulatedAlpha.b) / 3); + finalColor = vec4(accumulatedColor, (accumulatedAlpha.r + accumulatedAlpha.g + accumulatedAlpha.b) / 3.f); finalColor.rgb /= finalColor.a ; gl_FragDepth = normalizeFloat(entryDepth); From 0fce6a8d268949b6855d5e67391b52e70d29ae52 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Sun, 10 Nov 2019 14:17:23 -0500 Subject: [PATCH 06/42] Super-fast volume (aka Downscaled Volume Rendering). --- .../scene/milkyway/milkyway/volume.asset | 4 +- .../openspace/rendering/framebufferrenderer.h | 11 + include/openspace/rendering/volumeraycaster.h | 19 ++ modules/galaxy/rendering/renderablegalaxy.cpp | 14 ++ modules/galaxy/rendering/renderablegalaxy.h | 2 + shaders/framebuffer/hdrAndFiltering.frag | 1 - .../framebuffer/mergeDownscaledVolume.frag | 35 ++++ .../framebuffer/mergeDownscaledVolume.vert | 33 +++ shaders/framebuffer/raycastframebuffer.frag | 5 +- src/rendering/framebufferrenderer.cpp | 193 +++++++++++++++++- 10 files changed, 310 insertions(+), 7 deletions(-) create mode 100644 shaders/framebuffer/mergeDownscaledVolume.frag create mode 100644 shaders/framebuffer/mergeDownscaledVolume.vert diff --git a/data/assets/scene/milkyway/milkyway/volume.asset b/data/assets/scene/milkyway/milkyway/volume.asset index 0d1537d45e..78195a1b5c 100644 --- a/data/assets/scene/milkyway/milkyway/volume.asset +++ b/data/assets/scene/milkyway/milkyway/volume.asset @@ -24,7 +24,9 @@ local MilkyWayVolumeGalaxy = { Type = "Volume", Filename = data .. "/MilkyWayRGBAVolume1024x1024x128.raw", Dimensions = {1024, 1024, 128}, - Size = {1.2E21, 1.2E21, 0.15E21} + Size = {1.2E21, 1.2E21, 0.15E21}, + Steps = 480, + Downscale = 0.5, }, Points = { Type = "Points", diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index a49568fe17..4529fd60a4 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -70,6 +70,7 @@ public: void updateDeferredcastData(); void updateHDRAndFiltering(); void updateFXAA(); + void updateDownscaledVolume(); void setResolution(glm::ivec2 res) override; void setHDRExposure(float hdrExposure) override; @@ -110,6 +111,8 @@ private: void resolveMSAA(float blackoutFactor); void applyTMO(float blackoutFactor); void applyFXAA(); + void updateDownscaleColorTexture(); + void writeDownscaledVolume(); std::map _raycastData; RaycasterProgObjMap _exitPrograms; @@ -122,10 +125,12 @@ private: std::unique_ptr _hdrFilteringProgram; std::unique_ptr _tmoProgram; std::unique_ptr _fxaaProgram; + std::unique_ptr _downscaledVolumeProgram; UniformCache(hdrFeedingTexture, blackoutFactor, hdrExposure, gamma, Hue, Saturation, Value) _hdrUniformCache; UniformCache(renderedTexture, inverseScreenSize) _fxaaUniformCache; + UniformCache(downscaledRenderedVolume) _writeDownscaledVolumeUniformCache; GLint _defaultFBO; GLuint _screenQuad; @@ -157,6 +162,12 @@ private: GLuint fxaaTexture; } _fxaaBuffers; + struct { + GLuint framebuffer; + GLuint colorTexture; + float currentDownscaleFactor = 1.f; + } _downscaleVolumeRendering; + unsigned int _pingPongIndex = 0u; bool _dirtyDeferredcastData; diff --git a/include/openspace/rendering/volumeraycaster.h b/include/openspace/rendering/volumeraycaster.h index f8ed000553..687a5f335a 100644 --- a/include/openspace/rendering/volumeraycaster.h +++ b/include/openspace/rendering/volumeraycaster.h @@ -128,6 +128,25 @@ public: * helper file) which should be a prefix to all symbols defined by the helper */ virtual std::string helperPath() const = 0; + + virtual void setMaxSteps(int nsteps) { _rayCastMaxSteps = nsteps; }; + + virtual const int maxSteps() const { return _rayCastMaxSteps; }; + + virtual void setDownscaleRender(float value) { _downscaleRenderConst = value; }; + + virtual const float downscaleRender() const { return _downscaleRenderConst; }; + +private: + /** + * Maximum number of integration steps to be executed by the volume integrator. + */ + int _rayCastMaxSteps = 1000; + + /** + * Enable and set the downscale rendering of the volume. Used to improve performance. + */ + float _downscaleRenderConst = 1.0f; }; } // namespace openspace diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 1d88c2da23..758ab082a1 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -224,6 +224,18 @@ namespace openspace { LERROR("No volume dimensions specified."); } + if (volumeDictionary.hasKey("Steps")) { + _rayCastSteps = static_cast(volumeDictionary.value("Steps")); + } + else { + LINFO("Number of raycasting steps not specified for Milkway Galaxy." + " Using default value."); + } + + if (volumeDictionary.hasKey("Downscale")) { + _downScaleVolumeRendering = volumeDictionary.value("Downscale"); + } + if (!dictionary.hasKeyAndValue("Points")) { LERROR("No points dictionary specified."); } @@ -470,6 +482,8 @@ void RenderableGalaxy::update(const UpdateData& data) { volumeTransform[3] += translation; _pointTransform[3] += translation; + _raycaster->setDownscaleRender(_downScaleVolumeRendering); + _raycaster->setMaxSteps(_rayCastSteps); _raycaster->setStepSize(_stepSize); _raycaster->setAspect(_aspect); _raycaster->setModelTransform(volumeTransform); diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index 0b49d848c4..8346820b99 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -79,6 +79,8 @@ private: glm::ivec3 _volumeDimensions; std::string _pointsFilename; std::string _pointSpreadFunctionTexturePath; + int _rayCastSteps = 1000; + float _downScaleVolumeRendering = 1.f; std::unique_ptr _raycaster; std::unique_ptr>> _volume; diff --git a/shaders/framebuffer/hdrAndFiltering.frag b/shaders/framebuffer/hdrAndFiltering.frag index b22ebd9bc4..0e2b3b2090 100644 --- a/shaders/framebuffer/hdrAndFiltering.frag +++ b/shaders/framebuffer/hdrAndFiltering.frag @@ -38,7 +38,6 @@ uniform float Hue; uniform float Saturation; uniform float Value; uniform float Lightness; -uniform int nAaSamples; uniform sampler2D hdrFeedingTexture; diff --git a/shaders/framebuffer/mergeDownscaledVolume.frag b/shaders/framebuffer/mergeDownscaledVolume.frag new file mode 100644 index 0000000000..f34a300742 --- /dev/null +++ b/shaders/framebuffer/mergeDownscaledVolume.frag @@ -0,0 +1,35 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2019 * + * * + * 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__ + +layout (location = 0) out vec4 finalColor; + +uniform sampler2D downscaledRenderedVolume; + +in vec2 texCoord; + +void main() { + finalColor = texture(downscaledRenderedVolume, texCoord); +} diff --git a/shaders/framebuffer/mergeDownscaledVolume.vert b/shaders/framebuffer/mergeDownscaledVolume.vert new file mode 100644 index 0000000000..f737e51882 --- /dev/null +++ b/shaders/framebuffer/mergeDownscaledVolume.vert @@ -0,0 +1,33 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2019 * + * * + * 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__ + +layout(location = 0) in vec4 position; +out vec2 texCoord; + +void main() { + texCoord = 0.5 + position.xy * 0.5; + gl_Position = position; +} diff --git a/shaders/framebuffer/raycastframebuffer.frag b/shaders/framebuffer/raycastframebuffer.frag index b5a972cff8..120bcdd2b8 100644 --- a/shaders/framebuffer/raycastframebuffer.frag +++ b/shaders/framebuffer/raycastframebuffer.frag @@ -32,6 +32,8 @@ uniform bool insideRaycaster; uniform vec3 cameraPosInRaycaster; uniform vec2 windowSize; +uniform int rayCastSteps; + #include "blending.glsl" #include "rand.glsl" #include "floatoperations.glsl" @@ -45,7 +47,6 @@ uniform vec2 windowSize; out vec4 finalColor; #define ALPHA_LIMIT 0.99 -#define RAYCAST_MAX_STEPS 480 #include <#{getEntryPath}> @@ -99,7 +100,7 @@ void main() { for (nSteps = 0; (accumulatedAlpha.r < ALPHA_LIMIT || accumulatedAlpha.g < ALPHA_LIMIT || - accumulatedAlpha.b < ALPHA_LIMIT) && nSteps < RAYCAST_MAX_STEPS; + accumulatedAlpha.b < ALPHA_LIMIT) && nSteps < rayCastSteps; ++nSteps) { if (nextStepSize < raycastDepth / 10000000000.f) { diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 2007f13a53..b6ce5df96e 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -59,6 +59,10 @@ namespace { "renderedTexture", "inverseScreenSize" }; + constexpr const std::array DownscaledVolumeUniformNames = { + "downscaledRenderedVolume" + }; + constexpr const char* ExitFragmentShaderPath = "${SHADERS}/framebuffer/exitframebuffer.frag"; constexpr const char* RaycastFragmentShaderPath = @@ -184,6 +188,10 @@ void FramebufferRenderer::initialize() { glGenFramebuffers(1, &_fxaaBuffers.fxaaFramebuffer); glGenTextures(1, &_fxaaBuffers.fxaaTexture); + // DownscaleVolumeRendering + glGenFramebuffers(1, &_downscaleVolumeRendering.framebuffer); + glGenTextures(1, &_downscaleVolumeRendering.colorTexture); + // Allocate Textures/Buffers Memory updateResolution(); @@ -307,11 +315,29 @@ void FramebufferRenderer::initialize() { LERROR("FXAA framebuffer is not complete"); } + //================================================// + //===== Downscale Volume Rendering Buffers =====// + //================================================// + glBindFramebuffer(GL_FRAMEBUFFER, _downscaleVolumeRendering.framebuffer); + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + _downscaleVolumeRendering.colorTexture, + 0 + ); + + status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + LERROR("Downscale Volume Rendering framebuffer is not complete"); + } + + // JCC: Moved to here to avoid NVidia: "Program/shader state performance warning" // Building programs updateHDRAndFiltering(); updateFXAA(); updateDeferredcastData(); + updateDownscaledVolume(); // Sets back to default FBO glBindFramebuffer(GL_FRAMEBUFFER, _defaultFBO); @@ -326,6 +352,11 @@ void FramebufferRenderer::initialize() { _fxaaUniformCache, FXAAUniformNames ); + ghoul::opengl::updateUniformLocations( + *_downscaledVolumeProgram, + _writeDownscaledVolumeUniformCache, + DownscaledVolumeUniformNames + ); global::raycasterManager.addListener(*this); global::deferredcasterManager.addListener(*this); @@ -342,6 +373,7 @@ void FramebufferRenderer::deinitialize() { glDeleteFramebuffers(1, &_hdrBuffers.hdrFilteringFramebuffer); glDeleteFramebuffers(1, &_fxaaBuffers.fxaaFramebuffer); glDeleteFramebuffers(1, &_pingPongBuffers.framebuffer); + glDeleteFramebuffers(1, &_downscaleVolumeRendering.framebuffer); glDeleteTextures(1, &_gBuffers.colorTexture); glDeleteTextures(1, &_gBuffers.depthTexture); @@ -350,7 +382,8 @@ void FramebufferRenderer::deinitialize() { glDeleteTextures(1, &_fxaaBuffers.fxaaTexture); glDeleteTextures(1, &_gBuffers.positionTexture); glDeleteTextures(1, &_gBuffers.normalTexture); - + glDeleteTextures(1, &_downscaleVolumeRendering.colorTexture); + glDeleteTextures(1, &_pingPongBuffers.colorTexture[1]); glDeleteTextures(1, &_exitColorTexture); @@ -447,6 +480,90 @@ void FramebufferRenderer::applyFXAA() { _fxaaProgram->deactivate(); } +void FramebufferRenderer::updateDownscaleColorTexture() { + glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.colorTexture); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA32F, + _resolution.x * _downscaleVolumeRendering.currentDownscaleFactor, + _resolution.y * _downscaleVolumeRendering.currentDownscaleFactor, + 0, + GL_RGBA, + GL_FLOAT, + nullptr + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +} + +void FramebufferRenderer::writeDownscaledVolume() { + const bool doPerformanceMeasurements = global::performanceManager.isEnabled(); + std::unique_ptr perfInternal; + + if (doPerformanceMeasurements) { + perfInternal = std::make_unique( + "FramebufferRenderer::render::writeDownscaledVolume" + ); + } + + // Saving current OpenGL state + GLboolean blendEnabled = glIsEnabledi(GL_BLEND, 0); + + GLenum blendEquationRGB; + glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); + + GLenum blendEquationAlpha; + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); + + GLenum blendDestAlpha; + glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); + + GLenum blendDestRGB; + glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); + + GLenum blendSrcAlpha; + glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); + + GLenum blendSrcRGB; + glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); + + glEnablei(GL_BLEND, 0); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + + _downscaledVolumeProgram->activate(); + + ghoul::opengl::TextureUnit downscaledTextureUnit; + downscaledTextureUnit.activate(); + glBindTexture( + GL_TEXTURE_2D, + _downscaleVolumeRendering.colorTexture + ); + + _downscaledVolumeProgram->setUniform( + _writeDownscaledVolumeUniformCache.downscaledRenderedVolume, + downscaledTextureUnit + ); + + glEnablei(GL_BLEND, 0); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + + glBindVertexArray(_screenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); + glBindVertexArray(0); + + _downscaledVolumeProgram->deactivate(); + + // Restores blending state + glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); + glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); + + if (!blendEnabled) { + glDisablei(GL_BLEND, 0); + } + +} + void FramebufferRenderer::update() { if (_dirtyResolution) { updateResolution(); @@ -480,6 +597,16 @@ void FramebufferRenderer::update() { ); } + if (_downscaledVolumeProgram->isDirty()) { + _downscaledVolumeProgram->rebuildFromFile(); + + ghoul::opengl::updateUniformLocations( + *_downscaledVolumeProgram, + _writeDownscaledVolumeUniformCache, + DownscaledVolumeUniformNames + ); + } + using K = VolumeRaycaster*; using V = std::unique_ptr; for (const std::pair& program : _exitPrograms) { @@ -639,6 +766,23 @@ void FramebufferRenderer::updateResolution() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + // Downscale Volume Rendering + glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.colorTexture); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA32F, + _resolution.x * _downscaleVolumeRendering.currentDownscaleFactor, + _resolution.y * _downscaleVolumeRendering.currentDownscaleFactor, + 0, + GL_RGBA, + GL_FLOAT, + nullptr + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + + // Volume Rendering Textures glBindTexture(GL_TEXTURE_2D, _exitColorTexture); glTexImage2D( @@ -822,6 +966,17 @@ void FramebufferRenderer::updateFXAA() { //_fxaaProgram->setIgnoreUniformLocationError(IgnoreError::Yes); } +void FramebufferRenderer::updateDownscaledVolume() { + _downscaledVolumeProgram = ghoul::opengl::ProgramObject::Build( + "Write Downscaled Volume Program", + absPath("${SHADERS}/framebuffer/mergeDownscaledVolume.vert"), + absPath("${SHADERS}/framebuffer/mergeDownscaledVolume.frag") + ); + using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; + //_downscaledVolumeProgram->setIgnoreSubroutineUniformLocationError(IgnoreError::Yes); + //_downscaledVolumeProgram->setIgnoreUniformLocationError(IgnoreError::Yes); +} + void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFactor) { // Set OpenGL default rendering state glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_defaultFBO); @@ -945,7 +1100,20 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector exitProgram->deactivate(); } - glBindFramebuffer(GL_FRAMEBUFFER, _gBuffers.framebuffer); + if (raycaster->downscaleRender() != 1.f) { + float scaleDown = raycaster->downscaleRender(); + glBindFramebuffer(GL_FRAMEBUFFER, _downscaleVolumeRendering.framebuffer); + glViewport(0, 0, _resolution.x * scaleDown, _resolution.y * scaleDown); + if (_downscaleVolumeRendering.currentDownscaleFactor != scaleDown) { + _downscaleVolumeRendering.currentDownscaleFactor = scaleDown; + updateDownscaleColorTexture(); + } + glClear(GL_COLOR_BUFFER_BIT); + } + else { + glBindFramebuffer(GL_FRAMEBUFFER, _gBuffers.framebuffer); + } + glm::vec3 cameraPosition; bool isCameraInside = raycaster->isCameraInside( raycasterTask.renderData, @@ -977,6 +1145,8 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector } if (raycastProgram) { + raycastProgram->setUniform("rayCastSteps", raycaster->maxSteps()); + raycaster->preRaycast(_raycastData[raycaster], *raycastProgram); ghoul::opengl::TextureUnit exitColorTextureUnit; @@ -994,7 +1164,16 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector glBindTexture(GL_TEXTURE_2D, _gBuffers.depthTexture); raycastProgram->setUniform("mainDepthTexture", mainDepthTextureUnit); - raycastProgram->setUniform("windowSize", static_cast(_resolution)); + if (raycaster->downscaleRender() != 1.f) { + float scaleDown = raycaster->downscaleRender(); + raycastProgram->setUniform( + "windowSize", + glm::vec2(_resolution.x * scaleDown, _resolution.y * scaleDown) + ); + } + else { + raycastProgram->setUniform("windowSize", static_cast(_resolution)); + } glDisable(GL_DEPTH_TEST); glDepthMask(false); @@ -1015,6 +1194,14 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector else { LWARNING("Raycaster is not attached when trying to perform raycaster task"); } + + if (raycaster->downscaleRender() != 1.f) { + float scaleDown = raycaster->downscaleRender(); + glViewport(0, 0, _resolution.x, _resolution.y); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _gBuffers.framebuffer); + writeDownscaledVolume(); + + } } } From 86bd05276ff78a78340efacb3809820750880fa4 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 11 Nov 2019 13:29:32 -0500 Subject: [PATCH 07/42] Added slide control for downscaling factor. --- modules/galaxy/rendering/renderablegalaxy.cpp | 12 ++++++++++++ modules/galaxy/rendering/renderablegalaxy.h | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 758ab082a1..8597c7a5e0 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -117,6 +117,13 @@ namespace { "Enabled points", "" // @TODO Missing documentation }; + + constexpr openspace::properties::Property::PropertyInfo DownscaleVolumeRenderingInfo = { + "Downscale", + "Downscale Factor Volume Rendering", + "This value set the downscaling factor" + " when rendering the current volume." + }; } // namespace namespace openspace { @@ -135,6 +142,7 @@ namespace openspace { , _enabledPointsRatio(EnabledPointsRatioInfo, 0.5f, 0.01f, 1.0f) , _translation(TranslationInfo, glm::vec3(0.f), glm::vec3(0.f), glm::vec3(1.f)) , _rotation(RotationInfo, glm::vec3(0.f), glm::vec3(0.f), glm::vec3(6.28f)) + , _downScaleVolumeRendering(DownscaleVolumeRenderingInfo, 1.f, 0.1f, 1.f) { dictionary.getValue("VolumeRenderingEnabled", _volumeRenderingEnabled); dictionary.getValue("StarRenderingEnabled", _starRenderingEnabled); @@ -232,6 +240,9 @@ namespace openspace { " Using default value."); } + _downScaleVolumeRendering.setVisibility( + openspace::properties::Property::Visibility::Developer + ); if (volumeDictionary.hasKey("Downscale")) { _downScaleVolumeRendering = volumeDictionary.value("Downscale"); } @@ -319,6 +330,7 @@ void RenderableGalaxy::initializeGL() { addProperty(_enabledPointsRatio); addProperty(_translation); addProperty(_rotation); + addProperty(_downScaleVolumeRendering); // initialize points. if (!_pointsFilename.empty()) { diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index 8346820b99..ea7ddcb824 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -71,6 +71,7 @@ private: properties::FloatProperty _enabledPointsRatio; properties::Vec3Property _translation; properties::Vec3Property _rotation; + properties::FloatProperty _downScaleVolumeRendering; std::unique_ptr _pointSpreadFunctionTexture; std::unique_ptr _pointSpreadFunctionFile; @@ -80,7 +81,6 @@ private: std::string _pointsFilename; std::string _pointSpreadFunctionTexturePath; int _rayCastSteps = 1000; - float _downScaleVolumeRendering = 1.f; std::unique_ptr _raycaster; std::unique_ptr>> _volume; From 6ca304724759d8d9e3f267d7571f68a29f98e922 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 11 Nov 2019 14:39:28 -0500 Subject: [PATCH 08/42] Updated ToyVolume. Add downscaling controls. --- .../rendering/renderabletoyvolume.cpp | 29 +++++++++++++++++++ .../toyvolume/rendering/renderabletoyvolume.h | 3 ++ openspace.cfg | 2 +- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/modules/toyvolume/rendering/renderabletoyvolume.cpp b/modules/toyvolume/rendering/renderabletoyvolume.cpp index ccb5018780..a5c37bf4e2 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.cpp +++ b/modules/toyvolume/rendering/renderabletoyvolume.cpp @@ -29,8 +29,10 @@ #include #include #include +#include namespace { + constexpr const char* _loggerCat = "Renderable ToyVolume"; constexpr openspace::properties::Property::PropertyInfo SizeInfo = { "Size", "Size", @@ -66,6 +68,13 @@ namespace { "Color", "" // @TODO Missing documentation }; + + constexpr openspace::properties::Property::PropertyInfo DownscaleVolumeRenderingInfo = { + "Downscale", + "Downscale Factor Volume Rendering", + "This value set the downscaling factor" + " when rendering the current volume." + }; } // namespace namespace openspace { @@ -78,6 +87,7 @@ RenderableToyVolume::RenderableToyVolume(const ghoul::Dictionary& dictionary) , _translation(TranslationInfo, glm::vec3(0.f), glm::vec3(0.f), glm::vec3(10.f)) , _rotation(RotationInfo, glm::vec3(0.f, 0.f, 0.f), glm::vec3(0), glm::vec3(6.28f)) , _color(ColorInfo, glm::vec4(1.f, 0.f, 0.f, 0.1f), glm::vec4(0.f), glm::vec4(1.f)) + , _downScaleVolumeRendering(DownscaleVolumeRenderingInfo, 1.f, 0.1f, 1.f) { if (dictionary.hasKeyAndValue(ScalingExponentInfo.identifier)) { _scalingExponent = static_cast( @@ -104,6 +114,22 @@ RenderableToyVolume::RenderableToyVolume(const ghoul::Dictionary& dictionary) if (dictionary.hasKeyAndValue(StepSizeInfo.identifier)) { _stepSize = static_cast(dictionary.value(StepSizeInfo.identifier)); } + + _downScaleVolumeRendering.setVisibility( + openspace::properties::Property::Visibility::Developer + ); + if (dictionary.hasKey("Downscale")) { + _downScaleVolumeRendering = dictionary.value("Downscale"); + } + + if (dictionary.hasKey("Steps")) { + _rayCastSteps = static_cast(dictionary.value("Steps")); + } + else { + LINFO("Number of raycasting steps not specified for ToyVolume." + " Using default value."); + } + } RenderableToyVolume::~RenderableToyVolume() {} @@ -131,6 +157,7 @@ void RenderableToyVolume::initializeGL() { addProperty(_translation); addProperty(_rotation); addProperty(_color); + addProperty(_downScaleVolumeRendering); } void RenderableToyVolume::deinitializeGL() { @@ -167,6 +194,8 @@ void RenderableToyVolume::update(const UpdateData& data) { _raycaster->setStepSize(_stepSize); _raycaster->setModelTransform(transform); _raycaster->setTime(data.time.j2000Seconds()); + _raycaster->setDownscaleRender(_downScaleVolumeRendering); + _raycaster->setMaxSteps(_rayCastSteps); } } diff --git a/modules/toyvolume/rendering/renderabletoyvolume.h b/modules/toyvolume/rendering/renderabletoyvolume.h index 8c1b0a36e0..d946bd21f9 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.h +++ b/modules/toyvolume/rendering/renderabletoyvolume.h @@ -55,8 +55,11 @@ private: properties::Vec3Property _translation; properties::Vec3Property _rotation; properties::Vec4Property _color; + properties::FloatProperty _downScaleVolumeRendering; std::unique_ptr _raycaster; + + int _rayCastSteps = 1000; }; } // namespace openspace diff --git a/openspace.cfg b/openspace.cfg index b47a47aa89..996fa99556 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -27,7 +27,7 @@ SGCTConfig = sgct.config.single{} -- SGCTConfig = sgct.config.fisheye{1024, 1024} -- A 4k fisheye rendering in a 1024x1024 window --- SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27} +SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27} -- Streaming OpenSpace via Spout to OBS -- SGCTConfig = sgct.config.single{2560, 1440, shared=true, name="WV_OBS_SPOUT1"} From 7e8cae4a515e1c524632611f25e794ce9e8b0895 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 11 Nov 2019 14:48:35 -0500 Subject: [PATCH 09/42] Improved volume border color. --- src/rendering/framebufferrenderer.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 39a85fe1fd..f45c618b76 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -793,6 +793,8 @@ void FramebufferRenderer::updateResolution() { ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + float volumeBorderColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, volumeBorderColor); // Volume Rendering Textures From caa02ca20ac68c5564a21ecb7e985d602807b78c Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Tue, 12 Nov 2019 17:19:23 -0500 Subject: [PATCH 10/42] Clean up. Added the raycasting number of steps as a slider for user's control. --- modules/galaxy/rendering/renderablegalaxy.cpp | 21 ++++++++++++++----- modules/galaxy/rendering/renderablegalaxy.h | 2 +- openspace.cfg | 2 +- shaders/framebuffer/raycastframebuffer.frag | 4 ++-- src/rendering/framebufferrenderer.cpp | 6 +++--- 5 files changed, 23 insertions(+), 12 deletions(-) diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 8597c7a5e0..9dfe003559 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -124,6 +124,12 @@ namespace { "This value set the downscaling factor" " when rendering the current volume." }; + + constexpr openspace::properties::Property::PropertyInfo NumberOfRayCastingStepsInfo = { + "Steps", + "Number of RayCasting Steps", + "This value set the number of integration steps during the raycasting procedure." + }; } // namespace namespace openspace { @@ -143,6 +149,7 @@ namespace openspace { , _translation(TranslationInfo, glm::vec3(0.f), glm::vec3(0.f), glm::vec3(1.f)) , _rotation(RotationInfo, glm::vec3(0.f), glm::vec3(0.f), glm::vec3(6.28f)) , _downScaleVolumeRendering(DownscaleVolumeRenderingInfo, 1.f, 0.1f, 1.f) + , _numberOfRayCastingSteps(NumberOfRayCastingStepsInfo, 1000.f, 1.f, 1000.f) { dictionary.getValue("VolumeRenderingEnabled", _volumeRenderingEnabled); dictionary.getValue("StarRenderingEnabled", _starRenderingEnabled); @@ -232,8 +239,10 @@ namespace openspace { LERROR("No volume dimensions specified."); } - if (volumeDictionary.hasKey("Steps")) { - _rayCastSteps = static_cast(volumeDictionary.value("Steps")); + if (volumeDictionary.hasKey(NumberOfRayCastingStepsInfo.identifier)) { + _numberOfRayCastingSteps = static_cast( + volumeDictionary.value(NumberOfRayCastingStepsInfo.identifier) + ); } else { LINFO("Number of raycasting steps not specified for Milkway Galaxy." @@ -243,8 +252,9 @@ namespace openspace { _downScaleVolumeRendering.setVisibility( openspace::properties::Property::Visibility::Developer ); - if (volumeDictionary.hasKey("Downscale")) { - _downScaleVolumeRendering = volumeDictionary.value("Downscale"); + if (volumeDictionary.hasKey(DownscaleVolumeRenderingInfo.identifier)) { + _downScaleVolumeRendering = + volumeDictionary.value(DownscaleVolumeRenderingInfo.identifier); } if (!dictionary.hasKeyAndValue("Points")) { @@ -331,6 +341,7 @@ void RenderableGalaxy::initializeGL() { addProperty(_translation); addProperty(_rotation); addProperty(_downScaleVolumeRendering); + addProperty(_numberOfRayCastingSteps); // initialize points. if (!_pointsFilename.empty()) { @@ -495,7 +506,7 @@ void RenderableGalaxy::update(const UpdateData& data) { _pointTransform[3] += translation; _raycaster->setDownscaleRender(_downScaleVolumeRendering); - _raycaster->setMaxSteps(_rayCastSteps); + _raycaster->setMaxSteps(_numberOfRayCastingSteps); _raycaster->setStepSize(_stepSize); _raycaster->setAspect(_aspect); _raycaster->setModelTransform(volumeTransform); diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index ea7ddcb824..d074bd848b 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -72,6 +72,7 @@ private: properties::Vec3Property _translation; properties::Vec3Property _rotation; properties::FloatProperty _downScaleVolumeRendering; + properties::FloatProperty _numberOfRayCastingSteps; std::unique_ptr _pointSpreadFunctionTexture; std::unique_ptr _pointSpreadFunctionFile; @@ -80,7 +81,6 @@ private: glm::ivec3 _volumeDimensions; std::string _pointsFilename; std::string _pointSpreadFunctionTexturePath; - int _rayCastSteps = 1000; std::unique_ptr _raycaster; std::unique_ptr>> _volume; diff --git a/openspace.cfg b/openspace.cfg index 996fa99556..b47a47aa89 100644 --- a/openspace.cfg +++ b/openspace.cfg @@ -27,7 +27,7 @@ SGCTConfig = sgct.config.single{} -- SGCTConfig = sgct.config.fisheye{1024, 1024} -- A 4k fisheye rendering in a 1024x1024 window -SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27} +-- SGCTConfig = sgct.config.fisheye{1024, 1024, res={4096, 4096}, quality="2k", tilt=27} -- Streaming OpenSpace via Spout to OBS -- SGCTConfig = sgct.config.single{2560, 1440, shared=true, name="WV_OBS_SPOUT1"} diff --git a/shaders/framebuffer/raycastframebuffer.frag b/shaders/framebuffer/raycastframebuffer.frag index 120bcdd2b8..4cb79d25a0 100644 --- a/shaders/framebuffer/raycastframebuffer.frag +++ b/shaders/framebuffer/raycastframebuffer.frag @@ -28,7 +28,6 @@ uniform sampler2D exitColorTexture; uniform sampler2D exitDepthTexture; uniform sampler2D mainDepthTexture; -uniform bool insideRaycaster; uniform vec3 cameraPosInRaycaster; uniform vec2 windowSize; @@ -53,6 +52,7 @@ out vec4 finalColor; void main() { vec2 texCoord = vec2(gl_FragCoord.xy / windowSize); + // Boundary position in view space vec4 exitColorTexture = texture(exitColorTexture, texCoord); // If we don't have an exit, discard the ray @@ -80,7 +80,7 @@ void main() { vec3 direction = normalize(diff); float raycastDepth = length(diff); - float geoDepth = denormalizeFloat(texelFetch(mainDepthTexture, ivec2(gl_FragCoord), 0).x); + float geoDepth = denormalizeFloat((texture(mainDepthTexture, texCoord).x)); float geoRatio = clamp((geoDepth - entryDepth) / (exitDepth - entryDepth), 0.f, 1.f); raycastDepth = geoRatio * raycastDepth; diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index f45c618b76..76f571cf01 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -1116,7 +1116,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector exitProgram->deactivate(); } - if (raycaster->downscaleRender() != 1.f) { + if (raycaster->downscaleRender() < 1.f) { float scaleDown = raycaster->downscaleRender(); glBindFramebuffer(GL_FRAMEBUFFER, _downscaleVolumeRendering.framebuffer); glViewport(0, 0, _resolution.x * scaleDown, _resolution.y * scaleDown); @@ -1180,7 +1180,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector glBindTexture(GL_TEXTURE_2D, _gBuffers.depthTexture); raycastProgram->setUniform("mainDepthTexture", mainDepthTextureUnit); - if (raycaster->downscaleRender() != 1.f) { + if (raycaster->downscaleRender() < 1.f) { float scaleDown = raycaster->downscaleRender(); raycastProgram->setUniform( "windowSize", @@ -1211,7 +1211,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector LWARNING("Raycaster is not attached when trying to perform raycaster task"); } - if (raycaster->downscaleRender() != 1.f) { + if (raycaster->downscaleRender() < 1.f) { float scaleDown = raycaster->downscaleRender(); glViewport(0, 0, _resolution.x, _resolution.y); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _gBuffers.framebuffer); From aaa73415e9a62b1dc169c090cf4882ea19285d83 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 13 Nov 2019 15:36:13 -0500 Subject: [PATCH 11/42] Final touches in MW volume. --- data/assets/scene/milkyway/milkyway/volume.asset | 3 +-- include/openspace/rendering/framebufferrenderer.h | 1 + src/rendering/framebufferrenderer.cpp | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/data/assets/scene/milkyway/milkyway/volume.asset b/data/assets/scene/milkyway/milkyway/volume.asset index 78195a1b5c..5e88cb9052 100644 --- a/data/assets/scene/milkyway/milkyway/volume.asset +++ b/data/assets/scene/milkyway/milkyway/volume.asset @@ -25,8 +25,7 @@ local MilkyWayVolumeGalaxy = { Filename = data .. "/MilkyWayRGBAVolume1024x1024x128.raw", Dimensions = {1024, 1024, 128}, Size = {1.2E21, 1.2E21, 0.15E21}, - Steps = 480, - Downscale = 0.5, + Downscale = 0.4, }, Points = { Type = "Points", diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 4529fd60a4..952bf13d68 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -112,6 +112,7 @@ private: void applyTMO(float blackoutFactor); void applyFXAA(); void updateDownscaleColorTexture(); + void updateExitVolumeTextures(); void writeDownscaledVolume(); std::map _raycastData; diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 76f571cf01..7d43b4d981 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -560,10 +560,14 @@ void FramebufferRenderer::writeDownscaledVolume() { glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glDisable(GL_DEPTH_TEST); + glBindVertexArray(_screenQuad); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); + glEnable(GL_DEPTH_TEST); + _downscaledVolumeProgram->deactivate(); // Restores blending state @@ -1212,7 +1216,6 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector } if (raycaster->downscaleRender() < 1.f) { - float scaleDown = raycaster->downscaleRender(); glViewport(0, 0, _resolution.x, _resolution.y); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _gBuffers.framebuffer); writeDownscaledVolume(); From c6b460ab74ef9843357651bda0f7eee772483efd Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Fri, 22 Nov 2019 18:11:49 -0500 Subject: [PATCH 12/42] Added planet label rendering. Added Earth's label. --- .../solarsystem/planets/earth/earth.asset | 38 +- modules/base/CMakeLists.txt | 2 + modules/base/basemodule.cpp | 3 + modules/base/rendering/renderablelabels.cpp | 449 ++++++++++++++++++ modules/base/rendering/renderablelabels.h | 108 +++++ .../rendering/renderablebillboardscloud.cpp | 1 - 6 files changed, 599 insertions(+), 2 deletions(-) create mode 100644 modules/base/rendering/renderablelabels.cpp create mode 100644 modules/base/rendering/renderablelabels.h diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index 3c90956e24..22f7b7c225 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -287,6 +287,42 @@ local Earth = { } } +local EarthLabel = { + Identifier = "EarthLabel", + Parent = Earth.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Earth", + FontSize = 100.0, + LabelSize = 6.5, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, -8.0E6, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 1.0E7, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Earth Label", + Path = "/Solar System/Planets/Earth" + } +} -assetHelper.registerSceneGraphNodesAndExport(asset, { Earth }) +assetHelper.registerSceneGraphNodesAndExport(asset, { Earth, EarthLabel }) diff --git a/modules/base/CMakeLists.txt b/modules/base/CMakeLists.txt index 2ce1e6846c..8ba250eac0 100644 --- a/modules/base/CMakeLists.txt +++ b/modules/base/CMakeLists.txt @@ -41,6 +41,7 @@ set(HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/rendering/multimodelgeometry.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableboxgrid.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablecartesianaxes.h + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablelabels.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablemodel.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplane.h ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplaneimagelocal.h @@ -88,6 +89,7 @@ set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/rendering/multimodelgeometry.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableboxgrid.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablecartesianaxes.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablelabels.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderablemodel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplane.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rendering/renderableplaneimagelocal.cpp diff --git a/modules/base/basemodule.cpp b/modules/base/basemodule.cpp index ba70bd6c2e..ca0c8d4975 100644 --- a/modules/base/basemodule.cpp +++ b/modules/base/basemodule.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -122,6 +123,7 @@ void BaseModule::internalInitialize(const ghoul::Dictionary&) { fRenderable->registerClass("RenderableBoxGrid"); fRenderable->registerClass("RenderableCartesianAxes"); + fRenderable->registerClass("RenderableLabels"); fRenderable->registerClass("RenderableModel"); fRenderable->registerClass("RenderablePlaneImageLocal"); fRenderable->registerClass("RenderablePlaneImageOnline"); @@ -189,6 +191,7 @@ std::vector BaseModule::documentations() const { DashboardItemVelocity::Documentation(), RenderableBoxGrid::Documentation(), + RenderableLabels::Documentation(), RenderableModel::Documentation(), RenderablePlane::Documentation(), RenderableSphere::Documentation(), diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp new file mode 100644 index 0000000000..9c9a3cb213 --- /dev/null +++ b/modules/base/rendering/renderablelabels.cpp @@ -0,0 +1,449 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2019 * + * * + * 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 +#include +#include +#include +#include +#include + +namespace { + constexpr const char* _loggerCat = "base::RenderableLabels"; + + enum BlendMode { + BlendModeNormal = 0, + BlendModeAdditive + }; + + constexpr const int ViewDirection = 0; + constexpr const int NormalDirection = 1; + + constexpr openspace::properties::Property::PropertyInfo BlendModeInfo = { + "BlendMode", + "Blending Mode", + "This determines the blending mode that is applied to this plane." + }; + + constexpr openspace::properties::Property::PropertyInfo LabelColorInfo = { + "LabelColor", + "Label Color", + "The label color for the astronomical object." + }; + + constexpr openspace::properties::Property::PropertyInfo FontSizeInfo = { + "FontSize", + "Font Size", + "The font size for the astronomical object labels." + }; + + constexpr openspace::properties::Property::PropertyInfo LabelSizeInfo = { + "LabelSize", + "Label Size", + "The label size for the astronomical object labels." + }; + + constexpr openspace::properties::Property::PropertyInfo LabelTextInfo = { + "LabelText", + "Label Text", + "The text that will be displayed on screen." + }; + + constexpr openspace::properties::Property::PropertyInfo LabelMinSizeInfo = { + "LabelMinSize", + "Label Min Size", + "The minimal size (in pixels) of the labels for the astronomical " + "objects being rendered." + }; + + constexpr openspace::properties::Property::PropertyInfo LabelMaxSizeInfo = { + "LabelMaxSize", + "Label Max Size", + "The maximum size (in pixels) of the labels for the astronomical " + "objects being rendered." + }; + + constexpr openspace::properties::Property::PropertyInfo TransformationMatrixInfo = { + "TransformationMatrix", + "Transformation Matrix", + "Transformation matrix to be applied to each astronomical object." + }; + + constexpr openspace::properties::Property::PropertyInfo LabelOrientationOptionInfo = { + "LabelOrientationOption", + "Label Orientation Option", + "Label orientation rendering mode." + }; + + constexpr openspace::properties::Property::PropertyInfo FadeInDistancesInfo = { + "FadeInDistances", + "Fade-In Start and End Distances", + "These values determine the initial and final distances from the center of " + "our galaxy from which the astronomical object will start and end " + "fading-in." + }; + + constexpr openspace::properties::Property::PropertyInfo DisableFadeInInfo = { + "DisableFadeIn", + "Disable Fade-in effect", + "Enables/Disables the Fade-in effect." + }; + + constexpr openspace::properties::Property::PropertyInfo + CorrectionSizeEndDistanceInfo = { + "CorrectionSizeEndDistance", + "Distance in 10^X meters where correction size stops acting.", + "Distance in 10^X meters where correction size stops acting." + }; + + constexpr openspace::properties::Property::PropertyInfo CorrectionSizeFactorInfo = { + "CorrectionSizeFactor", + "Control variable for distance size.", + "" + }; + + constexpr openspace::properties::Property::PropertyInfo PixelSizeControlInfo = { + "EnablePixelSizeControl", + "Enable pixel size control.", + "Enable pixel size control for rectangular projections." + }; +} // namespace + +namespace openspace { + +documentation::Documentation RenderableLabels::Documentation() { + using namespace documentation; + return { + "Renderable Labels", + "base_renderable_labels", + { + { + BlendModeInfo.identifier, + new StringInListVerifier({ "Normal", "Additive" }), + Optional::Yes, + BlendModeInfo.description, // + " The default value is 'Normal'.", + } + } + }; +} + +RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) + : Renderable(dictionary) + , _blendMode(BlendModeInfo, properties::OptionProperty::DisplayType::Dropdown) + , _labelColor( + LabelColorInfo, + glm::vec4(1.f, 1.f, 1.f, 1.f), + glm::vec4(0.f), + glm::vec4(1.f) + ) + , _labelSize(LabelSizeInfo, 8.f, 0.5f, 30.f) + , _fontSize(FontSizeInfo, 50.f, 1.f, 100.f) + , _labelMinSize(LabelMinSizeInfo, 8.f, 0.5f, 24.f) + , _labelMaxSize(LabelMaxSizeInfo, 20.f, 0.5f, 100.f) + , _pixelSizeControl(PixelSizeControlInfo, false) + , _fadeInDistance( + FadeInDistancesInfo, + glm::vec2(0.f), + glm::vec2(0.f), + glm::vec2(100.f) + ) + , _disableFadeInDistance(DisableFadeInInfo, true) + , _correctionSizeEndDistance(CorrectionSizeEndDistanceInfo, 17.f, 12.f, 25.f) + , _correctionSizeFactor(CorrectionSizeFactorInfo, 8.f, 0.f, 20.f) + , _labelOrientationOption(LabelOrientationOptionInfo, properties::OptionProperty::DisplayType::Dropdown) +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "RenderableLabels" + ); + + registerUpdateRenderBinFromOpacity(); + + _blendMode.addOptions({ + { BlendModeNormal, "Normal" }, + { BlendModeAdditive, "Additive"} + }); + _blendMode.onChange([&]() { + switch (_blendMode) { + case BlendModeNormal: + setRenderBinFromOpacity(); + break; + case BlendModeAdditive: + setRenderBin(Renderable::RenderBin::Transparent); + break; + default: + throw ghoul::MissingCaseException(); + } + }); + + if (dictionary.hasKey(BlendModeInfo.identifier)) { + const std::string v = dictionary.value(BlendModeInfo.identifier); + if (v == "Normal") { + _blendMode = BlendModeNormal; + } + else if (v == "Additive") { + _blendMode = BlendModeAdditive; + } + } + + addProperty(_blendMode); + + _labelOrientationOption.addOption(ViewDirection, "Camera View Direction"); + _labelOrientationOption.addOption(NormalDirection, "Camera Position Normal"); + + _labelOrientationOption = NormalDirection; + if (dictionary.hasKeyAndValue(LabelOrientationOptionInfo.identifier)) { + const std::string o = dictionary.value(LabelOrientationOptionInfo.identifier); + + if (o == "Camera View Direction") { + _labelOrientationOption = ViewDirection; + } + else if (o == "Camera Position Normal") { + _labelOrientationOption = NormalDirection; + } + } + + if (dictionary.hasKey(LabelTextInfo.identifier)) { + _labelText = dictionary.value(LabelTextInfo.identifier); + } + + addProperty(_labelOrientationOption); + + _labelColor.setViewOption(properties::Property::ViewOptions::Color); + if (dictionary.hasKey(LabelColorInfo.identifier)) { + _labelColor = dictionary.value(LabelColorInfo.identifier); + } + addProperty(_labelColor); + + if (dictionary.hasKey(FontSizeInfo.identifier)) { + _fontSize = dictionary.value(FontSizeInfo.identifier); + } + _fontSize.onChange([&]() { + _font = global::fontManager.font( + "Mono", + _fontSize, + ghoul::fontrendering::FontManager::Outline::Yes, + ghoul::fontrendering::FontManager::LoadGlyphs::No + ); + }); + addProperty(_fontSize); + + if (dictionary.hasKey(LabelSizeInfo.identifier)) { + _labelSize = dictionary.value(LabelSizeInfo.identifier); + } + addProperty(_labelSize); + + if (dictionary.hasKey(LabelMinSizeInfo.identifier)) { + _labelMinSize = dictionary.value(LabelMinSizeInfo.identifier); + } + addProperty(_labelMinSize); + + if (dictionary.hasKey(LabelMaxSizeInfo.identifier)) { + _labelMaxSize = dictionary.value(LabelMaxSizeInfo.identifier); + } + addProperty(_labelMaxSize); + + if (dictionary.hasKey(TransformationMatrixInfo.identifier)) { + _transformationMatrix = dictionary.value( + TransformationMatrixInfo.identifier + ); + } + + if (dictionary.hasKey(FadeInDistancesInfo.identifier)) { + glm::vec2 v = dictionary.value(FadeInDistancesInfo.identifier); + _fadeInDistance = v; + _disableFadeInDistance = false; + addProperty(_fadeInDistance); + addProperty(_disableFadeInDistance); + } + + if (dictionary.hasKey(CorrectionSizeEndDistanceInfo.identifier)) { + _correctionSizeEndDistance = static_cast( + dictionary.value(CorrectionSizeEndDistanceInfo.identifier) + ); + } + addProperty(_correctionSizeEndDistance); + + if (dictionary.hasKey(CorrectionSizeFactorInfo.identifier)) { + _correctionSizeFactor = static_cast( + dictionary.value(CorrectionSizeFactorInfo.identifier) + ); + + addProperty(_correctionSizeFactor); + } + + + if (dictionary.hasKey(PixelSizeControlInfo.identifier)) { + _pixelSizeControl = dictionary.value(PixelSizeControlInfo.identifier); + addProperty(_pixelSizeControl); + } + + //setBoundingSphere(_size); +} + +bool RenderableLabels::isReady() const { + return true; +} + +void RenderableLabels::initialize() { + bool success = true;// loadData(); + if (!success) { + throw ghoul::RuntimeError("Error loading objects labels data."); + } + + setRenderBin(Renderable::RenderBin::Transparent); +} + +void RenderableLabels::initializeGL() { + if (_font == nullptr) { + //size_t _fontSize = 50; + _font = global::fontManager.font( + "Mono", + _fontSize, + ghoul::fontrendering::FontManager::Outline::Yes, + ghoul::fontrendering::FontManager::LoadGlyphs::No + ); + } +} + +void RenderableLabels::deinitializeGL() { +} + +void RenderableLabels::render(const RenderData& data, RendererTasks&) { + + //bool additiveBlending = (_blendMode == BlendModeAdditive); + //if (additiveBlending) { + glDepthMask(false); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + //} + + float fadeInVariable = 1.f; + if (!_disableFadeInDistance) { + float distCamera = static_cast(glm::length(data.camera.positionVec3())); + const glm::vec2 fadeRange = _fadeInDistance; + const float a = 1.f / ((fadeRange.y - fadeRange.x)); + const float b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); + const float funcValue = a * distCamera + b; + fadeInVariable *= funcValue > 1.f ? 1.f : funcValue; + + if (funcValue < 0.01f) { + return; + } + } + + //glm::dmat4 modelMatrix = + // glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation + // glm::dmat4(data.modelTransform.rotation) * // Spice rotation + // glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); + + glm::dmat4 modelMatrix(1.0); + glm::dmat4 modelViewMatrix = data.camera.combinedViewMatrix() * modelMatrix; + glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); + + glm::dmat4 modelViewProjectionMatrix = projectionMatrix * modelViewMatrix; + + glm::dvec3 cameraViewDirectionWorld = -data.camera.viewDirectionWorldSpace(); + glm::dvec3 cameraUpDirectionWorld = data.camera.lookUpVectorWorldSpace(); + glm::dvec3 orthoRight = glm::normalize( + glm::cross(cameraUpDirectionWorld, cameraViewDirectionWorld) + ); + if (orthoRight == glm::dvec3(0.0)) { + glm::dvec3 otherVector( + cameraUpDirectionWorld.y, + cameraUpDirectionWorld.x, + cameraUpDirectionWorld.z + ); + orthoRight = glm::normalize(glm::cross(otherVector, cameraViewDirectionWorld)); + } + glm::dvec3 orthoUp = glm::normalize(glm::cross(cameraViewDirectionWorld, orthoRight)); + + renderLabels(data, modelViewProjectionMatrix, orthoRight, orthoUp, fadeInVariable); + + //if (additiveBlending) { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDepthMask(true); + //} +} + +void RenderableLabels::update(const UpdateData&) { + // JCC: Change font size? +} + +void RenderableLabels::renderLabels(const RenderData& data, + const glm::dmat4& modelViewProjectionMatrix, + const glm::dvec3& orthoRight, + const glm::dvec3& orthoUp, + float fadeInVariable) +{ + glm::vec4 textColor = _labelColor; + + textColor.a *= fadeInVariable; + textColor.a *= _opacity; + + ghoul::fontrendering::FontRenderer::ProjectedLabelsInformation labelInfo; + + labelInfo.orthoRight = orthoRight; + labelInfo.orthoUp = orthoUp; + labelInfo.minSize = static_cast(_labelMinSize); + labelInfo.maxSize = static_cast(_labelMaxSize); + labelInfo.cameraPos = data.camera.positionVec3(); + labelInfo.cameraLookUp = data.camera.lookUpVectorWorldSpace(); + labelInfo.renderType = _labelOrientationOption; + labelInfo.mvpMatrix = modelViewProjectionMatrix; + labelInfo.scale = powf(10.f, _labelSize); + labelInfo.enableDepth = true; + labelInfo.enableFalseDepth = false; + + // We don't use spice rotation and scale + glm::vec3 transformedPos( + _transformationMatrix * glm::dvec4(data.modelTransform.translation, 1.0) + ); + + ghoul::fontrendering::FontRenderer::defaultProjectionRenderer().render( + *_font, + transformedPos, + _labelText, + textColor, + labelInfo + ); +} +} // namespace openspace diff --git a/modules/base/rendering/renderablelabels.h b/modules/base/rendering/renderablelabels.h new file mode 100644 index 0000000000..f0ee7392eb --- /dev/null +++ b/modules/base/rendering/renderablelabels.h @@ -0,0 +1,108 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2019 * + * * + * 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_BASE___RENDERABLELABELS___H__ +#define __OPENSPACE_MODULE_BASE___RENDERABLELABELS___H__ + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace ghoul::filesystem { class File; } +namespace ghoul::fontrendering { class Font; } +namespace ghoul::opengl { + class ProgramObject; + class Texture; +} // namespace ghoul::opengl + +namespace openspace { + +struct RenderData; +struct UpdateData; + +namespace documentation { struct Documentation; } + +struct LinePoint; + +class RenderableLabels : public Renderable { +public: + RenderableLabels(const ghoul::Dictionary& dictionary); + + void initialize() override; + void initializeGL() override; + void deinitializeGL() override; + + bool isReady() const override; + + void render(const RenderData& data, RendererTasks& rendererTask) override; + void update(const UpdateData& data) override; + + static documentation::Documentation Documentation(); + +protected: + properties::OptionProperty _blendMode; + +private: + void renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, + const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable); + + properties::Vec4Property _labelColor; + properties::FloatProperty _labelSize; + properties::FloatProperty _fontSize; + properties::FloatProperty _labelMinSize; + properties::FloatProperty _labelMaxSize; + properties::BoolProperty _pixelSizeControl; + properties::Vec2Property _fadeInDistance; + properties::BoolProperty _disableFadeInDistance; + properties::FloatProperty _correctionSizeEndDistance; + properties::FloatProperty _correctionSizeFactor; + + properties::OptionProperty _labelOrientationOption; + + std::shared_ptr _font; + + std::string _speckFile; + std::string _colorMapFile; + std::string _labelFile; + std::string _colorOptionString; + std::string _datavarSizeOptionString; + + std::string _labelText; + + // Data may require some type of transformation prior the spice transformation being + // applied. + glm::dmat4 _transformationMatrix = glm::dmat4(1.0); +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_BASE___RENDERABLELABELS___H__ diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index da42b36210..40d332b2d6 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -42,7 +42,6 @@ #include #include #include -#include #include #include #include From 747e699d5f8b6b766cf1af3cf38df6e465ac476e Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 25 Nov 2019 13:10:11 -0500 Subject: [PATCH 13/42] Added other planets. --- .../dwarf_planets/pluto/pluto.asset | 39 ++++++++++++++++++- .../solarsystem/planets/earth/earth.asset | 2 +- .../solarsystem/planets/jupiter/jupiter.asset | 39 ++++++++++++++++++- .../scene/solarsystem/planets/mars/mars.asset | 39 ++++++++++++++++++- .../solarsystem/planets/mercury/mercury.asset | 38 +++++++++++++++++- .../solarsystem/planets/neptune/neptune.asset | 39 ++++++++++++++++++- .../solarsystem/planets/saturn/saturn.asset | 38 +++++++++++++++++- .../solarsystem/planets/uranus/uranus.asset | 39 ++++++++++++++++++- .../solarsystem/planets/venus/venus.asset | 38 +++++++++++++++++- 9 files changed, 299 insertions(+), 12 deletions(-) diff --git a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset index 8d2b891b4b..b4de13d9d1 100644 --- a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset +++ b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset @@ -59,6 +59,41 @@ local Pluto = { } } +local PlutoLabel = { + Identifier = "PlutoLabel", + Parent = Pluto.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Pluto", + FontSize = 100.0, + LabelSize = 8.9, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Pluto Label", + Path = "/Solar System/Planets/Pluto" + } +} - -assetHelper.registerSceneGraphNodesAndExport(asset, { Pluto }) +assetHelper.registerSceneGraphNodesAndExport(asset, { Pluto, PlutoLabel }) diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index 22f7b7c225..d6d6c43ddc 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -307,7 +307,7 @@ local EarthLabel = { Type = "RenderableLabels", LabelText = "Earth", FontSize = 100.0, - LabelSize = 6.5, + LabelSize = 8.6, LabelMaxSize = 100.0, LabelMinSize = 1.0, BlendMode = "Additive", diff --git a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset index 9333c339c1..6cc5961b41 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset @@ -42,6 +42,41 @@ local Jupiter = { } } +local JupiterLabel = { + Identifier = "JupiterLabel", + Parent = Jupiter.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Jupiter", + FontSize = 100.0, + LabelSize = 8.6, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Jupiter Label", + Path = "/Solar System/Planets/Jupiter" + } +} - -assetHelper.registerSceneGraphNodesAndExport(asset, { Jupiter }) +assetHelper.registerSceneGraphNodesAndExport(asset, { Jupiter, JupiterLabel }) diff --git a/data/assets/scene/solarsystem/planets/mars/mars.asset b/data/assets/scene/solarsystem/planets/mars/mars.asset index 57ee23d861..5912db1141 100644 --- a/data/assets/scene/solarsystem/planets/mars/mars.asset +++ b/data/assets/scene/solarsystem/planets/mars/mars.asset @@ -187,4 +187,41 @@ local Mars = { } } -assetHelper.registerSceneGraphNodesAndExport(asset, { Mars }) +local MarsLabel = { + Identifier = "MarsLabel", + Parent = Mars.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Mars", + FontSize = 100.0, + LabelSize = 8.5, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, -8.0E6, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 1.0E7, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Mars Label", + Path = "/Solar System/Planets/Mars" + } +} + +assetHelper.registerSceneGraphNodesAndExport(asset, { Mars, MarsLabel }) diff --git a/data/assets/scene/solarsystem/planets/mercury/mercury.asset b/data/assets/scene/solarsystem/planets/mercury/mercury.asset index d2bcf7c591..868d83520d 100644 --- a/data/assets/scene/solarsystem/planets/mercury/mercury.asset +++ b/data/assets/scene/solarsystem/planets/mercury/mercury.asset @@ -223,5 +223,41 @@ local Mercury = { } } +local MercuryLabel = { + Identifier = "MercuryLabel", + Parent = Mercury.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Mercury", + FontSize = 100.0, + LabelSize = 8.3, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Mercury Label", + Path = "/Solar System/Planets/Mercury" + } +} -assetHelper.registerSceneGraphNodesAndExport(asset, { Mercury }) +assetHelper.registerSceneGraphNodesAndExport(asset, { Mercury, MercuryLabel }) diff --git a/data/assets/scene/solarsystem/planets/neptune/neptune.asset b/data/assets/scene/solarsystem/planets/neptune/neptune.asset index 677395e8e5..03016589de 100644 --- a/data/assets/scene/solarsystem/planets/neptune/neptune.asset +++ b/data/assets/scene/solarsystem/planets/neptune/neptune.asset @@ -40,4 +40,41 @@ local Neptune = { } } -assetHelper.registerSceneGraphNodesAndExport(asset, { Neptune }) +local NeptuneLabel = { + Identifier = "NeptuneLabel", + Parent = Neptune.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Neptune", + FontSize = 100.0, + LabelSize = 8.8, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Neptune Label", + Path = "/Solar System/Planets/Neptune" + } +} + +assetHelper.registerSceneGraphNodesAndExport(asset, { Neptune, NeptuneLabel }) diff --git a/data/assets/scene/solarsystem/planets/saturn/saturn.asset b/data/assets/scene/solarsystem/planets/saturn/saturn.asset index 77b45972f2..aabb1d9fb2 100644 --- a/data/assets/scene/solarsystem/planets/saturn/saturn.asset +++ b/data/assets/scene/solarsystem/planets/saturn/saturn.asset @@ -57,6 +57,42 @@ local SaturnRings = { } } +local SaturnLabel = { + Identifier = "SaturnLabel", + Parent = Saturn.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Saturn", + FontSize = 100.0, + LabelSize = 8.7, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Saturn Label", + Path = "/Solar System/Planets/Saturn" + } +} -assetHelper.registerSceneGraphNodesAndExport(asset, { Saturn, SaturnRings }) +assetHelper.registerSceneGraphNodesAndExport(asset, { Saturn, SaturnRings, SaturnLabel }) diff --git a/data/assets/scene/solarsystem/planets/uranus/uranus.asset b/data/assets/scene/solarsystem/planets/uranus/uranus.asset index 1bb29fa184..d4ec613b8c 100644 --- a/data/assets/scene/solarsystem/planets/uranus/uranus.asset +++ b/data/assets/scene/solarsystem/planets/uranus/uranus.asset @@ -42,6 +42,41 @@ local Uranus = { } } +local UranusLabel = { + Identifier = "UranusLabel", + Parent = Uranus.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Uranus", + FontSize = 100.0, + LabelSize = 8.7, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Neptune Label", + Path = "/Solar System/Planets/Uranus" + } +} - -assetHelper.registerSceneGraphNodesAndExport(asset, { Uranus }) +assetHelper.registerSceneGraphNodesAndExport(asset, { Uranus, UranusLabel }) diff --git a/data/assets/scene/solarsystem/planets/venus/venus.asset b/data/assets/scene/solarsystem/planets/venus/venus.asset index 0b7617dad2..051ba208d1 100644 --- a/data/assets/scene/solarsystem/planets/venus/venus.asset +++ b/data/assets/scene/solarsystem/planets/venus/venus.asset @@ -64,6 +64,42 @@ local Venus = { } } +local VenusLabel = { + Identifier = "VenusLabel", + Parent = Venus.Identifier, + -- Transform = { + -- Translation = { + -- Type = "SpiceTranslation", + -- Target = "EARTH", + -- Observer = "EARTH BARYCENTER" + -- }, + -- -- Rotation = { + -- -- Type = "SpiceRotation", + -- -- SourceFrame = "IAU_MOON", + -- -- DestinationFrame = "GALACTIC" + -- -- } + -- }, + Renderable = { + Enabled = true, + Type = "RenderableLabels", + LabelText = "Venus", + FontSize = 100.0, + LabelSize = 8.4, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + BlendMode = "Additive", + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Venus Label", + Path = "/Solar System/Planets/Venus" + } +} -assetHelper.registerSceneGraphNodesAndExport(asset, { Venus }) +assetHelper.registerSceneGraphNodesAndExport(asset, { Venus, VenusLabel }) From dfb08b98e5aec3db4cc0c382a270a2557a97b614 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 25 Nov 2019 13:15:31 -0500 Subject: [PATCH 14/42] Removed unused code. --- modules/base/rendering/renderablelabels.cpp | 31 --------------------- modules/base/rendering/renderablelabels.h | 4 +-- 2 files changed, 1 insertion(+), 34 deletions(-) diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp index 9c9a3cb213..1e71a91ed4 100644 --- a/modules/base/rendering/renderablelabels.cpp +++ b/modules/base/rendering/renderablelabels.cpp @@ -127,19 +127,6 @@ namespace { "Enables/Disables the Fade-in effect." }; - constexpr openspace::properties::Property::PropertyInfo - CorrectionSizeEndDistanceInfo = { - "CorrectionSizeEndDistance", - "Distance in 10^X meters where correction size stops acting.", - "Distance in 10^X meters where correction size stops acting." - }; - - constexpr openspace::properties::Property::PropertyInfo CorrectionSizeFactorInfo = { - "CorrectionSizeFactor", - "Control variable for distance size.", - "" - }; - constexpr openspace::properties::Property::PropertyInfo PixelSizeControlInfo = { "EnablePixelSizeControl", "Enable pixel size control.", @@ -186,8 +173,6 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) glm::vec2(100.f) ) , _disableFadeInDistance(DisableFadeInInfo, true) - , _correctionSizeEndDistance(CorrectionSizeEndDistanceInfo, 17.f, 12.f, 25.f) - , _correctionSizeFactor(CorrectionSizeFactorInfo, 8.f, 0.f, 20.f) , _labelOrientationOption(LabelOrientationOptionInfo, properties::OptionProperty::DisplayType::Dropdown) { documentation::testSpecificationAndThrow( @@ -296,22 +281,6 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) addProperty(_disableFadeInDistance); } - if (dictionary.hasKey(CorrectionSizeEndDistanceInfo.identifier)) { - _correctionSizeEndDistance = static_cast( - dictionary.value(CorrectionSizeEndDistanceInfo.identifier) - ); - } - addProperty(_correctionSizeEndDistance); - - if (dictionary.hasKey(CorrectionSizeFactorInfo.identifier)) { - _correctionSizeFactor = static_cast( - dictionary.value(CorrectionSizeFactorInfo.identifier) - ); - - addProperty(_correctionSizeFactor); - } - - if (dictionary.hasKey(PixelSizeControlInfo.identifier)) { _pixelSizeControl = dictionary.value(PixelSizeControlInfo.identifier); addProperty(_pixelSizeControl); diff --git a/modules/base/rendering/renderablelabels.h b/modules/base/rendering/renderablelabels.h index f0ee7392eb..9c424964c7 100644 --- a/modules/base/rendering/renderablelabels.h +++ b/modules/base/rendering/renderablelabels.h @@ -83,9 +83,7 @@ private: properties::BoolProperty _pixelSizeControl; properties::Vec2Property _fadeInDistance; properties::BoolProperty _disableFadeInDistance; - properties::FloatProperty _correctionSizeEndDistance; - properties::FloatProperty _correctionSizeFactor; - + properties::OptionProperty _labelOrientationOption; std::shared_ptr _font; From ef2d14d7fa872c5aac35fcc896b7b7c273daf381 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Mon, 25 Nov 2019 13:30:39 -0500 Subject: [PATCH 15/42] Changed default label's orientation. --- .../assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset | 3 ++- data/assets/scene/solarsystem/planets/earth/earth.asset | 5 +++-- data/assets/scene/solarsystem/planets/jupiter/jupiter.asset | 1 + data/assets/scene/solarsystem/planets/mars/mars.asset | 1 + data/assets/scene/solarsystem/planets/mercury/mercury.asset | 1 + data/assets/scene/solarsystem/planets/neptune/neptune.asset | 1 + data/assets/scene/solarsystem/planets/saturn/saturn.asset | 1 + data/assets/scene/solarsystem/planets/uranus/uranus.asset | 1 + data/assets/scene/solarsystem/planets/venus/venus.asset | 1 + 9 files changed, 12 insertions(+), 3 deletions(-) diff --git a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset index b4de13d9d1..8f2d2f3036 100644 --- a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset +++ b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset @@ -83,6 +83,7 @@ local PlutoLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, BlendMode = "Additive", + LabelOrientationOption = "Camera View Direction", TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, @@ -92,7 +93,7 @@ local PlutoLabel = { }, GUI = { Name = "Pluto Label", - Path = "/Solar System/Planets/Pluto" + Path = "/Solar System/Dwarf Planets/Pluto" } } diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index d6d6c43ddc..cb14706431 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -310,11 +310,12 @@ local EarthLabel = { LabelSize = 8.6, LabelMaxSize = 100.0, LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", TransformationMatrix = { - 1.0, 0.0, 0.0, -8.0E6, + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 1.0E7, + 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }, }, diff --git a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset index 6cc5961b41..1996531c87 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset @@ -65,6 +65,7 @@ local JupiterLabel = { LabelSize = 8.6, LabelMaxSize = 100.0, LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, diff --git a/data/assets/scene/solarsystem/planets/mars/mars.asset b/data/assets/scene/solarsystem/planets/mars/mars.asset index 5912db1141..0575f88e03 100644 --- a/data/assets/scene/solarsystem/planets/mars/mars.asset +++ b/data/assets/scene/solarsystem/planets/mars/mars.asset @@ -210,6 +210,7 @@ local MarsLabel = { LabelSize = 8.5, LabelMaxSize = 100.0, LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", TransformationMatrix = { 1.0, 0.0, 0.0, -8.0E6, diff --git a/data/assets/scene/solarsystem/planets/mercury/mercury.asset b/data/assets/scene/solarsystem/planets/mercury/mercury.asset index 868d83520d..1d24fa241d 100644 --- a/data/assets/scene/solarsystem/planets/mercury/mercury.asset +++ b/data/assets/scene/solarsystem/planets/mercury/mercury.asset @@ -246,6 +246,7 @@ local MercuryLabel = { LabelSize = 8.3, LabelMaxSize = 100.0, LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, diff --git a/data/assets/scene/solarsystem/planets/neptune/neptune.asset b/data/assets/scene/solarsystem/planets/neptune/neptune.asset index 03016589de..5e617b7286 100644 --- a/data/assets/scene/solarsystem/planets/neptune/neptune.asset +++ b/data/assets/scene/solarsystem/planets/neptune/neptune.asset @@ -63,6 +63,7 @@ local NeptuneLabel = { LabelSize = 8.8, LabelMaxSize = 100.0, LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, diff --git a/data/assets/scene/solarsystem/planets/saturn/saturn.asset b/data/assets/scene/solarsystem/planets/saturn/saturn.asset index aabb1d9fb2..22a223eb3a 100644 --- a/data/assets/scene/solarsystem/planets/saturn/saturn.asset +++ b/data/assets/scene/solarsystem/planets/saturn/saturn.asset @@ -81,6 +81,7 @@ local SaturnLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, BlendMode = "Additive", + LabelOrientationOption = "Camera View Direction", TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, diff --git a/data/assets/scene/solarsystem/planets/uranus/uranus.asset b/data/assets/scene/solarsystem/planets/uranus/uranus.asset index d4ec613b8c..f522c2fa89 100644 --- a/data/assets/scene/solarsystem/planets/uranus/uranus.asset +++ b/data/assets/scene/solarsystem/planets/uranus/uranus.asset @@ -65,6 +65,7 @@ local UranusLabel = { LabelSize = 8.7, LabelMaxSize = 100.0, LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, diff --git a/data/assets/scene/solarsystem/planets/venus/venus.asset b/data/assets/scene/solarsystem/planets/venus/venus.asset index 051ba208d1..3572c07083 100644 --- a/data/assets/scene/solarsystem/planets/venus/venus.asset +++ b/data/assets/scene/solarsystem/planets/venus/venus.asset @@ -87,6 +87,7 @@ local VenusLabel = { LabelSize = 8.4, LabelMaxSize = 100.0, LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, From 60813e3209d20674f7902ff3d0964ec6fc3b5aa9 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Tue, 26 Nov 2019 11:06:39 -0500 Subject: [PATCH 16/42] Final version with volume depth interpolation. --- .../openspace/rendering/framebufferrenderer.h | 6 +- .../framebuffer/mergeDownscaledVolume.frag | 4 +- shaders/framebuffer/raycastframebuffer.frag | 1 + src/rendering/framebufferrenderer.cpp | 60 +++++++++++++++++-- 4 files changed, 64 insertions(+), 7 deletions(-) diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 952bf13d68..7dd048052f 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -111,7 +111,7 @@ private: void resolveMSAA(float blackoutFactor); void applyTMO(float blackoutFactor); void applyFXAA(); - void updateDownscaleColorTexture(); + void updateDownscaleTextures(); void updateExitVolumeTextures(); void writeDownscaledVolume(); @@ -131,7 +131,8 @@ private: UniformCache(hdrFeedingTexture, blackoutFactor, hdrExposure, gamma, Hue, Saturation, Value) _hdrUniformCache; UniformCache(renderedTexture, inverseScreenSize) _fxaaUniformCache; - UniformCache(downscaledRenderedVolume) _writeDownscaledVolumeUniformCache; + UniformCache(downscaledRenderedVolume, downscaledRenderedVolumeDepth) + _writeDownscaledVolumeUniformCache; GLint _defaultFBO; GLuint _screenQuad; @@ -166,6 +167,7 @@ private: struct { GLuint framebuffer; GLuint colorTexture; + GLuint depthbuffer; float currentDownscaleFactor = 1.f; } _downscaleVolumeRendering; diff --git a/shaders/framebuffer/mergeDownscaledVolume.frag b/shaders/framebuffer/mergeDownscaledVolume.frag index f34a300742..14a6405735 100644 --- a/shaders/framebuffer/mergeDownscaledVolume.frag +++ b/shaders/framebuffer/mergeDownscaledVolume.frag @@ -27,9 +27,11 @@ layout (location = 0) out vec4 finalColor; uniform sampler2D downscaledRenderedVolume; +uniform sampler2D downscaledRenderedVolumeDepth; in vec2 texCoord; void main() { - finalColor = texture(downscaledRenderedVolume, texCoord); + finalColor = texture(downscaledRenderedVolume, texCoord); + gl_FragDepth = texture(downscaledRenderedVolumeDepth, texCoord).r; } diff --git a/shaders/framebuffer/raycastframebuffer.frag b/shaders/framebuffer/raycastframebuffer.frag index 4cb79d25a0..bff04b1dbe 100644 --- a/shaders/framebuffer/raycastframebuffer.frag +++ b/shaders/framebuffer/raycastframebuffer.frag @@ -126,5 +126,6 @@ void main() { finalColor = vec4(accumulatedColor, (accumulatedAlpha.r + accumulatedAlpha.g + accumulatedAlpha.b) / 3.f); finalColor.rgb /= finalColor.a ; + gl_FragDepth = normalizeFloat(entryDepth); } diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 7d43b4d981..6f9d372218 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -59,8 +59,8 @@ namespace { "renderedTexture", "inverseScreenSize" }; - constexpr const std::array DownscaledVolumeUniformNames = { - "downscaledRenderedVolume" + constexpr const std::array DownscaledVolumeUniformNames = { + "downscaledRenderedVolume", "downscaledRenderedVolumeDepth" }; constexpr const char* ExitFragmentShaderPath = @@ -191,6 +191,7 @@ void FramebufferRenderer::initialize() { // DownscaleVolumeRendering glGenFramebuffers(1, &_downscaleVolumeRendering.framebuffer); glGenTextures(1, &_downscaleVolumeRendering.colorTexture); + glGenTextures(1, &_downscaleVolumeRendering.depthbuffer); // Allocate Textures/Buffers Memory updateResolution(); @@ -325,6 +326,12 @@ void FramebufferRenderer::initialize() { _downscaleVolumeRendering.colorTexture, 0 ); + glFramebufferTexture( + GL_FRAMEBUFFER, + GL_DEPTH_ATTACHMENT, + _downscaleVolumeRendering.depthbuffer, + 0 + ); status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { @@ -383,6 +390,7 @@ void FramebufferRenderer::deinitialize() { glDeleteTextures(1, &_gBuffers.positionTexture); glDeleteTextures(1, &_gBuffers.normalTexture); glDeleteTextures(1, &_downscaleVolumeRendering.colorTexture); + glDeleteTextures(1, &_downscaleVolumeRendering.depthbuffer); glDeleteTextures(1, &_pingPongBuffers.colorTexture[1]); @@ -492,7 +500,7 @@ void FramebufferRenderer::applyFXAA() { _fxaaProgram->deactivate(); } -void FramebufferRenderer::updateDownscaleColorTexture() { +void FramebufferRenderer::updateDownscaleTextures() { glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.colorTexture); glTexImage2D( GL_TEXTURE_2D, @@ -507,6 +515,23 @@ void FramebufferRenderer::updateDownscaleColorTexture() { ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + float volumeBorderColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, volumeBorderColor); + + glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.depthbuffer); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_DEPTH_COMPONENT32F, + _resolution.x * _downscaleVolumeRendering.currentDownscaleFactor, + _resolution.y * _downscaleVolumeRendering.currentDownscaleFactor, + 0, + GL_DEPTH_COMPONENT, + GL_FLOAT, + nullptr + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } void FramebufferRenderer::writeDownscaledVolume() { @@ -557,6 +582,19 @@ void FramebufferRenderer::writeDownscaledVolume() { downscaledTextureUnit ); + ghoul::opengl::TextureUnit downscaledDepthUnit; + downscaledDepthUnit.activate(); + glBindTexture( + GL_TEXTURE_2D, + _downscaleVolumeRendering.depthbuffer + ); + + _downscaledVolumeProgram->setUniform( + _writeDownscaledVolumeUniformCache.downscaledRenderedVolumeDepth, + downscaledDepthUnit + ); + + glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE); @@ -800,6 +838,20 @@ void FramebufferRenderer::updateResolution() { float volumeBorderColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, volumeBorderColor); + glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.depthbuffer); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_DEPTH_COMPONENT32F, + _resolution.x * _downscaleVolumeRendering.currentDownscaleFactor, + _resolution.y * _downscaleVolumeRendering.currentDownscaleFactor, + 0, + GL_DEPTH_COMPONENT, + GL_FLOAT, + nullptr + ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Volume Rendering Textures glBindTexture(GL_TEXTURE_2D, _exitColorTexture); @@ -1126,7 +1178,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector glViewport(0, 0, _resolution.x * scaleDown, _resolution.y * scaleDown); if (_downscaleVolumeRendering.currentDownscaleFactor != scaleDown) { _downscaleVolumeRendering.currentDownscaleFactor = scaleDown; - updateDownscaleColorTexture(); + updateDownscaleTextures(); } glClear(GL_COLOR_BUFFER_BIT); } From e2e86c12abe09ff27eafc326a8aeb9077ac80e34 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Tue, 26 Nov 2019 17:07:27 -0500 Subject: [PATCH 17/42] Ops. Cleaning depth buffer now. --- src/rendering/framebufferrenderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 6f9d372218..3e145ecf5a 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -1180,7 +1180,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector _downscaleVolumeRendering.currentDownscaleFactor = scaleDown; updateDownscaleTextures(); } - glClear(GL_COLOR_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { glBindFramebuffer(GL_FRAMEBUFFER, _gBuffers.framebuffer); From 6432f484c4d8ca0fe3eb641fa76f3b2260d969ce Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Sun, 8 Dec 2019 18:44:08 -0500 Subject: [PATCH 18/42] Changed to accpet text label updating. Added super-fine controls for fading effects. --- .../solarsystem/planets/earth/earth.asset | 7 + modules/base/rendering/renderablelabels.cpp | 321 +++++++++++++++--- modules/base/rendering/renderablelabels.h | 54 ++- 3 files changed, 328 insertions(+), 54 deletions(-) diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index cb14706431..1b735b3e66 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -312,6 +312,13 @@ local EarthLabel = { LabelMinSize = 1.0, LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", + EnableFading = true, + FadeStartUnit = "au", + FadeStartDistance = 1.5, + FadeStartSpeed = 1.0, + FadeEndUnit = "au", + FadeEndDistance = 15.0, + FadeEndSpeed = 25.0, TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp index 1e71a91ed4..38a3449127 100644 --- a/modules/base/rendering/renderablelabels.cpp +++ b/modules/base/rendering/renderablelabels.cpp @@ -49,6 +49,15 @@ namespace { constexpr const char* _loggerCat = "base::RenderableLabels"; + constexpr const char* MeterUnit = "m"; + constexpr const char* KilometerUnit = "Km"; + constexpr const char* AstronomicalUnit = "au"; + constexpr const char* ParsecUnit = "pc"; + constexpr const char* KiloparsecUnit = "Kpc"; + constexpr const char* MegaparsecUnit = "Mpc"; + constexpr const char* GigaparsecUnit = "Gpc"; + constexpr const char* GigalightyearUnit = "Gly"; + enum BlendMode { BlendModeNormal = 0, BlendModeAdditive @@ -57,6 +66,8 @@ namespace { constexpr const int ViewDirection = 0; constexpr const int NormalDirection = 1; + constexpr double PARSEC = 0.308567756E17; + constexpr openspace::properties::Property::PropertyInfo BlendModeInfo = { "BlendMode", "Blending Mode", @@ -113,18 +124,10 @@ namespace { "Label orientation rendering mode." }; - constexpr openspace::properties::Property::PropertyInfo FadeInDistancesInfo = { - "FadeInDistances", - "Fade-In Start and End Distances", - "These values determine the initial and final distances from the center of " - "our galaxy from which the astronomical object will start and end " - "fading-in." - }; - - constexpr openspace::properties::Property::PropertyInfo DisableFadeInInfo = { - "DisableFadeIn", - "Disable Fade-in effect", - "Enables/Disables the Fade-in effect." + constexpr openspace::properties::Property::PropertyInfo EnableFadingEffectInfo = { + "EnableFading", + "Enable/Disable Fade-in effect", + "Enable/Disable the Fade-in effect." }; constexpr openspace::properties::Property::PropertyInfo PixelSizeControlInfo = { @@ -132,6 +135,42 @@ namespace { "Enable pixel size control.", "Enable pixel size control for rectangular projections." }; + + constexpr openspace::properties::Property::PropertyInfo FadeStartUnitOptionInfo = { + "FadeStartUnit", + "Fade-In/-Out Start Unit.", + "Unit for fade-in/-out starting position calculation." + }; + + constexpr openspace::properties::Property::PropertyInfo FadeEndUnitOptionInfo = { + "FadeEndUnit", + "Fade-In/-Out End Unit.", + "Unit for fade-in/-out ending position calculation." + }; + + constexpr openspace::properties::Property::PropertyInfo FadeStartDistInfo = { + "FadeStartDistance", + "Fade-In/-Out starting distance.", + "Fade-In/-Out starting distance." + }; + + constexpr openspace::properties::Property::PropertyInfo FadeEndDistInfo = { + "FadeEndDistance", + "Fade-In/-Out ending distance.", + "Fade-In/-Out ending distance." + }; + + constexpr openspace::properties::Property::PropertyInfo FadeStartSpeedInfo = { + "FadeStartSpeed", + "Fade-In/-Out starting speed.", + "Fade-In/-Out starting speed." + }; + + constexpr openspace::properties::Property::PropertyInfo FadeEndSpeedInfo = { + "FadeEndSpeed", + "Fade-In/-Out ending speed.", + "Fade-In/-Out ending speed." + }; } // namespace namespace openspace { @@ -166,14 +205,15 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) , _labelMinSize(LabelMinSizeInfo, 8.f, 0.5f, 24.f) , _labelMaxSize(LabelMaxSizeInfo, 20.f, 0.5f, 100.f) , _pixelSizeControl(PixelSizeControlInfo, false) - , _fadeInDistance( - FadeInDistancesInfo, - glm::vec2(0.f), - glm::vec2(0.f), - glm::vec2(100.f) - ) - , _disableFadeInDistance(DisableFadeInInfo, true) + , _enableFadingEffect(EnableFadingEffectInfo, false) + , _labelText(LabelTextInfo) + , _fadeStartDistance(FadeStartDistInfo, 1.f, 0.f, 100.f) + , _fadeEndDistance(FadeEndDistInfo, 1.f, 0.f, 100.f) + , _fadeStartSpeed(FadeStartSpeedInfo, 1.f, 1.f, 100.f) + , _fadeEndSpeed(FadeEndSpeedInfo, 1.f, 1.f, 100.f) , _labelOrientationOption(LabelOrientationOptionInfo, properties::OptionProperty::DisplayType::Dropdown) + , _fadeStartUnitOption(FadeStartUnitOptionInfo, properties::OptionProperty::DisplayType::Dropdown) + , _fadeEndUnitOption(FadeEndUnitOptionInfo, properties::OptionProperty::DisplayType::Dropdown) { documentation::testSpecificationAndThrow( Documentation(), @@ -230,6 +270,7 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) if (dictionary.hasKey(LabelTextInfo.identifier)) { _labelText = dictionary.value(LabelTextInfo.identifier); } + addProperty(_labelText); addProperty(_labelOrientationOption); @@ -273,19 +314,135 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) ); } - if (dictionary.hasKey(FadeInDistancesInfo.identifier)) { - glm::vec2 v = dictionary.value(FadeInDistancesInfo.identifier); - _fadeInDistance = v; - _disableFadeInDistance = false; - addProperty(_fadeInDistance); - addProperty(_disableFadeInDistance); - } - if (dictionary.hasKey(PixelSizeControlInfo.identifier)) { _pixelSizeControl = dictionary.value(PixelSizeControlInfo.identifier); addProperty(_pixelSizeControl); } + if (dictionary.hasKey(EnableFadingEffectInfo.identifier)) { + _enableFadingEffect = dictionary.value(EnableFadingEffectInfo.identifier); + } + addProperty(_enableFadingEffect); + + if (dictionary.hasKey(FadeStartDistInfo.identifier)) { + _fadeStartDistance = dictionary.value(FadeStartDistInfo.identifier); + } + + addProperty(_fadeStartDistance); + + _fadeStartUnitOption.addOption(Meter, MeterUnit); + _fadeStartUnitOption.addOption(Kilometer, KilometerUnit); + _fadeStartUnitOption.addOption(AU, AstronomicalUnit); + _fadeStartUnitOption.addOption(Parsec, ParsecUnit); + _fadeStartUnitOption.addOption(Kiloparsec, KiloparsecUnit); + _fadeStartUnitOption.addOption(Megaparsec, MegaparsecUnit); + _fadeStartUnitOption.addOption(Gigaparsec, GigaparsecUnit); + _fadeStartUnitOption.addOption(GigalightYears, GigalightyearUnit); + + _fadeStartUnitOption = AU; + + if (dictionary.hasKey(FadeStartUnitOptionInfo.identifier)) { + std::string unit = dictionary.value(FadeStartUnitOptionInfo.identifier); + if (unit == MeterUnit) { + _fadeStartUnitOption = Meter; + } + else if (unit == KilometerUnit) { + _fadeStartUnitOption = Kilometer; + } + else if (unit == AstronomicalUnit) { + _fadeStartUnitOption = AU; + } + else if (unit == ParsecUnit) { + _fadeStartUnitOption = Parsec; + } + else if (unit == KiloparsecUnit) { + _fadeStartUnitOption = Kiloparsec; + } + else if (unit == MegaparsecUnit) { + _fadeStartUnitOption = Megaparsec; + } + else if (unit == GigaparsecUnit) { + _fadeStartUnitOption = Gigaparsec; + } + else if (unit == GigalightyearUnit) { + _fadeStartUnitOption = GigalightYears; + } + else { + LWARNING( + "No unit given for RenderableLabels. Using kilometer as units." + ); + _fadeStartUnitOption = Kilometer; + } + } + + addProperty(_fadeStartUnitOption); + + if (dictionary.hasKey(FadeStartSpeedInfo.identifier)) { + _fadeStartSpeed = dictionary.value(FadeStartSpeedInfo.identifier); + } + + addProperty(_fadeStartSpeed); + + if (dictionary.hasKey(FadeEndDistInfo.identifier)) { + _fadeEndDistance = dictionary.value(FadeEndDistInfo.identifier); + } + + addProperty(_fadeEndDistance); + + _fadeEndUnitOption.addOption(Meter, MeterUnit); + _fadeEndUnitOption.addOption(Kilometer, KilometerUnit); + _fadeEndUnitOption.addOption(AU, AstronomicalUnit); + _fadeEndUnitOption.addOption(Parsec, ParsecUnit); + _fadeEndUnitOption.addOption(Kiloparsec, KiloparsecUnit); + _fadeEndUnitOption.addOption(Megaparsec, MegaparsecUnit); + _fadeEndUnitOption.addOption(Gigaparsec, GigaparsecUnit); + _fadeEndUnitOption.addOption(GigalightYears, GigalightyearUnit); + + _fadeEndUnitOption = AU; + + if (dictionary.hasKey(FadeEndUnitOptionInfo.identifier)) { + std::string unit = dictionary.value(FadeEndUnitOptionInfo.identifier); + if (unit == MeterUnit) { + _fadeEndUnitOption = Meter; + } + else if (unit == KilometerUnit) { + _fadeEndUnitOption = Kilometer; + } + else if (unit == AstronomicalUnit) { + _fadeEndUnitOption = AU; + } + else if (unit == ParsecUnit) { + _fadeEndUnitOption = Parsec; + } + else if (unit == KiloparsecUnit) { + _fadeEndUnitOption = Kiloparsec; + } + else if (unit == MegaparsecUnit) { + _fadeEndUnitOption = Megaparsec; + } + else if (unit == GigaparsecUnit) { + _fadeEndUnitOption = Gigaparsec; + } + else if (unit == GigalightyearUnit) { + _fadeEndUnitOption = GigalightYears; + } + else { + LWARNING( + "No unit given for RenderableLabels. Using kilometer as units." + ); + _fadeEndUnitOption = Kilometer; + } + } + + addProperty(_fadeEndUnitOption); + + if (dictionary.hasKey(FadeEndSpeedInfo.identifier)) { + _fadeEndSpeed = dictionary.value(FadeEndSpeedInfo.identifier); + } + + addProperty(_fadeEndSpeed); + + //setBoundingSphere(_size); } @@ -326,24 +483,20 @@ void RenderableLabels::render(const RenderData& data, RendererTasks&) { //} float fadeInVariable = 1.f; - if (!_disableFadeInDistance) { - float distCamera = static_cast(glm::length(data.camera.positionVec3())); - const glm::vec2 fadeRange = _fadeInDistance; - const float a = 1.f / ((fadeRange.y - fadeRange.x)); - const float b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); - const float funcValue = a * distCamera + b; - fadeInVariable *= funcValue > 1.f ? 1.f : funcValue; - - if (funcValue < 0.01f) { - return; - } + + if (_enableFadingEffect) { + float distanceNodeToCamera = glm::distance( + data.camera.positionVec3(), + data.modelTransform.translation + ); + float sUnit = getUnit(_fadeStartUnitOption); + float eUnit = getUnit(_fadeEndUnitOption); + float startX = _fadeStartDistance * sUnit; + float endX = _fadeEndDistance * eUnit; + //fadeInVariable = changedPerlinSmoothStepFunc(distanceNodeToCamera, startX, endX); + fadeInVariable = linearSmoothStepFunc(distanceNodeToCamera, startX, endX, sUnit, eUnit); } - //glm::dmat4 modelMatrix = - // glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation - // glm::dmat4(data.modelTransform.rotation) * // Spice rotation - // glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); - glm::dmat4 modelMatrix(1.0); glm::dmat4 modelViewMatrix = data.camera.combinedViewMatrix() * modelMatrix; glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); @@ -374,7 +527,10 @@ void RenderableLabels::render(const RenderData& data, RendererTasks&) { } void RenderableLabels::update(const UpdateData&) { - // JCC: Change font size? +} + +void RenderableLabels::setLabelText(const std::string & newText) { + _labelText = newText; } void RenderableLabels::renderLabels(const RenderData& data, @@ -415,4 +571,81 @@ void RenderableLabels::renderLabels(const RenderData& data, labelInfo ); } + +float RenderableLabels::changedPerlinSmoothStepFunc(const float x, + const float startX, + const float endX) const +{ + float f1 = 6.f * powf((x - startX), 5.f) - 15.f * powf((x - startX), 4.f) + + 10.f * powf((x - startX), 3.f); + float f2 = -6.f * powf((x - endX), 5.f) + 15.f * powf((x - endX), 4.f) - + 10.f * powf((x - endX), 3.f) + 1.f; + float f3 = 1.f; + + if (x <= startX) { + return std::clamp(f1, 0.f, 1.f); + } + else if (x > startX && x < endX) { + return f3; + } + else if (x >= endX) { + return std::clamp(f2, 0.f, 1.f); + } +} + +float RenderableLabels::linearSmoothStepFunc(const float x, + const float startX, + const float endX, + const float sUnit, + const float eUnit) const +{ + float sdiv = 1.f / (sUnit * _fadeStartSpeed); + float ediv = -1.f / (eUnit * _fadeEndSpeed); + float f1 = sdiv * (x - startX) + 1.f; + float f2 = ediv * (x - endX) + 1.f; + float f3 = 1.f; + + if (x <= startX) { + return std::clamp(f1, 0.f, 1.f); + } + else if (x > startX && x < endX) { + return f3; + } + else if (x >= endX) { + return std::clamp(f2, 0.f, 1.f); + } +} + +float RenderableLabels::getUnit(int unit) const { + + float scale = 0.f; + switch (static_cast(unit)) { + case Meter: + scale = 1.f; + break; + case Kilometer: + scale = 1e3f; + break; + case AU: + scale = 149597870700.f; + break; + case Parsec: + scale = static_cast(PARSEC); + break; + case Kiloparsec: + scale = static_cast(1e3 * PARSEC); + break; + case Megaparsec: + scale = static_cast(1e6 * PARSEC); + break; + case Gigaparsec: + scale = static_cast(1e9 * PARSEC); + break; + case GigalightYears: + scale = static_cast(306391534.73091 * PARSEC); + break; + } + + return scale; +} } // namespace openspace diff --git a/modules/base/rendering/renderablelabels.h b/modules/base/rendering/renderablelabels.h index 9c424964c7..491755f825 100644 --- a/modules/base/rendering/renderablelabels.h +++ b/modules/base/rendering/renderablelabels.h @@ -54,6 +54,18 @@ namespace documentation { struct Documentation; } struct LinePoint; class RenderableLabels : public Renderable { +private: + enum Unit { + Meter = 0, + Kilometer = 1, + AU = 2, + Parsec = 3, + Kiloparsec = 4, + Megaparsec = 5, + Gigaparsec = 6, + GigalightYears = 7 + }; + public: RenderableLabels(const ghoul::Dictionary& dictionary); @@ -68,6 +80,8 @@ public: static documentation::Documentation Documentation(); + void setLabelText(const std::string & newText); + protected: properties::OptionProperty _blendMode; @@ -75,16 +89,38 @@ private: void renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable); - properties::Vec4Property _labelColor; - properties::FloatProperty _labelSize; - properties::FloatProperty _fontSize; - properties::FloatProperty _labelMinSize; - properties::FloatProperty _labelMaxSize; - properties::BoolProperty _pixelSizeControl; - properties::Vec2Property _fadeInDistance; - properties::BoolProperty _disableFadeInDistance; + float changedPerlinSmoothStepFunc( + const float x, + const float startX, + const float endX + ) const; + float linearSmoothStepFunc( + const float x, + const float startX, + const float endX, + const float sUnit, + const float eUnit + ) const; + + float getUnit(int unit) const; + + properties::Vec4Property _labelColor; + properties::FloatProperty _labelSize; + properties::FloatProperty _fontSize; + properties::FloatProperty _labelMinSize; + properties::FloatProperty _labelMaxSize; + properties::BoolProperty _pixelSizeControl; + properties::BoolProperty _enableFadingEffect; + properties::StringProperty _labelText; + properties::FloatProperty _fadeStartDistance; + properties::FloatProperty _fadeEndDistance; + properties::FloatProperty _fadeStartSpeed; + properties::FloatProperty _fadeEndSpeed; + properties::OptionProperty _labelOrientationOption; + properties::OptionProperty _fadeStartUnitOption; + properties::OptionProperty _fadeEndUnitOption; std::shared_ptr _font; @@ -94,8 +130,6 @@ private: std::string _colorOptionString; std::string _datavarSizeOptionString; - std::string _labelText; - // Data may require some type of transformation prior the spice transformation being // applied. glm::dmat4 _transformationMatrix = glm::dmat4(1.0); From 43296979d8b5e4dca88d1301df083ce5e822d82d Mon Sep 17 00:00:00 2001 From: Mikael Pettersson Date: Tue, 10 Dec 2019 15:15:52 +0100 Subject: [PATCH 19/42] Fixed rotation matrices in touch Fixed rotation matrices in the touchmodule, while at it I also moved out the lev-marq solver from the touchinteraction.cpp to its own file, in an effort to make the code lighter to read. Also changed some logic in how touch intersection is made with the scenenodes. --- modules/touch/CMakeLists.txt | 2 + modules/touch/include/directinputsolver.h | 71 +++++ modules/touch/include/touchinteraction.h | 28 +- modules/touch/src/directinputsolver.cpp | 271 ++++++++++++++++++ modules/touch/src/touchinteraction.cpp | 333 ++++------------------ modules/touch/src/win32_touch.cpp | 4 +- modules/touch/touchmodule.cpp | 2 +- 7 files changed, 402 insertions(+), 309 deletions(-) create mode 100644 modules/touch/include/directinputsolver.h create mode 100644 modules/touch/src/directinputsolver.cpp diff --git a/modules/touch/CMakeLists.txt b/modules/touch/CMakeLists.txt index 07190880d5..d0b7ec5289 100644 --- a/modules/touch/CMakeLists.txt +++ b/modules/touch/CMakeLists.txt @@ -26,6 +26,7 @@ include(${OPENSPACE_CMAKE_EXT_DIR}/module_definition.cmake) set(HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/ext/levmarq.h + ${CMAKE_CURRENT_SOURCE_DIR}/include/directinputsolver.h ${CMAKE_CURRENT_SOURCE_DIR}/include/tuioear.h ${CMAKE_CURRENT_SOURCE_DIR}/include/touchinteraction.h ${CMAKE_CURRENT_SOURCE_DIR}/include/touchmarker.h @@ -35,6 +36,7 @@ source_group("Header Files" FILES ${HEADER_FILES}) set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/ext/levmarq.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/directinputsolver.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/tuioear.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/touchinteraction.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/touchmarker.cpp diff --git a/modules/touch/include/directinputsolver.h b/modules/touch/include/directinputsolver.h new file mode 100644 index 0000000000..418f01a535 --- /dev/null +++ b/modules/touch/include/directinputsolver.h @@ -0,0 +1,71 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2019 * + * * + * 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_TOUCH___DIRECTINPUT_SOLVER___H__ +#define __OPENSPACE_MODULE_TOUCH___DIRECTINPUT_SOLVER___H__ + + +#include + +#include + +#include + + +namespace openspace { + +class Camera; +class SceneGraphNode; + +// Stores the selected node, the cursor ID as well as the surface coordinates the +// cursor touched +struct SelectedBody { + long id; + SceneGraphNode* node; + glm::dvec3 coordinates; +}; + +class DirectInputSolver { +public: + DirectInputSolver(); + bool solve(const std::vector& list, + const std::vector& selectedBodies, + std::vector* calculatedValues, + const Camera& camera); + int getNDof() { return _nDof; } + + const LMstat& getLevMarqStat() { return _lmstat; } + void setLevMarqVerbosity(bool verbose) { _lmstat.verbose = verbose; } + +private: + int _nDof; + LMstat _lmstat; +}; + + + +} // openspace namespace + +#endif // __OPENSPACE_MODULE_TOUCH___DIRECTINPUT_SOLVER___H__ + diff --git a/modules/touch/include/touchinteraction.h b/modules/touch/include/touchinteraction.h index f8de436b4b..5cfddec46e 100644 --- a/modules/touch/include/touchinteraction.h +++ b/modules/touch/include/touchinteraction.h @@ -27,7 +27,7 @@ #include -#include +#include #include #include @@ -38,6 +38,8 @@ #include #include +#include + //#define TOUCH_DEBUG_PROPERTIES //#define TOUCH_DEBUG_NODE_PICK_MESSAGES @@ -79,27 +81,6 @@ public: glm::dvec2 pan; }; - // Stores the selected node, the cursor ID as well as the surface coordinates the - // cursor touched - struct SelectedBody { - long id; - SceneGraphNode* node; - glm::dvec3 coordinates; - }; - - // Used in the LM algorithm - struct FunctionData { - std::vector selectedPoints; - std::vector screenPoints; - int nDOF; - glm::dvec2(*castToNDC)(const glm::dvec3&, Camera&, SceneGraphNode*); - double(*distToMinimize)(double* par, int x, void* fdata, LMstat* lmstat); - Camera* camera; - SceneGraphNode* node; - LMstat stats; - double objectScreenRadius; - }; - /* Main function call * 1 Checks if doubleTap occured * 2 Goes through the guiMode() function @@ -258,7 +239,8 @@ private: bool _guiON; std::vector _selected; SceneGraphNode* _pickingSelected = nullptr; - LMstat _lmstat; + std::unique_ptr _solver; + glm::dquat _toSlerp; glm::dvec3 _centroid; diff --git a/modules/touch/src/directinputsolver.cpp b/modules/touch/src/directinputsolver.cpp new file mode 100644 index 0000000000..43624e6af6 --- /dev/null +++ b/modules/touch/src/directinputsolver.cpp @@ -0,0 +1,271 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2019 * + * * + * 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 + + +namespace openspace { + +// Used in the LM algorithm +struct FunctionData { + std::vector selectedPoints; + std::vector screenPoints; + int nDOF; + const Camera* camera; + SceneGraphNode* node; + LMstat stats; +}; + + +DirectInputSolver::DirectInputSolver() + : _nDof(0) +{ + levmarq_init(&_lmstat); +} + +// project back a 3D point in model view to clip space [-1,1] coordinates on the view plane +glm::dvec2 castToNDC(const glm::dvec3& vec, Camera& camera, SceneGraphNode* node) { + glm::dvec3 posInCamSpace = glm::inverse(camera.rotationQuaternion()) * + (node->worldRotationMatrix() * vec + + (node->worldPosition() - camera.positionVec3())); + + glm::dvec4 clipspace = camera.projectionMatrix() * glm::dvec4(posInCamSpace, 1.0); + return (glm::dvec2(clipspace) / clipspace.w); +} + +// Returns the screen point s(xi,par) dependent the transform M(par) and object point xi +double distToMinimize(double* par, int x, void* fdata, LMstat* lmstat) { + FunctionData* ptr = reinterpret_cast(fdata); + + // Apply transform to camera and find the new screen point of the updated camera state + + // { vec2 globalRot, zoom, roll, vec2 localRot } + double q[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; + for (int i = 0; i < ptr->nDOF; ++i) { + q[i] = par[i]; + } + + using namespace glm; + // Create variables from current state + dvec3 camPos = ptr->camera->positionVec3(); + dvec3 centerPos = ptr->node->worldPosition(); + + dvec3 directionToCenter = normalize(centerPos - camPos); + dvec3 lookUp = ptr->camera->lookUpVectorWorldSpace(); + dvec3 camDirection = ptr->camera->viewDirectionWorldSpace(); + + // Make a representation of the rotation quaternion with local and global + // rotations + dmat4 lookAtMat = lookAt( + dvec3(0, 0, 0), + directionToCenter, + // To avoid problem with lookup in up direction + normalize(camDirection + lookUp)); + dquat globalCamRot = normalize(quat_cast(inverse(lookAtMat))); + dquat localCamRot = inverse(globalCamRot) * ptr->camera->rotationQuaternion(); + + { // Roll + dquat rollRot = angleAxis(q[3], dvec3(0.0, 0.0, 1.0)); + localCamRot = localCamRot * rollRot; + } + { // Panning (local rotation) + dvec3 eulerAngles(q[5], q[4], 0); + dquat panRot = dquat(eulerAngles); + localCamRot = localCamRot * panRot; + } + { // Orbit (global rotation) + dvec3 eulerAngles(q[1], q[0], 0); + dquat rotationDiffCamSpace = dquat(eulerAngles); + + dvec3 centerToCamera = camPos - centerPos; + + dquat rotationDiffWorldSpace = + globalCamRot * rotationDiffCamSpace * inverse(globalCamRot); + dvec3 rotationDiffVec3 = + centerToCamera * rotationDiffWorldSpace - centerToCamera; + camPos += rotationDiffVec3; + + centerToCamera = camPos - centerPos; + directionToCenter = normalize(-centerToCamera); + dvec3 lookUpWhenFacingCenter = + globalCamRot * dvec3(ptr->camera->lookUpVectorCameraSpace()); + lookAtMat = lookAt( + dvec3(0, 0, 0), + directionToCenter, + lookUpWhenFacingCenter); + globalCamRot = normalize(quat_cast(inverse(lookAtMat))); + } + { // Zooming + camPos += directionToCenter * q[2]; + } + // Update the camera state + Camera cam = *(ptr->camera); + cam.setPositionVec3(camPos); + cam.setRotation(globalCamRot * localCamRot); + + // we now have a new position and orientation of camera, project surfacePoint to + // the new screen to get distance to minimize + glm::dvec2 newScreenPoint = castToNDC( + ptr->selectedPoints.at(x), + cam, + ptr->node + ); + lmstat->pos.push_back(newScreenPoint); + return glm::length(ptr->screenPoints.at(x) - newScreenPoint); +} + +// Gradient of distToMinimize w.r.t par (using forward difference) +void gradient(double* g, double* par, int x, void* fdata, LMstat* lmstat) { + FunctionData* ptr = reinterpret_cast(fdata); + double f0 = distToMinimize(par, x, fdata, lmstat); + // scale value to find minimum step size h, dependant on planet size + double scale = log10(ptr->node->boundingSphere()); + std::vector dPar(ptr->nDOF, 0.0); + dPar.assign(par, par + ptr->nDOF); + + for (int i = 0; i < ptr->nDOF; ++i) { + // Initial values + double h = 1e-8; + double lastG = 1; + dPar.at(i) += h; + double f1 = distToMinimize(dPar.data(), x, fdata, lmstat); + dPar.at(i) = par[i]; + // Iterative process to find the minimum step h that gives a good gradient + for (int j = 0; j < 100; ++j) { + if ((f1 - f0) != 0 && lastG == 0) { // found minimum step size h + // scale up to get a good initial guess value + h *= scale * scale * scale; + + // clamp min step size to a fraction of the incoming parameter + if (i == 2) { + double epsilon = 1e-3; + // make sure incoming parameter is larger than 0 + h = std::max(std::max(std::abs(dPar.at(i)), epsilon) * 0.001, h); + } + else if (ptr->nDOF == 2) { + h = std::max(std::abs(dPar.at(i)) * 0.001, h); + } + + // calculate f1 with good h for finite difference + dPar.at(i) += h; + f1 = distToMinimize(dPar.data(), x, fdata, lmstat); + dPar.at(i) = par[i]; + break; + } + else if ((f1 - f0) != 0 && lastG != 0) { // h too big + h /= scale; + } + else if ((f1 - f0) == 0) { // h too small + h *= scale; + } + lastG = f1 - f0; + dPar.at(i) += h; + f1 = distToMinimize(dPar.data(), x, fdata, lmstat); + dPar.at(i) = par[i]; + } + g[i] = (f1 - f0) / h; + } + if (ptr->nDOF == 2) { + // normalize on 1 finger case to allow for horizontal/vertical movement + for (int i = 0; i < 2; ++i) { + g[i] = g[i] / std::abs(g[i]); + } + } + else if (ptr->nDOF == 6) { + for (int i = 0; i < ptr->nDOF; ++i) { + // lock to only pan and zoom on 3 finger case, no roll/orbit + g[i] = (i == 2) ? g[i] : g[i] / std::abs(g[i]); + } + } +} + +bool DirectInputSolver::solve(const std::vector& list, + const std::vector& selectedBodies, + std::vector *parameters, + const Camera &camera) +{ + + int nFingers = std::min(static_cast(list.size()), 3); + _nDof = std::min(nFingers * 2, 6); + + // Parse input data to be used in the LM algorithm + std::vector selectedPoints; + std::vector screenPoints; + + for (int i = 0; i < nFingers; ++i) { + const SelectedBody& sb = selectedBodies.at(i); + selectedPoints.push_back(sb.coordinates); + screenPoints.emplace_back(2 * (list[i].getX() - 0.5), -2 * (list[i].getY() - 0.5)); + + // This might be needed when we're directing the touchtable from another screen? + // std::vector::const_iterator c = std::find_if( + // list.begin(), + // list.end(), + // [&sb](const TuioCursor& c) { return c.getSessionID() == sb.id; } + // ); + // if (c != list.end()) { + // // normalized -1 to 1 coordinates on screen + // screenPoints.emplace_back(2 * (c->getX() - 0.5), -2 * (c->getY() - 0.5)); + // } + // else { + // global::moduleEngine.module()->touchInput = { + // true, + // glm::dvec2(0.0, 0.0), + // 1 + // }; + // resetAfterInput(); + // return; + // } + } + + FunctionData fData = { + selectedPoints, + screenPoints, + _nDof, + &camera, + selectedBodies.at(0).node, + _lmstat + }; + void* dataPtr = reinterpret_cast(&fData); + + bool result = levmarq( + _nDof, + parameters->data(), + static_cast(screenPoints.size()), + nullptr, + distToMinimize, + gradient, + dataPtr, + &_lmstat + ); + + return result; +} + +} // openspace namespace + diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index 1653b13248..f9600b9e6f 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -23,7 +23,9 @@ ****************************************************************************************/ #include + #include +#include #include #include @@ -320,6 +322,7 @@ TouchInteraction::TouchInteraction() , _zoomOutTap(false) , _lmSuccess(true) , _guiON(false) + , _solver(new DirectInputSolver()) #ifdef TOUCH_DEBUG_PROPERTIES , _debugProperties() #endif @@ -369,11 +372,8 @@ TouchInteraction::TouchInteraction() } }); - levmarq_init(&_lmstat); - _time.initSession(); } - // Called each frame if there is any input void TouchInteraction::updateStateFromInput(const std::vector& list, std::vector& lastProcessed) @@ -513,231 +513,21 @@ void TouchInteraction::directControl(const std::vector& list) { #ifdef TOUCH_DEBUG_PROPERTIES LINFO("DirectControl"); #endif - // Returns the screen point s(xi,par) dependent the transform M(par) and object - // point xi - auto distToMinimize = [](double* par, int x, void* fdata, LMstat* lmstat) { - FunctionData* ptr = reinterpret_cast(fdata); - - // Apply transform to camera and find the new screen point of the updated camera - // state - - // { vec2 globalRot, zoom, roll, vec2 localRot } - double q[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; - for (int i = 0; i < ptr->nDOF; ++i) { - q[i] = par[i]; - } - - using namespace glm; - // Create variables from current state - dvec3 camPos = ptr->camera->positionVec3(); - dvec3 centerPos = ptr->node->worldPosition(); - - dvec3 directionToCenter = normalize(centerPos - camPos); - dvec3 lookUp = ptr->camera->lookUpVectorWorldSpace(); - dvec3 camDirection = ptr->camera->viewDirectionWorldSpace(); - - // Make a representation of the rotation quaternion with local and global - // rotations - dmat4 lookAtMat = lookAt( - dvec3(0, 0, 0), - directionToCenter, - // To avoid problem with lookup in up direction - normalize(camDirection + lookUp)); - dquat globalCamRot = normalize(quat_cast(inverse(lookAtMat))); - dquat localCamRot = inverse(globalCamRot) * ptr->camera->rotationQuaternion(); - - { // Roll - dquat rollRot = angleAxis(q[3], dvec3(0.0, 0.0, 1.0)); - localCamRot = localCamRot * rollRot; - } - { // Panning (local rotation) - dvec3 eulerAngles(q[5], q[4], 0); - dquat panRot = dquat(eulerAngles); - localCamRot = localCamRot * panRot; - } - { // Orbit (global rotation) - dvec3 eulerAngles(q[1], q[0], 0); - dquat rotationDiffCamSpace = dquat(eulerAngles); - - dvec3 centerToCamera = camPos - centerPos; - - dquat rotationDiffWorldSpace = - globalCamRot * rotationDiffCamSpace * inverse(globalCamRot); - dvec3 rotationDiffVec3 = - centerToCamera * rotationDiffWorldSpace - centerToCamera; - camPos += rotationDiffVec3; - - centerToCamera = camPos - centerPos; - directionToCenter = normalize(-centerToCamera); - dvec3 lookUpWhenFacingCenter = - globalCamRot * dvec3(ptr->camera->lookUpVectorCameraSpace()); - lookAtMat = lookAt( - dvec3(0, 0, 0), - directionToCenter, - lookUpWhenFacingCenter); - globalCamRot = normalize(quat_cast(inverse(lookAtMat))); - } - { // Zooming - camPos += directionToCenter * q[2]; - } - // Update the camera state - Camera cam = *(ptr->camera); - cam.setPositionVec3(camPos); - cam.setRotation(globalCamRot * localCamRot); - - // we now have a new position and orientation of camera, project surfacePoint to - // the new screen to get distance to minimize - glm::dvec2 newScreenPoint = ptr->castToNDC( - ptr->selectedPoints.at(x), - cam, - ptr->node - ); - lmstat->pos.push_back(newScreenPoint); - return glm::length(ptr->screenPoints.at(x) - newScreenPoint); - }; - // Gradient of distToMinimize w.r.t par (using forward difference) - auto gradient = [](double* g, double* par, int x, void* fdata, LMstat* lmstat) { - FunctionData* ptr = reinterpret_cast(fdata); - double h, lastG, f1, f0 = ptr->distToMinimize(par, x, fdata, lmstat); - // scale value to find minimum step size h, dependant on planet size - double scale = log10(ptr->node->boundingSphere()); - std::vector dPar(ptr->nDOF, 0.0); - dPar.assign(par, par + ptr->nDOF); - - for (int i = 0; i < ptr->nDOF; ++i) { - // Initial values - h = 1e-8; - lastG = 1; - dPar.at(i) += h; - f1 = ptr->distToMinimize(dPar.data(), x, fdata, lmstat); - dPar.at(i) = par[i]; - // Iterative process to find the minimum step h that gives a good gradient - for (int j = 0; j < 100; ++j) { - if ((f1 - f0) != 0 && lastG == 0) { // found minimum step size h - // scale up to get a good initial guess value - h *= scale * scale * scale; - - // clamp min step size to a fraction of the incoming parameter - if (i == 2) { - double epsilon = 1e-3; - // make sure incoming parameter is larger than 0 - h = std::max(std::max(std::abs(dPar.at(i)), epsilon) * 0.001, h); - } - else if (ptr->nDOF == 2) { - h = std::max(std::abs(dPar.at(i)) * 0.001, h); - } - - // calculate f1 with good h for finite difference - dPar.at(i) += h; - f1 = ptr->distToMinimize(dPar.data(), x, fdata, lmstat); - dPar.at(i) = par[i]; - break; - } - else if ((f1 - f0) != 0 && lastG != 0) { // h too big - h /= scale; - } - else if ((f1 - f0) == 0) { // h too small - h *= scale; - } - lastG = f1 - f0; - dPar.at(i) += h; - f1 = ptr->distToMinimize(dPar.data(), x, fdata, lmstat); - dPar.at(i) = par[i]; - } - g[i] = (f1 - f0) / h; - } - if (ptr->nDOF == 2) { - // normalize on 1 finger case to allow for horizontal/vertical movement - for (int i = 0; i < 2; ++i) { - g[i] = g[i]/std::abs(g[i]); - } - } - else if (ptr->nDOF == 6) { - for (int i = 0; i < ptr->nDOF; ++i) { - // lock to only pan and zoom on 3 finger case, no roll/orbit - g[i] = (i == 2) ? g[i] : g[i] / std::abs(g[i]); - } - } - }; - - // project back a 3D point in model view to clip space [-1,1] coordinates on the view - // plane - auto castToNDC = [](const glm::dvec3& vec, Camera& camera, SceneGraphNode* node) { - glm::dvec3 posInCamSpace = glm::inverse(camera.rotationQuaternion()) * - (node->rotationMatrix() * vec + - (node->worldPosition() - camera.positionVec3())); - - glm::dvec4 clipspace = camera.projectionMatrix() * glm::dvec4(posInCamSpace, 1.0); - return (glm::dvec2(clipspace) / clipspace.w); - }; - - // only send in first three fingers (to make it easier for LMA to converge on 3+ - // finger case with only zoom/pan) - int nFingers = std::min(static_cast(list.size()), 3); - int nDOF = std::min(nFingers * 2, 6); - std::vector par(nDOF, 0.0); - par.at(0) = _lastVel.orbit.x; // use _lastVel for orbit - par.at(1) = _lastVel.orbit.y; - - // Parse input data to be used in the LM algorithm - std::vector selectedPoints; - std::vector screenPoints; - for (int i = 0; i < nFingers; ++i) { - const SelectedBody& sb = _selected.at(i); - selectedPoints.push_back(sb.coordinates); - - std::vector::const_iterator c = std::find_if( - list.begin(), - list.end(), - [&sb](const TuioCursor& c) { return c.getSessionID() == sb.id; } - ); - if (c != list.end()) { - // normalized -1 to 1 coordinates on screen - screenPoints.emplace_back(2 * (c->getX() - 0.5), -2 * (c->getY() - 0.5)); - } - else { - global::moduleEngine.module()->touchInput = { - true, - glm::dvec2(0.0, 0.0), - 1 - }; - resetAfterInput(); - return; - } - } - - FunctionData fData = { - selectedPoints, - screenPoints, - nDOF, - castToNDC, - distToMinimize, - _camera, - _selected.at(0).node, - _lmstat, - _currentRadius - }; - void* dataPtr = reinterpret_cast(&fData); // finds best transform values for the new camera state and stores them in par - _lmSuccess = levmarq( - nDOF, - par.data(), - static_cast(screenPoints.size()), - nullptr, - distToMinimize, - gradient, - dataPtr, - &_lmstat - ); + std::vector par(6, 0.0); + par.at(0) = _lastVel.orbit.x; // use _lastVel for orbit + par.at(1) = _lastVel.orbit.y; + _lmSuccess = _solver->solve(list, _selected, &par, *_camera); + int nDof = _solver->getNDof(); if (_lmSuccess && !_unitTest) { // if good values were found set new camera state _vel.orbit = glm::dvec2(par.at(0), par.at(1)); - if (nDOF > 2) { + if (nDof > 2) { _vel.zoom = par.at(2); _vel.roll = par.at(3); - if (_panEnabled && nDOF > 4) { + if (_panEnabled && nDof > 4) { _vel.roll = 0.0; _vel.pan = glm::dvec2(par.at(4), par.at(5)); } @@ -785,19 +575,17 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { glm::dquat camToWorldSpace = _camera->rotationQuaternion(); glm::dvec3 camPos = _camera->positionVec3(); std::vector newSelected; - - struct PickingInfo { - SceneGraphNode* node; - double pickingDistanceNDC; - double pickingDistanceWorld; + + //node & distance + std::tuple currentlyPicked = { + nullptr, + std::numeric_limits::max() }; - std::vector pickingInfo; - + for (const TuioCursor& c : list) { double xCo = 2 * (c.getX() - 0.5); double yCo = -2 * (c.getY() - 0.5); // normalized -1 to 1 coordinates on screen - // vec3(projectionmatrix * clipspace), divide with w? glm::dvec3 cursorInWorldSpace = camToWorldSpace * glm::dvec3(glm::inverse(_camera->projectionMatrix()) * glm::dvec4(xCo, yCo, -1.0, 1.0)); @@ -808,20 +596,12 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { for (SceneGraphNode* node : selectableNodes) { double boundingSphere = node->boundingSphere(); glm::dvec3 camToSelectable = node->worldPosition() - camPos; - double dist = length(glm::cross(cursorInWorldSpace, camToSelectable)) / - glm::length(cursorInWorldSpace) - boundingSphere; - if (dist <= 0.0) { - // finds intersection closest point between boundingsphere and line in - // world coordinates, assumes line direction is normalized - double d = glm::dot(raytrace, camToSelectable); - double root = boundingSphere * boundingSphere - - glm::dot(camToSelectable, camToSelectable) + d * d; - if (root > 0) { // two intersection points (take the closest one) - d -= sqrt(root); - } - glm::dvec3 intersectionPoint = camPos + d * raytrace; - glm::dvec3 pointInModelView = glm::inverse(node->rotationMatrix()) * - (intersectionPoint - node->worldPosition()); + glm::dvec3 intersectionPos = {}; + glm::dvec3 intersectionNormal = {}; + bool intersected = glm::intersectRaySphere(camPos, raytrace, node->worldPosition(), boundingSphere, intersectionPos, intersectionNormal); + if (intersected) { + glm::dvec3 pointInModelView = glm::inverse(node->worldRotationMatrix()) * + (intersectionPos - node->worldPosition()); // Add id, node and surface coordinates to the selected list std::vector::iterator oldNode = std::find_if( @@ -830,9 +610,7 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { [id](SelectedBody s) { return s.id == id; } ); if (oldNode != newSelected.end()) { - double oldNodeDist = glm::length( - oldNode->node->worldPosition() - camPos - ); + double oldNodeDist = glm::length(oldNode->node->worldPosition() - camPos); if (glm::length(camToSelectable) < oldNodeDist) { // new node is closer, remove added node and add the new one // instead @@ -859,56 +637,44 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { // We either want to select the object if it's bounding sphere as been // touched (checked by the first part of this loop above) or if the touch // point is within a minimum distance of the center - if (dist <= 0.0 || (ndcDist <= _pickingRadiusMinimum)) { - // If the user touched the planet directly, this is definitely the one - // they are interested in => minimum distance - if (dist <= 0.0) { + // If the user touched the planet directly, this is definitely the one + // they are interested in => minimum distance + if (intersected) { #ifdef TOUCH_DEBUG_NODE_PICK_MESSAGES - LINFOC( - node->identifier(), - "Picking candidate based on direct touch" - ); + LINFOC( + node->identifier(), + "Picking candidate based on direct touch" + ); #endif //#ifdef TOUCH_DEBUG_NODE_PICK_MESSAGES - pickingInfo.push_back({ - node, - -std::numeric_limits::max(), - -std::numeric_limits::max() - }); - } - else { - // The node was considered due to minimum picking distance radius + currentlyPicked = { + node, + -std::numeric_limits::max() + }; + } + else if (ndcDist <= _pickingRadiusMinimum) { + // The node was considered due to minimum picking distance radius #ifdef TOUCH_DEBUG_NODE_PICK_MESSAGES - LINFOC( - node->identifier(), - "Picking candidate based on proximity" - ); + LINFOC( + node->identifier(), + "Picking candidate based on proximity" + ); #endif //#ifdef TOUCH_DEBUG_NODE_PICK_MESSAGES - pickingInfo.push_back({ + double dist = length(intersectionPos - camPos); + if (dist < std::get<1>(currentlyPicked)) { + currentlyPicked = { node, - ndcDist, dist - }); + }; } } } } } - - // After we are done with all of the nodes, we can sort the picking list and pick the - // one that fits best (= is closest or was touched directly) - std::sort( - pickingInfo.begin(), - pickingInfo.end(), - [](const PickingInfo& lhs, const PickingInfo& rhs) { - return lhs.pickingDistanceWorld < rhs.pickingDistanceWorld; - } - ); - // If an item has been picked, it's in the first position of the vector now - if (!pickingInfo.empty()) { - _pickingSelected = pickingInfo.begin()->node; + if (SceneGraphNode* node = std::get<0>(currentlyPicked)) { + _pickingSelected = node; #ifdef TOUCH_DEBUG_NODE_PICK_MESSAGES LINFOC("Picking", "Picked node: " + _pickingSelected->identifier()); #endif //#ifdef TOUCH_DEBUG_NODE_PICK_MESSAGES @@ -1447,7 +1213,7 @@ void TouchInteraction::step(double dt) { void TouchInteraction::unitTest() { if (_unitTest) { - _lmstat.verbose = true; + _solver->setLevMarqVerbosity(true); // set _selected pos and new pos (on screen) std::vector lastFrame = { @@ -1468,7 +1234,7 @@ void TouchInteraction::unitTest() { snprintf(buffer, sizeof(char) * 32, "lmdata%i.csv", _numOfTests); _numOfTests++; std::ofstream file(buffer); - file << _lmstat.data; + file << _solver->getLevMarqStat().data; // clear everything _selected.clear(); @@ -1480,6 +1246,7 @@ void TouchInteraction::unitTest() { _lastVel = _vel; _unitTest = false; + _solver->setLevMarqVerbosity(false); // could be the camera copy in func } } diff --git a/modules/touch/src/win32_touch.cpp b/modules/touch/src/win32_touch.cpp index 8d248d3a63..32331c8bb3 100644 --- a/modules/touch/src/win32_touch.cpp +++ b/modules/touch/src/win32_touch.cpp @@ -69,8 +69,8 @@ LRESULT CALLBACK HookCallback(int nCode, WPARAM wParam, LPARAM lParam) { // native touch to screen conversion ScreenToClient(pStruct->hwnd, reinterpret_cast(&p)); - float xPos = (float)p.x / (float)(rect.right - rect.left); - float yPos = (float)p.y / (float)(rect.bottom - rect.top); + float xPos = static_cast(p.x) / static_cast(rect.right - rect.left); + float yPos = static_cast(p.y) / static_cast(rect.bottom - rect.top); if (pointerInfo.pointerFlags & POINTER_FLAG_DOWN) { // Handle new touchpoint gTuioServer->initFrame(TUIO::TuioTime::getSessionTime()); diff --git a/modules/touch/touchmodule.cpp b/modules/touch/touchmodule.cpp index a47e2fe4d2..f968095a44 100644 --- a/modules/touch/touchmodule.cpp +++ b/modules/touch/touchmodule.cpp @@ -164,7 +164,7 @@ TouchModule::TouchModule() if (nativeWindowHandle) { _win32TouchHook.reset(new Win32TouchHook(nativeWindowHandle)); } -#endif //WIN32 +#endif }); global::callback::deinitializeGL.push_back([&]() { From 140de3d808b0f46bbe4cc217adbd8bfdcee7cdfc Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Tue, 10 Dec 2019 12:55:58 -0500 Subject: [PATCH 20/42] Added automatic documentation and Sun's label. --- data/assets/scene/solarsystem/sun/sun.asset | 35 +++++++- modules/base/rendering/renderablelabels.cpp | 98 ++++++++++++++++++++- 2 files changed, 131 insertions(+), 2 deletions(-) diff --git a/data/assets/scene/solarsystem/sun/sun.asset b/data/assets/scene/solarsystem/sun/sun.asset index cc887dc4d2..81f72297f9 100644 --- a/data/assets/scene/solarsystem/sun/sun.asset +++ b/data/assets/scene/solarsystem/sun/sun.asset @@ -27,4 +27,37 @@ local Sun = { } } -assetHelper.registerSceneGraphNodesAndExport(asset, { Sun }) +local SunLabel = { + Identifier = "SunLabel", + Parent = Sun.Identifier, + Renderable = { + Enabled = false, + Type = "RenderableLabels", + LabelText = "Sun", + FontSize = 100.0, + LabelSize = 8.6, + LabelMaxSize = 100.0, + LabelMinSize = 1.0, + LabelOrientationOption = "Camera View Direction", + BlendMode = "Additive", + EnableFading = true, + FadeStartUnit = "pc", + FadeStartDistance = 0.1, + FadeStartSpeed = 1.0, + FadeEndUnit = "pc", + FadeEndDistance = 1.0, + FadeEndSpeed = 4.0, + TransformationMatrix = { + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + }, + }, + GUI = { + Name = "Sun Label", + Path = "/Solar System/Sun" + } +} + +assetHelper.registerSceneGraphNodesAndExport(asset, { Sun, SunLabel }) diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp index 38a3449127..ff20e8cbad 100644 --- a/modules/base/rendering/renderablelabels.cpp +++ b/modules/base/rendering/renderablelabels.cpp @@ -186,7 +186,103 @@ documentation::Documentation RenderableLabels::Documentation() { new StringInListVerifier({ "Normal", "Additive" }), Optional::Yes, BlendModeInfo.description, // + " The default value is 'Normal'.", - } + }, + { + LabelOrientationOptionInfo.identifier, + new StringInListVerifier({ "Camera View Direction", "Camera Position Normal" }), + Optional::Yes, + LabelOrientationOptionInfo.description, + }, + { + LabelColorInfo.identifier, + new DoubleVector4Verifier, + Optional::Yes, + LabelColorInfo.description, + }, + { + LabelColorInfo.identifier, + new DoubleVector4Verifier, + Optional::Yes, + LabelColorInfo.description, + }, + { + LabelTextInfo.identifier, + new StringVerifier, + Optional::No, + LabelTextInfo.description + }, + { + FontSizeInfo.identifier, + new DoubleVerifier, + Optional::Yes, + FontSizeInfo.description + }, + { + LabelSizeInfo.identifier, + new DoubleVerifier, + Optional::Yes, + LabelSizeInfo.description + }, + { + LabelMinSizeInfo.identifier, + new DoubleVerifier, + Optional::Yes, + LabelMinSizeInfo.description + }, + { + LabelMaxSizeInfo.identifier, + new DoubleVerifier, + Optional::Yes, + LabelMaxSizeInfo.description + }, + { + EnableFadingEffectInfo.identifier, + new BoolVerifier, + Optional::Yes, + EnableFadingEffectInfo.description + }, + { + PixelSizeControlInfo.identifier, + new BoolVerifier, + Optional::Yes, + PixelSizeControlInfo.description + }, + { + FadeStartUnitOptionInfo.identifier, + new StringInListVerifier({"m", "Km", "au", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), + Optional::Yes, + FadeStartUnitOptionInfo.description, + }, + { + FadeEndUnitOptionInfo.identifier, + new StringInListVerifier({"m", "Km", "au", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), + Optional::Yes, + FadeEndUnitOptionInfo.description, + }, + { + FadeStartDistInfo.identifier, + new DoubleVerifier, + Optional::Yes, + FadeStartDistInfo.description + }, + { + FadeEndDistInfo.identifier, + new DoubleVerifier, + Optional::Yes, + FadeEndDistInfo.description + }, + { + FadeStartSpeedInfo.identifier, + new DoubleVerifier, + Optional::Yes, + FadeStartSpeedInfo.description + }, + { + FadeEndSpeedInfo.identifier, + new DoubleVerifier, + Optional::Yes, + FadeEndSpeedInfo.description + }, } }; } From 69fb1eec20b4adcca5b93aa30dfd9fac4ee06094 Mon Sep 17 00:00:00 2001 From: Mikael Pettersson Date: Wed, 11 Dec 2019 09:56:45 +0100 Subject: [PATCH 21/42] Fixed edge case and cleanup Fixed picking edge case, where we now will sort our elements as before Also used another ray-sphere intersect fn as we did not use everything from the other one. --- modules/touch/src/touchinteraction.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index f9600b9e6f..fa0cb44c56 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -594,12 +594,13 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { long id = c.getSessionID(); for (SceneGraphNode* node : selectableNodes) { - double boundingSphere = node->boundingSphere(); + double boundingSphereSquared = double(node->boundingSphere()) * double(node->boundingSphere()); glm::dvec3 camToSelectable = node->worldPosition() - camPos; - glm::dvec3 intersectionPos = {}; - glm::dvec3 intersectionNormal = {}; - bool intersected = glm::intersectRaySphere(camPos, raytrace, node->worldPosition(), boundingSphere, intersectionPos, intersectionNormal); + double intersectionDist = 0.0; + bool intersected = glm::intersectRaySphere(camPos, raytrace, node->worldPosition(), + boundingSphereSquared, intersectionDist); if (intersected) { + glm::dvec3 intersectionPos = camPos + raytrace * intersectionDist; glm::dvec3 pointInModelView = glm::inverse(node->worldRotationMatrix()) * (intersectionPos - node->worldPosition()); @@ -660,7 +661,7 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { "Picking candidate based on proximity" ); #endif //#ifdef TOUCH_DEBUG_NODE_PICK_MESSAGES - double dist = length(intersectionPos - camPos); + double dist = length(camToSelectable); if (dist < std::get<1>(currentlyPicked)) { currentlyPicked = { node, From 3e23e4323c6a4a95908be4af689000331c158371 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Wed, 11 Dec 2019 13:30:52 -0700 Subject: [PATCH 22/42] Feature/venus magellan (#1020) * Updated Venus asset and added wms for Magellan mosaic imagery * Adding Magellan height layer --- .../map_service_configs/Utah/MagellanDEM.wms | 21 ++++++++++++ .../Utah/MagellanMosaic.wms | 21 ++++++++++++ .../solarsystem/planets/venus/venus.asset | 33 ++++++++++++++----- 3 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanDEM.wms create mode 100644 data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanMosaic.wms diff --git a/data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanDEM.wms b/data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanDEM.wms new file mode 100644 index 0000000000..c8072a6e30 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanDEM.wms @@ -0,0 +1,21 @@ + + + http://openspace.sci.utah.edu/Venus/MagellanDEM/tile/${z}/${y}/${x} + + + -180.0 + 90.0 + 180.0 + -90.0 + 8192 + 4096 + 4 + top + + GEOGCS["GCS_Venus",DATUM["D_Venus",SPHEROID["Venus",6051000,0]],PRIMEM["Reference_Meridian",0],UNIT["Degree",0.0174532925199433]] + 256 + 256 + 1 + 10 + 5 + diff --git a/data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanMosaic.wms b/data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanMosaic.wms new file mode 100644 index 0000000000..084e231ea4 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/venus/map_service_configs/Utah/MagellanMosaic.wms @@ -0,0 +1,21 @@ + + + http://openspace.sci.utah.edu/Venus/MagellanMosaic/tile/${z}/${y}/${x} + + + -180.0 + 84.0 + 180.0 + -80.0 + 506928 + 230948 + 9 + top + + GEOGCS["GCS_Venus",DATUM["D_Venus",SPHEROID["Venus_localRadius",6051000,0]],PRIMEM["Reference_Meridian",0],UNIT["Degree",0.0174532925199433]] + 512 + 512 + 1 + 10 + 5 + diff --git a/data/assets/scene/solarsystem/planets/venus/venus.asset b/data/assets/scene/solarsystem/planets/venus/venus.asset index 0b7617dad2..d11b371752 100644 --- a/data/assets/scene/solarsystem/planets/venus/venus.asset +++ b/data/assets/scene/solarsystem/planets/venus/venus.asset @@ -4,7 +4,7 @@ asset.require("spice/base") asset.request('./trail') local labelsPath = asset.require('./venus_labels').LabelsPath - +local mapServiceConfigs = asset.localResource("map_service_configs") local textures = asset.syncedResource({ Name = "Venus Textures", @@ -13,6 +13,28 @@ local textures = asset.syncedResource({ Version = 1 }) +local color_layers = { + { + Identifier = "Texture", + FilePath = textures .. "/venus.jpg", + Enabled = true + }, + { + Identifier = "Magellan_Mosaic_Utah", + Name = "Magellan Mosaic [Utah]", + FilePath = mapServiceConfigs .. "/Utah/MagellanMosaic.wms" + } +} + +local height_layers = { + { + Identifier = "Magellan", + Name = "Magellan Elevation [Utah]", + FilePath = mapServiceConfigs .. "/Utah/MagellanDEM.wms", + TilePixelSize = 64 + } +} + local Venus = { Identifier = "Venus", Parent = transforms.VenusBarycenter.Identifier, @@ -33,13 +55,8 @@ local Venus = { Radii = { 6051900.0, 6051900.0, 6051800.0 }, SegmentsPerPatch = 64, Layers = { - ColorLayers = { - { - Identifier = "Texture", - FilePath = textures .. "/venus.jpg", - Enabled = true - } - } + ColorLayers = color_layers, + HeightLayers = height_layers }, Labels = { Enable = false, From 5509fb0a6bf6cf7d5d3af44c72b1b13e07b2af5f Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 11 Dec 2019 15:38:11 -0500 Subject: [PATCH 23/42] Added more units to refine fading controls. Updated Sun fading values. --- data/assets/scene/solarsystem/sun/sun.asset | 14 +++--- modules/base/rendering/renderablelabels.cpp | 54 +++++++++++++++++++-- modules/base/rendering/renderablelabels.h | 16 +++--- 3 files changed, 68 insertions(+), 16 deletions(-) diff --git a/data/assets/scene/solarsystem/sun/sun.asset b/data/assets/scene/solarsystem/sun/sun.asset index 81f72297f9..0ca4e4a8be 100644 --- a/data/assets/scene/solarsystem/sun/sun.asset +++ b/data/assets/scene/solarsystem/sun/sun.asset @@ -31,22 +31,22 @@ local SunLabel = { Identifier = "SunLabel", Parent = Sun.Identifier, Renderable = { - Enabled = false, + Enabled = true, Type = "RenderableLabels", LabelText = "Sun", FontSize = 100.0, - LabelSize = 8.6, + LabelSize = 13.127, LabelMaxSize = 100.0, LabelMinSize = 1.0, LabelOrientationOption = "Camera View Direction", BlendMode = "Additive", EnableFading = true, - FadeStartUnit = "pc", - FadeStartDistance = 0.1, - FadeStartSpeed = 1.0, + FadeStartUnit = "Pm", + FadeStartDistance = 2.841, + FadeStartSpeed = 1.375, FadeEndUnit = "pc", - FadeEndDistance = 1.0, - FadeEndSpeed = 4.0, + FadeEndDistance = 1.326, + FadeEndSpeed = 1.0, TransformationMatrix = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp index ff20e8cbad..a5b33f2624 100644 --- a/modules/base/rendering/renderablelabels.cpp +++ b/modules/base/rendering/renderablelabels.cpp @@ -51,7 +51,11 @@ namespace { constexpr const char* MeterUnit = "m"; constexpr const char* KilometerUnit = "Km"; + constexpr const char* MegameterUnit = "Mm"; + constexpr const char* GigameterUnit = "Gm"; constexpr const char* AstronomicalUnit = "au"; + constexpr const char* TerameterUnit = "Tm"; + constexpr const char* PetameterUnit = "Pm"; constexpr const char* ParsecUnit = "pc"; constexpr const char* KiloparsecUnit = "Kpc"; constexpr const char* MegaparsecUnit = "Mpc"; @@ -249,13 +253,13 @@ documentation::Documentation RenderableLabels::Documentation() { }, { FadeStartUnitOptionInfo.identifier, - new StringInListVerifier({"m", "Km", "au", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), + new StringInListVerifier({"m", "Km", "Mm", "Gm", "au", "Tm", "Pm", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), Optional::Yes, FadeStartUnitOptionInfo.description, }, { FadeEndUnitOptionInfo.identifier, - new StringInListVerifier({"m", "Km", "au", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), + new StringInListVerifier({"m", "Km", "Mm", "Gm", "au", "Tm", "Pm", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), Optional::Yes, FadeEndUnitOptionInfo.description, }, @@ -428,7 +432,11 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) _fadeStartUnitOption.addOption(Meter, MeterUnit); _fadeStartUnitOption.addOption(Kilometer, KilometerUnit); + _fadeStartUnitOption.addOption(Megameter, MegameterUnit); + _fadeStartUnitOption.addOption(Gigameter, GigameterUnit); _fadeStartUnitOption.addOption(AU, AstronomicalUnit); + _fadeStartUnitOption.addOption(Terameter, TerameterUnit); + _fadeStartUnitOption.addOption(Petameter, PetameterUnit); _fadeStartUnitOption.addOption(Parsec, ParsecUnit); _fadeStartUnitOption.addOption(Kiloparsec, KiloparsecUnit); _fadeStartUnitOption.addOption(Megaparsec, MegaparsecUnit); @@ -445,9 +453,21 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) else if (unit == KilometerUnit) { _fadeStartUnitOption = Kilometer; } + else if (unit == MegameterUnit) { + _fadeStartUnitOption = Megameter; + } + else if (unit == GigameterUnit) { + _fadeStartUnitOption = Gigameter; + } else if (unit == AstronomicalUnit) { _fadeStartUnitOption = AU; } + else if (unit == TerameterUnit) { + _fadeStartUnitOption = Terameter; + } + else if (unit == PetameterUnit) { + _fadeStartUnitOption = Petameter; + } else if (unit == ParsecUnit) { _fadeStartUnitOption = Parsec; } @@ -487,7 +507,11 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) _fadeEndUnitOption.addOption(Meter, MeterUnit); _fadeEndUnitOption.addOption(Kilometer, KilometerUnit); + _fadeEndUnitOption.addOption(Megameter, MegameterUnit); + _fadeEndUnitOption.addOption(Gigameter, GigameterUnit); _fadeEndUnitOption.addOption(AU, AstronomicalUnit); + _fadeEndUnitOption.addOption(Terameter, TerameterUnit); + _fadeEndUnitOption.addOption(Petameter, PetameterUnit); _fadeEndUnitOption.addOption(Parsec, ParsecUnit); _fadeEndUnitOption.addOption(Kiloparsec, KiloparsecUnit); _fadeEndUnitOption.addOption(Megaparsec, MegaparsecUnit); @@ -504,9 +528,21 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) else if (unit == KilometerUnit) { _fadeEndUnitOption = Kilometer; } + else if (unit == MegameterUnit) { + _fadeEndUnitOption = Megameter; + } + else if (unit == GigameterUnit) { + _fadeEndUnitOption = Gigameter; + } else if (unit == AstronomicalUnit) { _fadeEndUnitOption = AU; } + else if (unit == TerameterUnit) { + _fadeEndUnitOption = Terameter; + } + else if (unit == PetameterUnit) { + _fadeEndUnitOption = Petameter; + } else if (unit == ParsecUnit) { _fadeEndUnitOption = Parsec; } @@ -720,11 +756,23 @@ float RenderableLabels::getUnit(int unit) const { scale = 1.f; break; case Kilometer: - scale = 1e3f; + scale = 1e3; + break; + case Megameter: + scale = 1e6; + break; + case Gigameter: + scale = 1e9; break; case AU: scale = 149597870700.f; break; + case Terameter: + scale = 1e12; + break; + case Petameter: + scale = 1e15; + break; case Parsec: scale = static_cast(PARSEC); break; diff --git a/modules/base/rendering/renderablelabels.h b/modules/base/rendering/renderablelabels.h index 491755f825..c0fa9848e9 100644 --- a/modules/base/rendering/renderablelabels.h +++ b/modules/base/rendering/renderablelabels.h @@ -58,12 +58,16 @@ private: enum Unit { Meter = 0, Kilometer = 1, - AU = 2, - Parsec = 3, - Kiloparsec = 4, - Megaparsec = 5, - Gigaparsec = 6, - GigalightYears = 7 + Megameter = 2, + Gigameter = 3, + AU = 4, + Terameter = 5, + Petameter = 6, + Parsec = 7, + Kiloparsec = 8, + Megaparsec = 9, + Gigaparsec = 10, + GigalightYears = 11 }; public: From fba204a51ff6865e4ce094806fcb03f35292ab20 Mon Sep 17 00:00:00 2001 From: Jonathas Costa Date: Wed, 11 Dec 2019 15:59:26 -0500 Subject: [PATCH 24/42] Added Venus atm. --- data/assets/scene/solarsystem/planets.asset | 1 + .../planets/venus/atmosphere.asset | 66 +++++++++++++++++++ .../solarsystem/planets/venus/venus.asset | 3 +- 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 data/assets/scene/solarsystem/planets/venus/atmosphere.asset diff --git a/data/assets/scene/solarsystem/planets.asset b/data/assets/scene/solarsystem/planets.asset index 8603643031..a631b33339 100644 --- a/data/assets/scene/solarsystem/planets.asset +++ b/data/assets/scene/solarsystem/planets.asset @@ -1,6 +1,7 @@ asset.request('./planets/mercury/mercury') asset.request('./planets/venus/venus') +asset.request('./planets/venus/atmosphere') asset.request('./planets/earth/earth') asset.request('./planets/earth/atmosphere') diff --git a/data/assets/scene/solarsystem/planets/venus/atmosphere.asset b/data/assets/scene/solarsystem/planets/venus/atmosphere.asset new file mode 100644 index 0000000000..40a95cdc54 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/venus/atmosphere.asset @@ -0,0 +1,66 @@ +local transforms = asset.require('./venus') +local assetHelper = asset.require('util/asset_helper') + + + +local Atmosphere = { + Identifier = "VenusAtmosphere", + Parent = transforms.Venus.Identifier, + Renderable = { + Type = "RenderableAtmosphere", + Atmosphere = { + -- Atmosphere radius in Km + AtmosphereRadius = 6121.9, + PlanetRadius = 6051.9, + PlanetAverageGroundReflectance = 0.018, + GroundRadianceEmittion = 0.8, + SunIntensity = 11.47, + --MieScatteringExtinctionPropCoefficient = 0.23862, + Rayleigh = { + Coefficients = { + -- Wavelengths are given in 10^-9m + Wavelengths = { 680, 550, 440 }, + -- Reflection coefficients are given in km^-1 + Scattering = { 19.518E-3, 13.83E-3, 3.65E-3 } + -- In Rayleigh scattering, the coefficients of + -- absorption and scattering are the same. + }, + -- Thichkness of atmosphere if its density were uniform, in Km + H_R = 6.7 + }, + -- Default + Mie = { + Coefficients = { + -- Reflection coefficients are given in km^-1 + Scattering = { 53.61771e-3, 53.61771e-3, 53.61771e-3 }, + -- Extinction coefficients are a fraction of the Scattering coefficients + Extinction = { 53.61771e-3/0.98979, 53.61771e-3/0.98979, 53.61771e-3/0.98979 } + }, + -- Mie Height scale (atmosphere thickness for constant density) in Km + H_M = 9.8, + -- Mie Phase Function Value (G e [-1.0, 1.0]. + -- If G = 1.0, Mie phase function = Rayleigh Phase Function) + G = 0.85 + }, + Image = { + ToneMapping = jToneMapping, + Exposure = 0.4, + Background = 1.8, + Gamma = 1.85 + }, + Debug = { + -- PreCalculatedTextureScale is a float from 1.0 to N, with N > 0.0 and N in Naturals (i.e., 1, 2, 3, 4, 5....) + PreCalculatedTextureScale = 1.0, + SaveCalculatedTextures = false + } + } + }, + GUI = { + Name = "Venus Atmosphere", + Path = "/Solar System/Planets/Venus" + } +} + + + +assetHelper.registerSceneGraphNodesAndExport(asset, { Atmosphere }) diff --git a/data/assets/scene/solarsystem/planets/venus/venus.asset b/data/assets/scene/solarsystem/planets/venus/venus.asset index 0b7617dad2..07e74fdf25 100644 --- a/data/assets/scene/solarsystem/planets/venus/venus.asset +++ b/data/assets/scene/solarsystem/planets/venus/venus.asset @@ -30,7 +30,8 @@ local Venus = { }, Renderable = { Type = "RenderableGlobe", - Radii = { 6051900.0, 6051900.0, 6051800.0 }, + --Radii = { 6051900.0, 6051900.0, 6051800.0 }, + Radii = { 6051900.0, 6051900.0, 6051900.0 }, SegmentsPerPatch = 64, Layers = { ColorLayers = { From 99c995565b13078e6727b092900a516179eec647 Mon Sep 17 00:00:00 2001 From: Gene Payne Date: Fri, 13 Dec 2019 07:47:05 -0700 Subject: [PATCH 25/42] Fix for issue 1023: prevents crash when using satellites and changing segments property, and fixes rendering errors. (#1028) --- .../earth/satellites/satellites_shared.asset | 2 +- .../space/rendering/renderablesatellites.cpp | 25 ++++++------------- .../space/rendering/renderablesatellites.h | 2 -- 3 files changed, 9 insertions(+), 20 deletions(-) diff --git a/data/assets/scene/solarsystem/planets/earth/satellites/satellites_shared.asset b/data/assets/scene/solarsystem/planets/earth/satellites/satellites_shared.asset index 58b3e35ec4..e5fde6d30c 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/satellites_shared.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/satellites_shared.asset @@ -56,7 +56,7 @@ local registerSatelliteGroupObjects = function(containingAsset, group, tleFolder Renderable = { Type = "RenderableSatellites", Path = file, - Segments = 160, + Segments = 120, Color = color, Fade = 0.5 }, diff --git a/modules/space/rendering/renderablesatellites.cpp b/modules/space/rendering/renderablesatellites.cpp index 7453ff44f5..5476bf828f 100644 --- a/modules/space/rendering/renderablesatellites.cpp +++ b/modules/space/rendering/renderablesatellites.cpp @@ -66,13 +66,6 @@ namespace { "method includes lines. If the rendering mode is set to Points, this value is " "ignored." }; - constexpr openspace::properties::Property::PropertyInfo FadeInfo = { - "Fade", - "Line fade", - "The fading factor that is applied to the trail if the 'EnableFade' value is " - "'true'. If it is 'false', this setting has no effect. The higher the number, " - "the less fading is applied." - }; constexpr openspace::properties::Property::PropertyInfo LineColorInfo = { "Color", "Color", @@ -301,12 +294,6 @@ documentation::Documentation RenderableSatellites::Documentation() { Optional::Yes, LineWidthInfo.description }, - { - FadeInfo.identifier, - new DoubleVerifier, - Optional::Yes, - FadeInfo.description - }, { LineColorInfo.identifier, new DoubleVector3Verifier, @@ -320,8 +307,7 @@ documentation::Documentation RenderableSatellites::Documentation() { RenderableSatellites::RenderableSatellites(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _path(PathInfo) - , _nSegments(SegmentsInfo) - , _lineFade(FadeInfo) + , _nSegments(SegmentsInfo, 120, 4, 1024) { documentation::testSpecificationAndThrow( @@ -332,16 +318,21 @@ RenderableSatellites::RenderableSatellites(const ghoul::Dictionary& dictionary) _path = dictionary.value(PathInfo.identifier); _nSegments = static_cast(dictionary.value(SegmentsInfo.identifier)); - _lineFade = static_cast(dictionary.value(FadeInfo.identifier)); if (dictionary.hasKeyAndValue(LineColorInfo.identifier)) { _appearance.lineColor = dictionary.value(LineColorInfo.identifier); } + auto reinitializeTrailBuffers = [this]() { + initializeGL(); + }; + + _path.onChange(reinitializeTrailBuffers); + _nSegments.onChange(reinitializeTrailBuffers); + addPropertySubOwner(_appearance); addProperty(_path); addProperty(_nSegments); - addProperty(_lineFade); } diff --git a/modules/space/rendering/renderablesatellites.h b/modules/space/rendering/renderablesatellites.h index e052683cfc..b2bf0864a0 100644 --- a/modules/space/rendering/renderablesatellites.h +++ b/modules/space/rendering/renderablesatellites.h @@ -113,8 +113,6 @@ private: properties::StringProperty _path; properties::UIntProperty _nSegments; - properties::DoubleProperty _lineFade; - RenderableTrail::Appearance _appearance; glm::vec3 _position; From b2d2039dc27e9e489ea74ced58e0aff4430cacf2 Mon Sep 17 00:00:00 2001 From: Lovisa Hassler Date: Fri, 13 Dec 2019 19:04:06 +0100 Subject: [PATCH 26/42] Trail fading for satellites and debris --- .../space/rendering/renderablesatellites.cpp | 22 ++++++++++++++----- .../space/rendering/renderablesatellites.h | 4 ---- modules/space/shaders/debrisViz_fs.glsl | 16 +++++++++++--- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/modules/space/rendering/renderablesatellites.cpp b/modules/space/rendering/renderablesatellites.cpp index 5476bf828f..9998db6b2c 100644 --- a/modules/space/rendering/renderablesatellites.cpp +++ b/modules/space/rendering/renderablesatellites.cpp @@ -308,7 +308,6 @@ RenderableSatellites::RenderableSatellites(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _path(PathInfo) , _nSegments(SegmentsInfo, 120, 4, 1024) - { documentation::testSpecificationAndThrow( Documentation(), @@ -322,6 +321,14 @@ RenderableSatellites::RenderableSatellites(const ghoul::Dictionary& dictionary) if (dictionary.hasKeyAndValue(LineColorInfo.identifier)) { _appearance.lineColor = dictionary.value(LineColorInfo.identifier); } + if (dictionary.hasKeyAndValue("FadeInfo")) { + _appearance.lineFade = static_cast( + dictionary.value("FadeInfo") + ); + } + else { + _appearance.lineFade = 20; + } auto reinitializeTrailBuffers = [this]() { initializeGL(); @@ -333,6 +340,9 @@ RenderableSatellites::RenderableSatellites(const ghoul::Dictionary& dictionary) addPropertySubOwner(_appearance); addProperty(_path); addProperty(_nSegments); + addProperty(_opacity); + + setRenderBin(Renderable::RenderBin::Overlay); } @@ -475,7 +485,6 @@ void RenderableSatellites::initializeGL() { _uniformCache.opacity = _programObject->uniformLocation("opacity"); updateBuffers(); - setRenderBin(Renderable::RenderBin::Overlay); } void RenderableSatellites::deinitializeGL() { @@ -514,9 +523,12 @@ void RenderableSatellites::render(const RenderData& data, RendererTasks&) { data.camera.combinedViewMatrix() * modelTransform ); + // Because we want the property to work similar to the planet trails + float fade = static_cast(pow(_appearance.lineFade.maxValue() - _appearance.lineFade, 2.0)); + _programObject->setUniform(_uniformCache.projection, data.camera.projectionMatrix()); _programObject->setUniform(_uniformCache.color, _appearance.lineColor); - _programObject->setUniform(_uniformCache.lineFade, _appearance.lineFade); + _programObject->setUniform(_uniformCache.lineFade, fade); glLineWidth(_appearance.lineWidth); @@ -595,10 +607,10 @@ void RenderableSatellites::updateBuffers() { ); glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(TrailVBOLayout), (GLvoid*)0); // stride : 4*sizeof(GL_FLOAT) + 2*sizeof(GL_DOUBLE) + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(TrailVBOLayout), nullptr); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_DOUBLE, GL_FALSE, sizeof(TrailVBOLayout), (GLvoid*)(4*sizeof(GL_FLOAT)) ); + glVertexAttribPointer(1, 2, GL_DOUBLE, GL_FALSE, sizeof(TrailVBOLayout), (GLvoid*)(4 * sizeof(GL_FLOAT))); glBindVertexArray(0); diff --git a/modules/space/rendering/renderablesatellites.h b/modules/space/rendering/renderablesatellites.h index b2bf0864a0..8f58d936d8 100644 --- a/modules/space/rendering/renderablesatellites.h +++ b/modules/space/rendering/renderablesatellites.h @@ -94,10 +94,6 @@ private: /// trail. std::vector _vertexBufferData; - /// The index array that is potentially used in the draw call. If this is empty, no - /// element draw call is used. - std::vector _indexBufferData; - GLuint _vertexArray; GLuint _vertexBuffer; GLuint _indexBuffer; diff --git a/modules/space/shaders/debrisViz_fs.glsl b/modules/space/shaders/debrisViz_fs.glsl index ada17beb95..e54886d99a 100644 --- a/modules/space/shaders/debrisViz_fs.glsl +++ b/modules/space/shaders/debrisViz_fs.glsl @@ -63,15 +63,25 @@ Fragment getFragment() { vertexDistance_f += 1.0; } - float invert = 1.0 - vertexDistance_f; - float fade = clamp(invert * lineFade, 0.0, 1.0); + float invert = pow((1.0 - vertexDistance_f), lineFade); + float fade = clamp(invert, 0.0, 1.0); + // Currently even fully transparent lines can occlude other lines, thus we discard + // these fragments since debris and satellites are rendered so close to each other + if (fade < 0.05) { + discard; + } Fragment frag; + + // Use additive blending for some values to make the discarding less abrupt + if (fade < 0.15) { + frag.blend = BLEND_MODE_ADDITIVE; + } + frag.color = vec4(color, fade * opacity); frag.depth = vs_position_w; frag.gPosition = viewSpacePosition; frag.gNormal = vec4(1, 1, 1, 0); - // frag.blend = BLEND_MODE_ADDITIVE; // to debug using colors use this if-statment. From cf3a64110399caa37b3289d716a8b2c852b27cfa Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 16 Dec 2019 09:50:34 +0100 Subject: [PATCH 27/42] Some small cleanup Remove virtual attribute from some of the raycaster functions --- data/assets/scene/milkyway/milkyway/volume.asset | 8 ++++---- include/openspace/rendering/volumeraycaster.h | 8 ++++---- modules/galaxy/rendering/renderablegalaxy.cpp | 5 ++--- src/rendering/framebufferrenderer.cpp | 4 +--- src/rendering/volumeraycaster.cpp | 16 ++++++++++++++++ 5 files changed, 27 insertions(+), 14 deletions(-) diff --git a/data/assets/scene/milkyway/milkyway/volume.asset b/data/assets/scene/milkyway/milkyway/volume.asset index adbd05e08a..2ae420e931 100644 --- a/data/assets/scene/milkyway/milkyway/volume.asset +++ b/data/assets/scene/milkyway/milkyway/volume.asset @@ -21,7 +21,7 @@ local MilkyWayVolumeGalaxy = { -- The center of the Milky Way is approximately 8 kiloparsec from the Sun. -- The x-axis of galactic coordinates points from the sun towards the center -- of the galaxy. - Position = {8 * kiloparsec, 0, 0} + Position = { 8 * kiloparsec, 0, 0 } } }, Renderable = { @@ -29,12 +29,12 @@ local MilkyWayVolumeGalaxy = { StepSize = 0.01, AbsorptionMultiply = 200, EmissionMultiply = 250, - Rotation = {3.1415926, 3.1248, 4.45741}, + Rotation = { 3.1415926, 3.1248, 4.45741 }, Volume = { Type = "Volume", Filename = data .. "/MilkyWayRGBAVolume1024x1024x128.raw", - Dimensions = {1024, 1024, 128}, - Size = {1.2E21, 1.2E21, 0.15E21}, + Dimensions = { 1024, 1024, 128 }, + Size = { 1.2E21, 1.2E21, 0.15E21 }, Downscale = 0.4, }, Points = { diff --git a/include/openspace/rendering/volumeraycaster.h b/include/openspace/rendering/volumeraycaster.h index 687a5f335a..aa1133606e 100644 --- a/include/openspace/rendering/volumeraycaster.h +++ b/include/openspace/rendering/volumeraycaster.h @@ -129,13 +129,13 @@ public: */ virtual std::string helperPath() const = 0; - virtual void setMaxSteps(int nsteps) { _rayCastMaxSteps = nsteps; }; + void setMaxSteps(int nsteps); - virtual const int maxSteps() const { return _rayCastMaxSteps; }; + int maxSteps() const; - virtual void setDownscaleRender(float value) { _downscaleRenderConst = value; }; + void setDownscaleRender(float value); - virtual const float downscaleRender() const { return _downscaleRenderConst; }; + float downscaleRender() const; private: /** diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 9dfe003559..71edb8d372 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -245,8 +245,7 @@ namespace openspace { ); } else { - LINFO("Number of raycasting steps not specified for Milkway Galaxy." - " Using default value."); + LINFO("Number of raycasting steps not specified. Using default value."); } _downScaleVolumeRendering.setVisibility( @@ -254,7 +253,7 @@ namespace openspace { ); if (volumeDictionary.hasKey(DownscaleVolumeRenderingInfo.identifier)) { _downScaleVolumeRendering = - volumeDictionary.value(DownscaleVolumeRenderingInfo.identifier); + volumeDictionary.value(DownscaleVolumeRenderingInfo.identifier); } if (!dictionary.hasKeyAndValue("Points")) { diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 3e145ecf5a..a6b327149b 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -1271,14 +1271,12 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector glViewport(0, 0, _resolution.x, _resolution.y); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _gBuffers.framebuffer); writeDownscaledVolume(); - } } } void FramebufferRenderer::performDeferredTasks( - const std::vector& tasks - ) + const std::vector& tasks) { for (const DeferredcasterTask& deferredcasterTask : tasks) { Deferredcaster* deferredcaster = deferredcasterTask.deferredcaster; diff --git a/src/rendering/volumeraycaster.cpp b/src/rendering/volumeraycaster.cpp index 17d13627c0..954bda7ac7 100644 --- a/src/rendering/volumeraycaster.cpp +++ b/src/rendering/volumeraycaster.cpp @@ -33,4 +33,20 @@ bool VolumeRaycaster::isCameraInside(const RenderData&, glm::vec3&) { return false; } +void VolumeRaycaster::setMaxSteps(int nsteps) { + _rayCastMaxSteps = nsteps; +} + +int VolumeRaycaster::maxSteps() const { + return _rayCastMaxSteps; +} + +void VolumeRaycaster::setDownscaleRender(float value) { + _downscaleRenderConst = value; +} + +float VolumeRaycaster::downscaleRender() const { + return _downscaleRenderConst; +} + } // namespace openspace From 2f1805b6514f81322c0343a6dc4627ac0ea387f3 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 16 Dec 2019 10:09:41 +0100 Subject: [PATCH 28/42] Some general cleanup of the code --- modules/touch/include/directinputsolver.h | 34 ++++++-------- modules/touch/include/touchinteraction.h | 4 +- modules/touch/src/directinputsolver.cpp | 56 +++++++++++++---------- modules/touch/src/touchinteraction.cpp | 54 +++++++++++++--------- modules/touch/src/win32_touch.cpp | 38 ++++++++++----- 5 files changed, 109 insertions(+), 77 deletions(-) diff --git a/modules/touch/include/directinputsolver.h b/modules/touch/include/directinputsolver.h index 418f01a535..50f5cbeceb 100644 --- a/modules/touch/include/directinputsolver.h +++ b/modules/touch/include/directinputsolver.h @@ -25,11 +25,8 @@ #ifndef __OPENSPACE_MODULE_TOUCH___DIRECTINPUT_SOLVER___H__ #define __OPENSPACE_MODULE_TOUCH___DIRECTINPUT_SOLVER___H__ - #include - #include - #include @@ -38,33 +35,30 @@ namespace openspace { class Camera; class SceneGraphNode; -// Stores the selected node, the cursor ID as well as the surface coordinates the -// cursor touched -struct SelectedBody { - long id; - SceneGraphNode* node; - glm::dvec3 coordinates; -}; - class DirectInputSolver { public: + // Stores the selected node, the cursor ID as well as the surface coordinates the + // cursor touched + struct SelectedBody { + long id; + SceneGraphNode* node; + glm::dvec3 coordinates; + }; + DirectInputSolver(); bool solve(const std::vector& list, - const std::vector& selectedBodies, - std::vector* calculatedValues, - const Camera& camera); - int getNDof() { return _nDof; } + const std::vector& selectedBodies, + std::vector* calculatedValues, const Camera& camera); + int getNDof() const; - const LMstat& getLevMarqStat() { return _lmstat; } - void setLevMarqVerbosity(bool verbose) { _lmstat.verbose = verbose; } + const LMstat& getLevMarqStat(); + void setLevMarqVerbosity(bool verbose); private: - int _nDof; + int _nDof = 0; LMstat _lmstat; }; - - } // openspace namespace #endif // __OPENSPACE_MODULE_TOUCH___DIRECTINPUT_SOLVER___H__ diff --git a/modules/touch/include/touchinteraction.h b/modules/touch/include/touchinteraction.h index 5cfddec46e..7158973b70 100644 --- a/modules/touch/include/touchinteraction.h +++ b/modules/touch/include/touchinteraction.h @@ -237,9 +237,9 @@ private: bool _zoomOutTap; bool _lmSuccess; bool _guiON; - std::vector _selected; + std::vector _selected; SceneGraphNode* _pickingSelected = nullptr; - std::unique_ptr _solver; + DirectInputSolver _solver; glm::dquat _toSlerp; glm::dvec3 _centroid; diff --git a/modules/touch/src/directinputsolver.cpp b/modules/touch/src/directinputsolver.cpp index 43624e6af6..6ceed7dac4 100644 --- a/modules/touch/src/directinputsolver.cpp +++ b/modules/touch/src/directinputsolver.cpp @@ -24,27 +24,24 @@ #include - #include #include +namespace { + // Used in the LM algorithm + struct FunctionData { + std::vector selectedPoints; + std::vector screenPoints; + int nDOF; + const openspace::Camera* camera; + openspace::SceneGraphNode* node; + LMstat stats; + }; +} namespace openspace { -// Used in the LM algorithm -struct FunctionData { - std::vector selectedPoints; - std::vector screenPoints; - int nDOF; - const Camera* camera; - SceneGraphNode* node; - LMstat stats; -}; - - -DirectInputSolver::DirectInputSolver() - : _nDof(0) -{ +DirectInputSolver::DirectInputSolver() { levmarq_init(&_lmstat); } @@ -106,8 +103,7 @@ double distToMinimize(double* par, int x, void* fdata, LMstat* lmstat) { dquat rotationDiffWorldSpace = globalCamRot * rotationDiffCamSpace * inverse(globalCamRot); - dvec3 rotationDiffVec3 = - centerToCamera * rotationDiffWorldSpace - centerToCamera; + dvec3 rotationDiffVec3 = centerToCamera * rotationDiffWorldSpace - centerToCamera; camPos += rotationDiffVec3; centerToCamera = camPos - centerPos; @@ -117,7 +113,8 @@ double distToMinimize(double* par, int x, void* fdata, LMstat* lmstat) { lookAtMat = lookAt( dvec3(0, 0, 0), directionToCenter, - lookUpWhenFacingCenter); + lookUpWhenFacingCenter + ); globalCamRot = normalize(quat_cast(inverse(lookAtMat))); } { // Zooming @@ -205,11 +202,9 @@ void gradient(double* g, double* par, int x, void* fdata, LMstat* lmstat) { } bool DirectInputSolver::solve(const std::vector& list, - const std::vector& selectedBodies, - std::vector *parameters, - const Camera &camera) + const std::vector& selectedBodies, + std::vector* parameters, const Camera& camera) { - int nFingers = std::min(static_cast(list.size()), 3); _nDof = std::min(nFingers * 2, 6); @@ -220,7 +215,10 @@ bool DirectInputSolver::solve(const std::vector& list, for (int i = 0; i < nFingers; ++i) { const SelectedBody& sb = selectedBodies.at(i); selectedPoints.push_back(sb.coordinates); - screenPoints.emplace_back(2 * (list[i].getX() - 0.5), -2 * (list[i].getY() - 0.5)); + screenPoints.emplace_back( + 2 * (list[i].getX() - 0.5), + -2 * (list[i].getY() - 0.5) + ); // This might be needed when we're directing the touchtable from another screen? // std::vector::const_iterator c = std::find_if( @@ -267,5 +265,17 @@ bool DirectInputSolver::solve(const std::vector& list, return result; } +int DirectInputSolver::getNDof() const { + return _nDof; +} + +const LMstat& DirectInputSolver::getLevMarqStat() { + return _lmstat; +} + +void DirectInputSolver::setLevMarqVerbosity(bool verbose) { + _lmstat.verbose = verbose; +} + } // openspace namespace diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index fa0cb44c56..eab3fa0185 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -322,7 +322,6 @@ TouchInteraction::TouchInteraction() , _zoomOutTap(false) , _lmSuccess(true) , _guiON(false) - , _solver(new DirectInputSolver()) #ifdef TOUCH_DEBUG_PROPERTIES , _debugProperties() #endif @@ -518,8 +517,8 @@ void TouchInteraction::directControl(const std::vector& list) { std::vector par(6, 0.0); par.at(0) = _lastVel.orbit.x; // use _lastVel for orbit par.at(1) = _lastVel.orbit.y; - _lmSuccess = _solver->solve(list, _selected, &par, *_camera); - int nDof = _solver->getNDof(); + _lmSuccess = _solver.solve(list, _selected, &par, *_camera); + int nDof = _solver.getNDof(); if (_lmSuccess && !_unitTest) { // if good values were found set new camera state @@ -574,7 +573,7 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { glm::dquat camToWorldSpace = _camera->rotationQuaternion(); glm::dvec3 camPos = _camera->positionVec3(); - std::vector newSelected; + std::vector newSelected; //node & distance std::tuple currentlyPicked = { @@ -594,24 +593,32 @@ void TouchInteraction::findSelectedNode(const std::vector& list) { long id = c.getSessionID(); for (SceneGraphNode* node : selectableNodes) { - double boundingSphereSquared = double(node->boundingSphere()) * double(node->boundingSphere()); + double boundingSphereSquared = static_cast(node->boundingSphere()) * + static_cast(node->boundingSphere()); glm::dvec3 camToSelectable = node->worldPosition() - camPos; double intersectionDist = 0.0; - bool intersected = glm::intersectRaySphere(camPos, raytrace, node->worldPosition(), - boundingSphereSquared, intersectionDist); + bool intersected = glm::intersectRaySphere( + camPos, + raytrace, + node->worldPosition(), + boundingSphereSquared, + intersectionDist + ); if (intersected) { glm::dvec3 intersectionPos = camPos + raytrace * intersectionDist; glm::dvec3 pointInModelView = glm::inverse(node->worldRotationMatrix()) * (intersectionPos - node->worldPosition()); // Add id, node and surface coordinates to the selected list - std::vector::iterator oldNode = std::find_if( + auto oldNode = std::find_if( newSelected.begin(), newSelected.end(), - [id](SelectedBody s) { return s.id == id; } + [id](const DirectInputSolver::SelectedBody& s) { return s.id == id; } ); if (oldNode != newSelected.end()) { - double oldNodeDist = glm::length(oldNode->node->worldPosition() - camPos); + double oldNodeDist = glm::length( + oldNode->node->worldPosition() - camPos + ); if (glm::length(camToSelectable) < oldNodeDist) { // new node is closer, remove added node and add the new one // instead @@ -1127,8 +1134,11 @@ void TouchInteraction::step(double dt) { else if (_zoomInLimit.value() < zoomInBounds) { // If zoom in limit is less than the estimated node radius we need to // make sure we do not get too close to possible height maps - SurfacePositionHandle posHandle = anchor->calculateSurfacePositionHandle(camPos); - glm::dvec3 centerToActualSurfaceModelSpace = posHandle.centerToReferenceSurface + + SurfacePositionHandle posHandle = anchor->calculateSurfacePositionHandle( + camPos + ); + glm::dvec3 centerToActualSurfaceModelSpace = + posHandle.centerToReferenceSurface + posHandle.referenceSurfaceOutDirection * posHandle.heightToSurface; glm::dvec3 centerToActualSurface = glm::dmat3(anchor->modelTransform()) * centerToActualSurfaceModelSpace; @@ -1137,9 +1147,8 @@ void TouchInteraction::step(double dt) { // Because of heightmaps we should make sure we do not go through the surface if (_zoomInLimit.value() < nodeRadius) { #ifdef TOUCH_DEBUG_PROPERTIES - LINFO(fmt::format( - "{}: Zoom In Limit should be larger than anchor center to surface, setting it to {}", - _loggerCat, zoomInBounds)); + LINFO(fmt::format("{}: Zoom In limit should be larger than anchor " + "center to surface, setting it to {}", _loggerCat, zoomInBounds)); #endif _zoomInLimit.setValue(zoomInBounds); } @@ -1159,9 +1168,12 @@ void TouchInteraction::step(double dt) { double currentPosDistance = length(centerToCamera); // Possible with other navigations performed outside touch interaction - bool currentPosViolatingZoomOutLimit = (currentPosDistance >= _zoomOutLimit.value()); - bool willNewPositionViolateZoomOutLimit = (newPosDistance >= _zoomOutLimit.value()); - bool willNewPositionViolateZoomInLimit = (newPosDistance < _zoomInLimit.value()); + bool currentPosViolatingZoomOutLimit = + (currentPosDistance >= _zoomOutLimit.value()); + bool willNewPositionViolateZoomOutLimit = + (newPosDistance >= _zoomOutLimit.value()); + bool willNewPositionViolateZoomInLimit = + (newPosDistance < _zoomInLimit.value()); if (!willNewPositionViolateZoomInLimit && !willNewPositionViolateZoomOutLimit){ camPos += zoomDistanceIncrement; @@ -1214,7 +1226,7 @@ void TouchInteraction::step(double dt) { void TouchInteraction::unitTest() { if (_unitTest) { - _solver->setLevMarqVerbosity(true); + _solver.setLevMarqVerbosity(true); // set _selected pos and new pos (on screen) std::vector lastFrame = { @@ -1235,7 +1247,7 @@ void TouchInteraction::unitTest() { snprintf(buffer, sizeof(char) * 32, "lmdata%i.csv", _numOfTests); _numOfTests++; std::ofstream file(buffer); - file << _solver->getLevMarqStat().data; + file << _solver.getLevMarqStat().data; // clear everything _selected.clear(); @@ -1247,7 +1259,7 @@ void TouchInteraction::unitTest() { _lastVel = _vel; _unitTest = false; - _solver->setLevMarqVerbosity(false); + _solver.setLevMarqVerbosity(false); // could be the camera copy in func } } diff --git a/modules/touch/src/win32_touch.cpp b/modules/touch/src/win32_touch.cpp index 32331c8bb3..03ded0a114 100644 --- a/modules/touch/src/win32_touch.cpp +++ b/modules/touch/src/win32_touch.cpp @@ -28,11 +28,8 @@ #include #include - #include - #include - #include #include @@ -42,7 +39,7 @@ namespace { bool gStarted{ false }; TUIO::TuioServer* gTuioServer{ nullptr }; std::unordered_map gCursorMap; -} +} // namespace namespace openspace { @@ -69,22 +66,32 @@ LRESULT CALLBACK HookCallback(int nCode, WPARAM wParam, LPARAM lParam) { // native touch to screen conversion ScreenToClient(pStruct->hwnd, reinterpret_cast(&p)); - float xPos = static_cast(p.x) / static_cast(rect.right - rect.left); - float yPos = static_cast(p.y) / static_cast(rect.bottom - rect.top); + float xPos = static_cast(p.x) / + static_cast(rect.right - rect.left); + float yPos = static_cast(p.y) / + static_cast(rect.bottom - rect.top); if (pointerInfo.pointerFlags & POINTER_FLAG_DOWN) { // Handle new touchpoint gTuioServer->initFrame(TUIO::TuioTime::getSessionTime()); - gCursorMap[pointerInfo.pointerId] = gTuioServer->addTuioCursor(xPos, yPos); + gCursorMap[pointerInfo.pointerId] = gTuioServer->addTuioCursor( + xPos, + yPos + ); gTuioServer->commitFrame(); } else if (pointerInfo.pointerFlags & POINTER_FLAG_UPDATE) { // Handle update of touchpoint TUIO::TuioTime frameTime = TUIO::TuioTime::getSessionTime(); - if (gCursorMap[pointerInfo.pointerId]->getTuioTime() == frameTime) { + if (gCursorMap[pointerInfo.pointerId]->getTuioTime() == frameTime) + { break; } gTuioServer->initFrame(frameTime); - gTuioServer->updateTuioCursor(gCursorMap[pointerInfo.pointerId], xPos, yPos); + gTuioServer->updateTuioCursor( + gCursorMap[pointerInfo.pointerId], + xPos, + yPos + ); gTuioServer->commitFrame(); } else if (pointerInfo.pointerFlags & POINTER_FLAG_UP) { @@ -139,14 +146,23 @@ Win32TouchHook::Win32TouchHook(void* nativeWindow) const DWORD dwHwndTabletProperty = TABLET_DISABLE_PRESSANDHOLD; ATOM atom = ::GlobalAddAtom(MICROSOFT_TABLETPENSERVICE_PROPERTY); - ::SetProp(hWnd, MICROSOFT_TABLETPENSERVICE_PROPERTY, reinterpret_cast(dwHwndTabletProperty)); + ::SetProp( + hWnd, + MICROSOFT_TABLETPENSERVICE_PROPERTY, + reinterpret_cast(dwHwndTabletProperty) + ); ::GlobalDeleteAtom(atom); if (!gStarted) { gStarted = true; gTuioServer = new TUIO::TuioServer("localhost", 3333); TUIO::TuioTime::initSession(); - gTouchHook = SetWindowsHookExW(WH_GETMESSAGE, HookCallback, GetModuleHandleW(NULL), GetCurrentThreadId()); + gTouchHook = SetWindowsHookExW( + WH_GETMESSAGE, + HookCallback, + GetModuleHandleW(NULL), + GetCurrentThreadId() + ); if (!gTouchHook) { LINFO(fmt::format("Failed to setup WindowsHook for touch input redirection")); delete gTuioServer; From dfa25b28e6c3ff83efce435790268ec74fb67544 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 16 Dec 2019 10:26:42 +0100 Subject: [PATCH 29/42] Disable labels on default Some small code cleanup --- .../dwarf_planets/pluto/pluto.asset | 20 +-- .../solarsystem/planets/earth/earth.asset | 10 +- .../solarsystem/planets/jupiter/jupiter.asset | 22 +-- .../scene/solarsystem/planets/mars/mars.asset | 14 +- .../solarsystem/planets/mercury/mercury.asset | 22 +-- .../solarsystem/planets/neptune/neptune.asset | 22 +-- .../solarsystem/planets/saturn/saturn.asset | 22 +-- .../solarsystem/planets/uranus/uranus.asset | 22 +-- .../solarsystem/planets/venus/venus.asset | 22 +-- data/assets/scene/solarsystem/sun/sun.asset | 10 +- modules/base/rendering/renderablelabels.cpp | 143 ++++++++++-------- modules/base/rendering/renderablelabels.h | 68 ++++----- 12 files changed, 129 insertions(+), 268 deletions(-) diff --git a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset index 8f2d2f3036..db18a54cc1 100644 --- a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset +++ b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset @@ -62,18 +62,6 @@ local Pluto = { local PlutoLabel = { Identifier = "PlutoLabel", Parent = Pluto.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { Enabled = true, Type = "RenderableLabels", @@ -83,13 +71,7 @@ local PlutoLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, BlendMode = "Additive", - LabelOrientationOption = "Camera View Direction", - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + LabelOrientationOption = "Camera View Direction" }, GUI = { Name = "Pluto Label", diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index 1b735b3e66..dc14382046 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -303,7 +303,7 @@ local EarthLabel = { -- -- } -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Earth", FontSize = 100.0, @@ -318,13 +318,7 @@ local EarthLabel = { FadeStartSpeed = 1.0, FadeEndUnit = "au", FadeEndDistance = 15.0, - FadeEndSpeed = 25.0, - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + FadeEndSpeed = 25.0 }, GUI = { Name = "Earth Label", diff --git a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset index 1996531c87..1ce8b88fff 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset @@ -45,20 +45,8 @@ local Jupiter = { local JupiterLabel = { Identifier = "JupiterLabel", Parent = Jupiter.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Jupiter", FontSize = 100.0, @@ -66,13 +54,7 @@ local JupiterLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, LabelOrientationOption = "Camera View Direction", - BlendMode = "Additive", - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + BlendMode = "Additive" }, GUI = { Name = "Jupiter Label", diff --git a/data/assets/scene/solarsystem/planets/mars/mars.asset b/data/assets/scene/solarsystem/planets/mars/mars.asset index 0575f88e03..cee87159c5 100644 --- a/data/assets/scene/solarsystem/planets/mars/mars.asset +++ b/data/assets/scene/solarsystem/planets/mars/mars.asset @@ -190,20 +190,8 @@ local Mars = { local MarsLabel = { Identifier = "MarsLabel", Parent = Mars.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Mars", FontSize = 100.0, diff --git a/data/assets/scene/solarsystem/planets/mercury/mercury.asset b/data/assets/scene/solarsystem/planets/mercury/mercury.asset index 1d24fa241d..98bd538f33 100644 --- a/data/assets/scene/solarsystem/planets/mercury/mercury.asset +++ b/data/assets/scene/solarsystem/planets/mercury/mercury.asset @@ -226,20 +226,8 @@ local Mercury = { local MercuryLabel = { Identifier = "MercuryLabel", Parent = Mercury.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Mercury", FontSize = 100.0, @@ -247,13 +235,7 @@ local MercuryLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, LabelOrientationOption = "Camera View Direction", - BlendMode = "Additive", - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + BlendMode = "Additive" }, GUI = { Name = "Mercury Label", diff --git a/data/assets/scene/solarsystem/planets/neptune/neptune.asset b/data/assets/scene/solarsystem/planets/neptune/neptune.asset index 5e617b7286..a7546d5f2a 100644 --- a/data/assets/scene/solarsystem/planets/neptune/neptune.asset +++ b/data/assets/scene/solarsystem/planets/neptune/neptune.asset @@ -43,20 +43,8 @@ local Neptune = { local NeptuneLabel = { Identifier = "NeptuneLabel", Parent = Neptune.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Neptune", FontSize = 100.0, @@ -64,13 +52,7 @@ local NeptuneLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, LabelOrientationOption = "Camera View Direction", - BlendMode = "Additive", - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + BlendMode = "Additive" }, GUI = { Name = "Neptune Label", diff --git a/data/assets/scene/solarsystem/planets/saturn/saturn.asset b/data/assets/scene/solarsystem/planets/saturn/saturn.asset index 22a223eb3a..853bd1ce8b 100644 --- a/data/assets/scene/solarsystem/planets/saturn/saturn.asset +++ b/data/assets/scene/solarsystem/planets/saturn/saturn.asset @@ -60,20 +60,8 @@ local SaturnRings = { local SaturnLabel = { Identifier = "SaturnLabel", Parent = Saturn.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Saturn", FontSize = 100.0, @@ -81,13 +69,7 @@ local SaturnLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, BlendMode = "Additive", - LabelOrientationOption = "Camera View Direction", - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + LabelOrientationOption = "Camera View Direction" }, GUI = { Name = "Saturn Label", diff --git a/data/assets/scene/solarsystem/planets/uranus/uranus.asset b/data/assets/scene/solarsystem/planets/uranus/uranus.asset index f522c2fa89..758f87f998 100644 --- a/data/assets/scene/solarsystem/planets/uranus/uranus.asset +++ b/data/assets/scene/solarsystem/planets/uranus/uranus.asset @@ -45,20 +45,8 @@ local Uranus = { local UranusLabel = { Identifier = "UranusLabel", Parent = Uranus.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Uranus", FontSize = 100.0, @@ -66,13 +54,7 @@ local UranusLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, LabelOrientationOption = "Camera View Direction", - BlendMode = "Additive", - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + BlendMode = "Additive" }, GUI = { Name = "Neptune Label", diff --git a/data/assets/scene/solarsystem/planets/venus/venus.asset b/data/assets/scene/solarsystem/planets/venus/venus.asset index 3572c07083..52cfe29303 100644 --- a/data/assets/scene/solarsystem/planets/venus/venus.asset +++ b/data/assets/scene/solarsystem/planets/venus/venus.asset @@ -67,20 +67,8 @@ local Venus = { local VenusLabel = { Identifier = "VenusLabel", Parent = Venus.Identifier, - -- Transform = { - -- Translation = { - -- Type = "SpiceTranslation", - -- Target = "EARTH", - -- Observer = "EARTH BARYCENTER" - -- }, - -- -- Rotation = { - -- -- Type = "SpiceRotation", - -- -- SourceFrame = "IAU_MOON", - -- -- DestinationFrame = "GALACTIC" - -- -- } - -- }, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Venus", FontSize = 100.0, @@ -88,13 +76,7 @@ local VenusLabel = { LabelMaxSize = 100.0, LabelMinSize = 1.0, LabelOrientationOption = "Camera View Direction", - BlendMode = "Additive", - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + BlendMode = "Additive" }, GUI = { Name = "Venus Label", diff --git a/data/assets/scene/solarsystem/sun/sun.asset b/data/assets/scene/solarsystem/sun/sun.asset index 0ca4e4a8be..9d44fb2462 100644 --- a/data/assets/scene/solarsystem/sun/sun.asset +++ b/data/assets/scene/solarsystem/sun/sun.asset @@ -31,7 +31,7 @@ local SunLabel = { Identifier = "SunLabel", Parent = Sun.Identifier, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Sun", FontSize = 100.0, @@ -46,13 +46,7 @@ local SunLabel = { FadeStartSpeed = 1.375, FadeEndUnit = "pc", FadeEndDistance = 1.326, - FadeEndSpeed = 1.0, - TransformationMatrix = { - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 - }, + FadeEndSpeed = 1.0 }, GUI = { Name = "Sun Label", diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp index a5b33f2624..5c8bbd20ae 100644 --- a/modules/base/rendering/renderablelabels.cpp +++ b/modules/base/rendering/renderablelabels.cpp @@ -193,7 +193,9 @@ documentation::Documentation RenderableLabels::Documentation() { }, { LabelOrientationOptionInfo.identifier, - new StringInListVerifier({ "Camera View Direction", "Camera Position Normal" }), + new StringInListVerifier( + { "Camera View Direction", "Camera Position Normal" } + ), Optional::Yes, LabelOrientationOptionInfo.description, }, @@ -253,13 +255,19 @@ documentation::Documentation RenderableLabels::Documentation() { }, { FadeStartUnitOptionInfo.identifier, - new StringInListVerifier({"m", "Km", "Mm", "Gm", "au", "Tm", "Pm", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), + new StringInListVerifier( + { "m", "Km", "Mm", "Gm", "au", "Tm", "Pm", "pc", "Kpc", "Mpc", + "Gpc", "Gly"} + ), Optional::Yes, FadeStartUnitOptionInfo.description, }, { FadeEndUnitOptionInfo.identifier, - new StringInListVerifier({"m", "Km", "Mm", "Gm", "au", "Tm", "Pm", "pc", "Kpc", "Mpc", "Gpc", "Gly"}), + new StringInListVerifier( + {"m", "Km", "Mm", "Gm", "au", "Tm", "Pm", "pc", "Kpc", "Mpc", + "Gpc", "Gly"} + ), Optional::Yes, FadeEndUnitOptionInfo.description, }, @@ -311,9 +319,18 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) , _fadeEndDistance(FadeEndDistInfo, 1.f, 0.f, 100.f) , _fadeStartSpeed(FadeStartSpeedInfo, 1.f, 1.f, 100.f) , _fadeEndSpeed(FadeEndSpeedInfo, 1.f, 1.f, 100.f) - , _labelOrientationOption(LabelOrientationOptionInfo, properties::OptionProperty::DisplayType::Dropdown) - , _fadeStartUnitOption(FadeStartUnitOptionInfo, properties::OptionProperty::DisplayType::Dropdown) - , _fadeEndUnitOption(FadeEndUnitOptionInfo, properties::OptionProperty::DisplayType::Dropdown) + , _labelOrientationOption( + LabelOrientationOptionInfo, + properties::OptionProperty::DisplayType::Dropdown + ) + , _fadeStartUnitOption( + FadeStartUnitOptionInfo, + properties::OptionProperty::DisplayType::Dropdown + ) + , _fadeEndUnitOption( + FadeEndUnitOptionInfo, + properties::OptionProperty::DisplayType::Dropdown + ) { documentation::testSpecificationAndThrow( Documentation(), @@ -357,7 +374,9 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) _labelOrientationOption = NormalDirection; if (dictionary.hasKeyAndValue(LabelOrientationOptionInfo.identifier)) { - const std::string o = dictionary.value(LabelOrientationOptionInfo.identifier); + const std::string o = dictionary.value( + LabelOrientationOptionInfo.identifier + ); if (o == "Camera View Direction") { _labelOrientationOption = ViewDirection; @@ -446,7 +465,9 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) _fadeStartUnitOption = AU; if (dictionary.hasKey(FadeStartUnitOptionInfo.identifier)) { - std::string unit = dictionary.value(FadeStartUnitOptionInfo.identifier); + std::string unit = dictionary.value( + FadeStartUnitOptionInfo.identifier + ); if (unit == MeterUnit) { _fadeStartUnitOption = Meter; } @@ -521,7 +542,9 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) _fadeEndUnitOption = AU; if (dictionary.hasKey(FadeEndUnitOptionInfo.identifier)) { - std::string unit = dictionary.value(FadeEndUnitOptionInfo.identifier); + std::string unit = dictionary.value( + FadeEndUnitOptionInfo.identifier + ); if (unit == MeterUnit) { _fadeEndUnitOption = Meter; } @@ -573,9 +596,6 @@ RenderableLabels::RenderableLabels(const ghoul::Dictionary& dictionary) } addProperty(_fadeEndSpeed); - - - //setBoundingSphere(_size); } bool RenderableLabels::isReady() const { @@ -603,8 +623,7 @@ void RenderableLabels::initializeGL() { } } -void RenderableLabels::deinitializeGL() { -} +void RenderableLabels::deinitializeGL() {} void RenderableLabels::render(const RenderData& data, RendererTasks&) { @@ -626,7 +645,13 @@ void RenderableLabels::render(const RenderData& data, RendererTasks&) { float startX = _fadeStartDistance * sUnit; float endX = _fadeEndDistance * eUnit; //fadeInVariable = changedPerlinSmoothStepFunc(distanceNodeToCamera, startX, endX); - fadeInVariable = linearSmoothStepFunc(distanceNodeToCamera, startX, endX, sUnit, eUnit); + fadeInVariable = linearSmoothStepFunc( + distanceNodeToCamera, + startX, + endX, + sUnit, + eUnit + ); } glm::dmat4 modelMatrix(1.0); @@ -668,8 +693,7 @@ void RenderableLabels::setLabelText(const std::string & newText) { void RenderableLabels::renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, const glm::dvec3& orthoRight, - const glm::dvec3& orthoUp, - float fadeInVariable) + const glm::dvec3& orthoUp, float fadeInVariable) { glm::vec4 textColor = _labelColor; @@ -704,9 +728,8 @@ void RenderableLabels::renderLabels(const RenderData& data, ); } -float RenderableLabels::changedPerlinSmoothStepFunc(const float x, - const float startX, - const float endX) const +float RenderableLabels::changedPerlinSmoothStepFunc(float x, float startX, + float endX) const { float f1 = 6.f * powf((x - startX), 5.f) - 15.f * powf((x - startX), 4.f) + 10.f * powf((x - startX), 3.f); @@ -725,11 +748,8 @@ float RenderableLabels::changedPerlinSmoothStepFunc(const float x, } } -float RenderableLabels::linearSmoothStepFunc(const float x, - const float startX, - const float endX, - const float sUnit, - const float eUnit) const +float RenderableLabels::linearSmoothStepFunc(float x, float startX, float endX, + float sUnit, float eUnit) const { float sdiv = 1.f / (sUnit * _fadeStartSpeed); float ediv = -1.f / (eUnit * _fadeEndSpeed); @@ -752,44 +772,45 @@ float RenderableLabels::getUnit(int unit) const { float scale = 0.f; switch (static_cast(unit)) { - case Meter: - scale = 1.f; - break; - case Kilometer: - scale = 1e3; - break; - case Megameter: - scale = 1e6; - break; - case Gigameter: - scale = 1e9; - break; - case AU: - scale = 149597870700.f; - break; - case Terameter: - scale = 1e12; - break; - case Petameter: - scale = 1e15; - break; - case Parsec: - scale = static_cast(PARSEC); - break; - case Kiloparsec: - scale = static_cast(1e3 * PARSEC); - break; - case Megaparsec: - scale = static_cast(1e6 * PARSEC); - break; - case Gigaparsec: - scale = static_cast(1e9 * PARSEC); - break; - case GigalightYears: - scale = static_cast(306391534.73091 * PARSEC); - break; + case Meter: + scale = 1.f; + break; + case Kilometer: + scale = 1e3; + break; + case Megameter: + scale = 1e6; + break; + case Gigameter: + scale = 1e9; + break; + case AU: + scale = 149597870700.f; + break; + case Terameter: + scale = 1e12; + break; + case Petameter: + scale = 1e15; + break; + case Parsec: + scale = static_cast(PARSEC); + break; + case Kiloparsec: + scale = static_cast(1e3 * PARSEC); + break; + case Megaparsec: + scale = static_cast(1e6 * PARSEC); + break; + case Gigaparsec: + scale = static_cast(1e9 * PARSEC); + break; + case GigalightYears: + scale = static_cast(306391534.73091 * PARSEC); + break; } return scale; } + } // namespace openspace diff --git a/modules/base/rendering/renderablelabels.h b/modules/base/rendering/renderablelabels.h index c0fa9848e9..0f5bbf6f99 100644 --- a/modules/base/rendering/renderablelabels.h +++ b/modules/base/rendering/renderablelabels.h @@ -54,22 +54,6 @@ namespace documentation { struct Documentation; } struct LinePoint; class RenderableLabels : public Renderable { -private: - enum Unit { - Meter = 0, - Kilometer = 1, - Megameter = 2, - Gigameter = 3, - AU = 4, - Terameter = 5, - Petameter = 6, - Parsec = 7, - Kiloparsec = 8, - Megaparsec = 9, - Gigaparsec = 10, - GigalightYears = 11 - }; - public: RenderableLabels(const ghoul::Dictionary& dictionary); @@ -90,37 +74,43 @@ protected: properties::OptionProperty _blendMode; private: + enum Unit { + Meter = 0, + Kilometer, + Megameter, + Gigameter, + AU, + Terameter, + Petameter, + Parsec, + Kiloparsec, + Megaparsec, + Gigaparsec, + GigalightYears + }; + void renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable); - float changedPerlinSmoothStepFunc( - const float x, - const float startX, - const float endX - ) const; + float changedPerlinSmoothStepFunc(float x, float startX, float endX) const; - float linearSmoothStepFunc( - const float x, - const float startX, - const float endX, - const float sUnit, - const float eUnit - ) const; + float linearSmoothStepFunc(float x, float startX, float endX, float sUnit, + float eUnit) const; float getUnit(int unit) const; - properties::Vec4Property _labelColor; - properties::FloatProperty _labelSize; - properties::FloatProperty _fontSize; - properties::FloatProperty _labelMinSize; - properties::FloatProperty _labelMaxSize; - properties::BoolProperty _pixelSizeControl; - properties::BoolProperty _enableFadingEffect; + properties::Vec4Property _labelColor; + properties::FloatProperty _labelSize; + properties::FloatProperty _fontSize; + properties::FloatProperty _labelMinSize; + properties::FloatProperty _labelMaxSize; + properties::BoolProperty _pixelSizeControl; + properties::BoolProperty _enableFadingEffect; properties::StringProperty _labelText; - properties::FloatProperty _fadeStartDistance; - properties::FloatProperty _fadeEndDistance; - properties::FloatProperty _fadeStartSpeed; - properties::FloatProperty _fadeEndSpeed; + properties::FloatProperty _fadeStartDistance; + properties::FloatProperty _fadeEndDistance; + properties::FloatProperty _fadeStartSpeed; + properties::FloatProperty _fadeEndSpeed; properties::OptionProperty _labelOrientationOption; properties::OptionProperty _fadeStartUnitOption; From bfc2da3475160f2741a2964f6df140c815fc288d Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 16 Dec 2019 10:38:10 +0100 Subject: [PATCH 30/42] Make a defaut keybind for toggling the labels --- data/assets/base.asset | 16 ++++++++++++++++ .../scene/solarsystem/planets/earth/earth.asset | 1 + .../solarsystem/planets/jupiter/jupiter.asset | 1 + .../scene/solarsystem/planets/mars/mars.asset | 1 + .../solarsystem/planets/mercury/mercury.asset | 1 + .../solarsystem/planets/neptune/neptune.asset | 1 + .../solarsystem/planets/saturn/saturn.asset | 1 + .../solarsystem/planets/uranus/uranus.asset | 1 + .../scene/solarsystem/planets/venus/venus.asset | 1 + data/assets/scene/solarsystem/sun/sun.asset | 1 + 10 files changed, 25 insertions(+) diff --git a/data/assets/base.asset b/data/assets/base.asset index 73e2db77ab..6ef26ab294 100644 --- a/data/assets/base.asset +++ b/data/assets/base.asset @@ -63,6 +63,22 @@ local Keybindings = { GuiPath = "/Rendering", Local = false }, + { + Key = "l", + Name = "Turn on labels", + Command = "openspace.setPropertyValue('{solarsystem_labels}.Renderable.Enabled', true)", + Documentation = "Turns on visibility for all solar system labels", + GuiPath = "/Rendering", + Local = false + }, + { + Key = "Shift+l", + Name = "Turn off labels", + Command = "openspace.setPropertyValue('{solarsystem_labels}.Renderable.Enabled', false)", + Documentation = "Turns off visibility for all solar system labels", + GuiPath = "/Rendering", + Local = false + } } asset.onInitialize(function () diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index dc14382046..c604a102ce 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -320,6 +320,7 @@ local EarthLabel = { FadeEndDistance = 15.0, FadeEndSpeed = 25.0 }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Earth Label", Path = "/Solar System/Planets/Earth" diff --git a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset index 1ce8b88fff..071a9cad9f 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/jupiter.asset @@ -56,6 +56,7 @@ local JupiterLabel = { LabelOrientationOption = "Camera View Direction", BlendMode = "Additive" }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Jupiter Label", Path = "/Solar System/Planets/Jupiter" diff --git a/data/assets/scene/solarsystem/planets/mars/mars.asset b/data/assets/scene/solarsystem/planets/mars/mars.asset index cee87159c5..4c2e8dcd76 100644 --- a/data/assets/scene/solarsystem/planets/mars/mars.asset +++ b/data/assets/scene/solarsystem/planets/mars/mars.asset @@ -207,6 +207,7 @@ local MarsLabel = { 0.0, 0.0, 0.0, 1.0 }, }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Mars Label", Path = "/Solar System/Planets/Mars" diff --git a/data/assets/scene/solarsystem/planets/mercury/mercury.asset b/data/assets/scene/solarsystem/planets/mercury/mercury.asset index 98bd538f33..93924f8444 100644 --- a/data/assets/scene/solarsystem/planets/mercury/mercury.asset +++ b/data/assets/scene/solarsystem/planets/mercury/mercury.asset @@ -237,6 +237,7 @@ local MercuryLabel = { LabelOrientationOption = "Camera View Direction", BlendMode = "Additive" }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Mercury Label", Path = "/Solar System/Planets/Mercury" diff --git a/data/assets/scene/solarsystem/planets/neptune/neptune.asset b/data/assets/scene/solarsystem/planets/neptune/neptune.asset index a7546d5f2a..326b2ef6c0 100644 --- a/data/assets/scene/solarsystem/planets/neptune/neptune.asset +++ b/data/assets/scene/solarsystem/planets/neptune/neptune.asset @@ -54,6 +54,7 @@ local NeptuneLabel = { LabelOrientationOption = "Camera View Direction", BlendMode = "Additive" }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Neptune Label", Path = "/Solar System/Planets/Neptune" diff --git a/data/assets/scene/solarsystem/planets/saturn/saturn.asset b/data/assets/scene/solarsystem/planets/saturn/saturn.asset index 853bd1ce8b..aabfe92b81 100644 --- a/data/assets/scene/solarsystem/planets/saturn/saturn.asset +++ b/data/assets/scene/solarsystem/planets/saturn/saturn.asset @@ -71,6 +71,7 @@ local SaturnLabel = { BlendMode = "Additive", LabelOrientationOption = "Camera View Direction" }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Saturn Label", Path = "/Solar System/Planets/Saturn" diff --git a/data/assets/scene/solarsystem/planets/uranus/uranus.asset b/data/assets/scene/solarsystem/planets/uranus/uranus.asset index 758f87f998..db3fb11848 100644 --- a/data/assets/scene/solarsystem/planets/uranus/uranus.asset +++ b/data/assets/scene/solarsystem/planets/uranus/uranus.asset @@ -56,6 +56,7 @@ local UranusLabel = { LabelOrientationOption = "Camera View Direction", BlendMode = "Additive" }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Neptune Label", Path = "/Solar System/Planets/Uranus" diff --git a/data/assets/scene/solarsystem/planets/venus/venus.asset b/data/assets/scene/solarsystem/planets/venus/venus.asset index 52cfe29303..f3e1f83fed 100644 --- a/data/assets/scene/solarsystem/planets/venus/venus.asset +++ b/data/assets/scene/solarsystem/planets/venus/venus.asset @@ -78,6 +78,7 @@ local VenusLabel = { LabelOrientationOption = "Camera View Direction", BlendMode = "Additive" }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Venus Label", Path = "/Solar System/Planets/Venus" diff --git a/data/assets/scene/solarsystem/sun/sun.asset b/data/assets/scene/solarsystem/sun/sun.asset index 9d44fb2462..10c0ff4aec 100644 --- a/data/assets/scene/solarsystem/sun/sun.asset +++ b/data/assets/scene/solarsystem/sun/sun.asset @@ -48,6 +48,7 @@ local SunLabel = { FadeEndDistance = 1.326, FadeEndSpeed = 1.0 }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Sun Label", Path = "/Solar System/Sun" From 4f2883034ba39617e1fb02838d8f194f29c81033 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 16 Dec 2019 10:51:38 +0100 Subject: [PATCH 31/42] Rename labels assets to globe_labels --- data/assets/scene/solarsystem/planets/earth/earth.asset | 2 +- .../earth/{earth_labels.asset => earth_globelabels.asset} | 0 .../scene/solarsystem/planets/jupiter/callisto/callisto.asset | 2 +- .../scene/solarsystem/planets/jupiter/europa/europa.asset | 2 +- .../scene/solarsystem/planets/jupiter/ganymede/ganymede.asset | 2 +- data/assets/scene/solarsystem/planets/jupiter/io/io.asset | 2 +- .../jupiter/{jupiter_labels.asset => jupiter_globelabels.asset} | 0 data/assets/scene/solarsystem/planets/mars/mars.asset | 2 +- .../planets/mars/{mars_labels.asset => mars_globelabels.asset} | 0 data/assets/scene/solarsystem/planets/mercury/mercury.asset | 2 +- .../mercury/{mercury_labels.asset => mercury_globelabels.asset} | 0 data/assets/scene/solarsystem/planets/saturn/dione/dione.asset | 2 +- .../scene/solarsystem/planets/saturn/enceladus/enceladus.asset | 2 +- .../scene/solarsystem/planets/saturn/iapetus/iapetus.asset | 2 +- data/assets/scene/solarsystem/planets/saturn/mimas/mimas.asset | 2 +- data/assets/scene/solarsystem/planets/saturn/rhea/rhea.asset | 2 +- .../saturn/{saturn_labels.asset => saturn_globelabels.asset} | 0 .../assets/scene/solarsystem/planets/saturn/tethys/tethys.asset | 2 +- data/assets/scene/solarsystem/planets/saturn/titan/titan.asset | 2 +- data/assets/scene/solarsystem/planets/venus/venus.asset | 2 +- .../venus/{venus_labels.asset => venus_globelabels.asset} | 0 21 files changed, 15 insertions(+), 15 deletions(-) rename data/assets/scene/solarsystem/planets/earth/{earth_labels.asset => earth_globelabels.asset} (100%) rename data/assets/scene/solarsystem/planets/jupiter/{jupiter_labels.asset => jupiter_globelabels.asset} (100%) rename data/assets/scene/solarsystem/planets/mars/{mars_labels.asset => mars_globelabels.asset} (100%) rename data/assets/scene/solarsystem/planets/mercury/{mercury_labels.asset => mercury_globelabels.asset} (100%) rename data/assets/scene/solarsystem/planets/saturn/{saturn_labels.asset => saturn_globelabels.asset} (100%) rename data/assets/scene/solarsystem/planets/venus/{venus_labels.asset => venus_globelabels.asset} (100%) diff --git a/data/assets/scene/solarsystem/planets/earth/earth.asset b/data/assets/scene/solarsystem/planets/earth/earth.asset index c604a102ce..aab7c67f07 100644 --- a/data/assets/scene/solarsystem/planets/earth/earth.asset +++ b/data/assets/scene/solarsystem/planets/earth/earth.asset @@ -1,7 +1,7 @@ local transforms = asset.require('./transforms') local assetHelper = asset.require('util/asset_helper') local texturesPath = asset.require('./earth_textures').TexturesPath -local labelsPath = asset.require('./earth_labels').LabelsPath +local labelsPath = asset.require('./earth_globelabels').LabelsPath asset.request('./trail') diff --git a/data/assets/scene/solarsystem/planets/earth/earth_labels.asset b/data/assets/scene/solarsystem/planets/earth/earth_globelabels.asset similarity index 100% rename from data/assets/scene/solarsystem/planets/earth/earth_labels.asset rename to data/assets/scene/solarsystem/planets/earth/earth_globelabels.asset diff --git a/data/assets/scene/solarsystem/planets/jupiter/callisto/callisto.asset b/data/assets/scene/solarsystem/planets/jupiter/callisto/callisto.asset index 1a31062cd1..d0b2496e52 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/callisto/callisto.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/callisto/callisto.asset @@ -3,7 +3,7 @@ local assetHelper = asset.require('util/asset_helper') asset.require("spice/base") asset.request('./trail') local kernel = asset.require('../kernels').jup310 -local labelsPath = asset.require('../jupiter_labels').LabelsPath +local labelsPath = asset.require('../jupiter_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/jupiter/europa/europa.asset b/data/assets/scene/solarsystem/planets/jupiter/europa/europa.asset index 9ee299ebf6..d5e455bb9f 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/europa/europa.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/europa/europa.asset @@ -3,7 +3,7 @@ local assetHelper = asset.require('util/asset_helper') asset.require("spice/base") asset.request('./trail') local kernel = asset.require('../kernels').jup310 -local labelsPath = asset.require('../jupiter_labels').LabelsPath +local labelsPath = asset.require('../jupiter_globelabels').LabelsPath local map_service_configs = asset.localResource("map_service_configs") diff --git a/data/assets/scene/solarsystem/planets/jupiter/ganymede/ganymede.asset b/data/assets/scene/solarsystem/planets/jupiter/ganymede/ganymede.asset index 510484cebf..513136ef98 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/ganymede/ganymede.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/ganymede/ganymede.asset @@ -3,7 +3,7 @@ local assetHelper = asset.require('util/asset_helper') asset.require("spice/base") asset.request('./trail') local kernel = asset.require('../kernels').jup310 -local labelsPath = asset.require('../jupiter_labels').LabelsPath +local labelsPath = asset.require('../jupiter_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/jupiter/io/io.asset b/data/assets/scene/solarsystem/planets/jupiter/io/io.asset index ca10670c06..fb10f0b3a8 100644 --- a/data/assets/scene/solarsystem/planets/jupiter/io/io.asset +++ b/data/assets/scene/solarsystem/planets/jupiter/io/io.asset @@ -3,7 +3,7 @@ local assetHelper = asset.require('util/asset_helper') asset.require("spice/base") asset.request('./trail') local kernel = asset.require('../kernels').jup310 -local labelsPath = asset.require('../jupiter_labels').LabelsPath +local labelsPath = asset.require('../jupiter_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/jupiter/jupiter_labels.asset b/data/assets/scene/solarsystem/planets/jupiter/jupiter_globelabels.asset similarity index 100% rename from data/assets/scene/solarsystem/planets/jupiter/jupiter_labels.asset rename to data/assets/scene/solarsystem/planets/jupiter/jupiter_globelabels.asset diff --git a/data/assets/scene/solarsystem/planets/mars/mars.asset b/data/assets/scene/solarsystem/planets/mars/mars.asset index 4c2e8dcd76..ee4da17e7d 100644 --- a/data/assets/scene/solarsystem/planets/mars/mars.asset +++ b/data/assets/scene/solarsystem/planets/mars/mars.asset @@ -2,7 +2,7 @@ local transforms = asset.require('./transforms') local assetHelper = asset.require('util/asset_helper') asset.require("spice/base") asset.request('./trail') -local labelsPath = asset.require('./mars_labels').LabelsPath +local labelsPath = asset.require('./mars_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/mars/mars_labels.asset b/data/assets/scene/solarsystem/planets/mars/mars_globelabels.asset similarity index 100% rename from data/assets/scene/solarsystem/planets/mars/mars_labels.asset rename to data/assets/scene/solarsystem/planets/mars/mars_globelabels.asset diff --git a/data/assets/scene/solarsystem/planets/mercury/mercury.asset b/data/assets/scene/solarsystem/planets/mercury/mercury.asset index 93924f8444..8eda6c5eb9 100644 --- a/data/assets/scene/solarsystem/planets/mercury/mercury.asset +++ b/data/assets/scene/solarsystem/planets/mercury/mercury.asset @@ -1,6 +1,6 @@ local assetHelper = asset.require('util/asset_helper') local transforms = asset.require('./transforms') -local labelsPath = asset.require('./mercury_labels').LabelsPath +local labelsPath = asset.require('./mercury_globelabels').LabelsPath asset.require("spice/base") diff --git a/data/assets/scene/solarsystem/planets/mercury/mercury_labels.asset b/data/assets/scene/solarsystem/planets/mercury/mercury_globelabels.asset similarity index 100% rename from data/assets/scene/solarsystem/planets/mercury/mercury_labels.asset rename to data/assets/scene/solarsystem/planets/mercury/mercury_globelabels.asset diff --git a/data/assets/scene/solarsystem/planets/saturn/dione/dione.asset b/data/assets/scene/solarsystem/planets/saturn/dione/dione.asset index 7cdd49b5cd..ded4b6ae73 100644 --- a/data/assets/scene/solarsystem/planets/saturn/dione/dione.asset +++ b/data/assets/scene/solarsystem/planets/saturn/dione/dione.asset @@ -2,7 +2,7 @@ local transforms = asset.require('../transforms') local assetHelper = asset.require('util/asset_helper') local kernel = asset.require('../kernels').sat375 asset.request('./trail') -local labelsPath = asset.require('../saturn_labels').LabelsPath +local labelsPath = asset.require('../saturn_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/saturn/enceladus/enceladus.asset b/data/assets/scene/solarsystem/planets/saturn/enceladus/enceladus.asset index 5fa01501ba..8a66735198 100644 --- a/data/assets/scene/solarsystem/planets/saturn/enceladus/enceladus.asset +++ b/data/assets/scene/solarsystem/planets/saturn/enceladus/enceladus.asset @@ -2,7 +2,7 @@ local transforms = asset.require('../transforms') local assetHelper = asset.require('util/asset_helper') local kernel = asset.require('../kernels').sat375 asset.request('./trail') -local labelsPath = asset.require('../saturn_labels').LabelsPath +local labelsPath = asset.require('../saturn_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/saturn/iapetus/iapetus.asset b/data/assets/scene/solarsystem/planets/saturn/iapetus/iapetus.asset index bab9c45056..892cc2c13e 100644 --- a/data/assets/scene/solarsystem/planets/saturn/iapetus/iapetus.asset +++ b/data/assets/scene/solarsystem/planets/saturn/iapetus/iapetus.asset @@ -2,7 +2,7 @@ local transforms = asset.require('../transforms') local assetHelper = asset.require('util/asset_helper') local kernel = asset.require('../kernels').sat375 asset.request('./trail') -local labelsPath = asset.require('../saturn_labels').LabelsPath +local labelsPath = asset.require('../saturn_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/saturn/mimas/mimas.asset b/data/assets/scene/solarsystem/planets/saturn/mimas/mimas.asset index 4dbedaad48..53d9b7da21 100644 --- a/data/assets/scene/solarsystem/planets/saturn/mimas/mimas.asset +++ b/data/assets/scene/solarsystem/planets/saturn/mimas/mimas.asset @@ -2,7 +2,7 @@ local transforms = asset.require('../transforms') local assetHelper = asset.require('util/asset_helper') local kernel = asset.require('../kernels').sat375 asset.request('./trail') -local labelsPath = asset.require('../saturn_labels').LabelsPath +local labelsPath = asset.require('../saturn_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/saturn/rhea/rhea.asset b/data/assets/scene/solarsystem/planets/saturn/rhea/rhea.asset index 0ab5688544..008663ecf5 100644 --- a/data/assets/scene/solarsystem/planets/saturn/rhea/rhea.asset +++ b/data/assets/scene/solarsystem/planets/saturn/rhea/rhea.asset @@ -2,7 +2,7 @@ local transforms = asset.require('../transforms') local assetHelper = asset.require('util/asset_helper') local kernel = asset.require('../kernels').sat375 asset.request('./trail') -local labelsPath = asset.require('../saturn_labels').LabelsPath +local labelsPath = asset.require('../saturn_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/saturn/saturn_labels.asset b/data/assets/scene/solarsystem/planets/saturn/saturn_globelabels.asset similarity index 100% rename from data/assets/scene/solarsystem/planets/saturn/saturn_labels.asset rename to data/assets/scene/solarsystem/planets/saturn/saturn_globelabels.asset diff --git a/data/assets/scene/solarsystem/planets/saturn/tethys/tethys.asset b/data/assets/scene/solarsystem/planets/saturn/tethys/tethys.asset index 1979cf4d66..fea8618180 100644 --- a/data/assets/scene/solarsystem/planets/saturn/tethys/tethys.asset +++ b/data/assets/scene/solarsystem/planets/saturn/tethys/tethys.asset @@ -2,7 +2,7 @@ local transforms = asset.require('../transforms') local assetHelper = asset.require('util/asset_helper') local kernel = asset.require('../kernels').sat375 asset.request('./trail') -local labelsPath = asset.require('../saturn_labels').LabelsPath +local labelsPath = asset.require('../saturn_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/saturn/titan/titan.asset b/data/assets/scene/solarsystem/planets/saturn/titan/titan.asset index 0145308ed4..a086c9eecb 100644 --- a/data/assets/scene/solarsystem/planets/saturn/titan/titan.asset +++ b/data/assets/scene/solarsystem/planets/saturn/titan/titan.asset @@ -2,7 +2,7 @@ local transforms = asset.require('../transforms') local assetHelper = asset.require('util/asset_helper') local kernel = asset.require('../kernels').sat375 asset.request('./trail') -local labelsPath = asset.require('../saturn_labels').LabelsPath +local labelsPath = asset.require('../saturn_globelabels').LabelsPath local map_service_configs = asset.localResource("map_service_configs") diff --git a/data/assets/scene/solarsystem/planets/venus/venus.asset b/data/assets/scene/solarsystem/planets/venus/venus.asset index f3e1f83fed..e53b0e7ede 100644 --- a/data/assets/scene/solarsystem/planets/venus/venus.asset +++ b/data/assets/scene/solarsystem/planets/venus/venus.asset @@ -2,7 +2,7 @@ local assetHelper = asset.require('util/asset_helper') local transforms = asset.require('./transforms') asset.require("spice/base") asset.request('./trail') -local labelsPath = asset.require('./venus_labels').LabelsPath +local labelsPath = asset.require('./venus_globelabels').LabelsPath diff --git a/data/assets/scene/solarsystem/planets/venus/venus_labels.asset b/data/assets/scene/solarsystem/planets/venus/venus_globelabels.asset similarity index 100% rename from data/assets/scene/solarsystem/planets/venus/venus_labels.asset rename to data/assets/scene/solarsystem/planets/venus/venus_globelabels.asset From f90fe90aae2e6d52f98a76134bb2b2d7427bc9f7 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Mon, 16 Dec 2019 11:34:41 +0100 Subject: [PATCH 32/42] Also include Pluto in the change of labels to globelabels --- .../assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset | 5 +++-- .../pluto/{pluto_labels.asset => pluto_globelabels.asset} | 0 2 files changed, 3 insertions(+), 2 deletions(-) rename data/assets/scene/solarsystem/dwarf_planets/pluto/{pluto_labels.asset => pluto_globelabels.asset} (100%) diff --git a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset index db18a54cc1..ce98ef30f8 100644 --- a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset +++ b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto.asset @@ -2,7 +2,7 @@ local assetHelper = asset.require('util/asset_helper') local transforms = asset.require('./transforms') asset.require("spice/base") asset.request('./trail') -local labelsPath = asset.require('./pluto_labels').LabelsPath +local labelsPath = asset.require('./pluto_globelabels').LabelsPath @@ -63,7 +63,7 @@ local PlutoLabel = { Identifier = "PlutoLabel", Parent = Pluto.Identifier, Renderable = { - Enabled = true, + Enabled = false, Type = "RenderableLabels", LabelText = "Pluto", FontSize = 100.0, @@ -73,6 +73,7 @@ local PlutoLabel = { BlendMode = "Additive", LabelOrientationOption = "Camera View Direction" }, + Tag = { "solarsystem_labels" }, GUI = { Name = "Pluto Label", Path = "/Solar System/Dwarf Planets/Pluto" diff --git a/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto_labels.asset b/data/assets/scene/solarsystem/dwarf_planets/pluto/pluto_globelabels.asset similarity index 100% rename from data/assets/scene/solarsystem/dwarf_planets/pluto/pluto_labels.asset rename to data/assets/scene/solarsystem/dwarf_planets/pluto/pluto_globelabels.asset From 04bd649bfe14820082ee8702745aa1d8bab4ab96 Mon Sep 17 00:00:00 2001 From: liuloppan Date: Mon, 16 Dec 2019 13:50:44 +0100 Subject: [PATCH 33/42] Update to use pluto_globelabels Update to use the renamed filename --- data/assets/scene/solarsystem/dwarf_planets/pluto/charon.asset | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data/assets/scene/solarsystem/dwarf_planets/pluto/charon.asset b/data/assets/scene/solarsystem/dwarf_planets/pluto/charon.asset index c9c58a820f..87139c2b9e 100644 --- a/data/assets/scene/solarsystem/dwarf_planets/pluto/charon.asset +++ b/data/assets/scene/solarsystem/dwarf_planets/pluto/charon.asset @@ -2,7 +2,7 @@ local assetHelper = asset.require('util/asset_helper') local transforms = asset.require('./transforms') asset.require("spice/base") asset.request('./trail') -local labelsPath = asset.require('./pluto_labels').LabelsPath +local labelsPath = asset.require('./pluto_globelabels').LabelsPath From 3051d71fea98591bf26eeae27b4564402da7e112 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Tue, 17 Dec 2019 11:05:14 +0100 Subject: [PATCH 34/42] Small code cleanup --- .../digitaluniverse/shaders/billboard_fs.glsl | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/modules/digitaluniverse/shaders/billboard_fs.glsl b/modules/digitaluniverse/shaders/billboard_fs.glsl index 0db1fa3fe4..90fe9d0696 100644 --- a/modules/digitaluniverse/shaders/billboard_fs.glsl +++ b/modules/digitaluniverse/shaders/billboard_fs.glsl @@ -35,12 +35,11 @@ uniform sampler2D spriteTexture; uniform bool hasColorMap; uniform float fadeInValue; -Fragment getFragment() { - +Fragment getFragment() { vec4 textureColor = texture(spriteTexture, texCoord); - if (textureColor.a == 0.f || gs_colorMap.a == 0.f || - ta == 0.f || fadeInValue == 0.f) { + if (textureColor.a == 0.f || gs_colorMap.a == 0.f || ta == 0.f || fadeInValue == 0.f) + { discard; } @@ -48,10 +47,11 @@ Fragment getFragment() { if (hasColorMap) { fullColor = vec4( - gs_colorMap.rgb * textureColor.rgb, + gs_colorMap.rgb * textureColor.rgb, gs_colorMap.a * textureColor.a * alphaValue - ); - } else { + ); + } + else { fullColor = vec4(color.rgb * textureColor.rgb, textureColor.a * alphaValue); } @@ -63,14 +63,13 @@ Fragment getFragment() { } Fragment frag; - frag.color = fullColor; - frag.depth = vs_screenSpaceDepth; + frag.color = fullColor; + frag.depth = vs_screenSpaceDepth; // Setting the position of the billboards to not interact // with the ATM. - frag.gPosition = vec4(-1e32, -1e32, -1e32, 1.0); - frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); + frag.gPosition = vec4(-1e32, -1e32, -1e32, 1.0); + frag.gNormal = vec4(0.0, 0.0, 0.0, 1.0); //frag.disableLDR2HDR = true; - return frag; -} \ No newline at end of file +} From 2d0eb703a49772a7e7e7a79c90e7887dc4b36a51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eric=20S=C3=B6derman?= Date: Fri, 20 Dec 2019 08:07:28 +0100 Subject: [PATCH 35/42] fix case sensitive include file for linux compile --- modules/base/rendering/renderablelabels.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/base/rendering/renderablelabels.cpp b/modules/base/rendering/renderablelabels.cpp index 5c8bbd20ae..d070d0f974 100644 --- a/modules/base/rendering/renderablelabels.cpp +++ b/modules/base/rendering/renderablelabels.cpp @@ -22,7 +22,7 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include #include #include From 02bf704c0217a93c1f8b5bc6a1360b09859e6d03 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Thu, 26 Dec 2019 19:01:01 +0100 Subject: [PATCH 36/42] Update Kameleon repository --- modules/kameleon/ext/kameleon | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/kameleon/ext/kameleon b/modules/kameleon/ext/kameleon index 1b4549edc7..338d482c86 160000 --- a/modules/kameleon/ext/kameleon +++ b/modules/kameleon/ext/kameleon @@ -1 +1 @@ -Subproject commit 1b4549edc74ef371730ef9d39c1ffa0efe90a985 +Subproject commit 338d482c8617bfacda0a5af8f3f6bb23163d436f From c8106da25b5b9d79afb1f21d0910d177350e7076 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 27 Dec 2019 17:21:00 +0100 Subject: [PATCH 37/42] First version of galaxy caching --- modules/galaxy/rendering/renderablegalaxy.cpp | 216 ++++++++++++++---- modules/galaxy/rendering/renderablegalaxy.h | 14 +- 2 files changed, 179 insertions(+), 51 deletions(-) diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 71edb8d372..17f95d1a48 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -34,7 +34,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -46,6 +48,8 @@ #include namespace { + constexpr int8_t CurrentCacheVersion = 1; + constexpr const char* GlslRaycastPath = "${MODULES}/galaxy/shaders/galaxyraycast.glsl"; constexpr const char* GlslBoundsVsPath = @@ -118,14 +122,16 @@ namespace { "" // @TODO Missing documentation }; - constexpr openspace::properties::Property::PropertyInfo DownscaleVolumeRenderingInfo = { + constexpr openspace::properties::Property::PropertyInfo DownscaleVolumeRenderingInfo = + { "Downscale", "Downscale Factor Volume Rendering", "This value set the downscaling factor" " when rendering the current volume." }; - constexpr openspace::properties::Property::PropertyInfo NumberOfRayCastingStepsInfo = { + constexpr openspace::properties::Property::PropertyInfo NumberOfRayCastingStepsInfo = + { "Steps", "Number of RayCasting Steps", "This value set the number of integration steps during the raycasting procedure." @@ -134,7 +140,7 @@ namespace { namespace openspace { - RenderableGalaxy::RenderableGalaxy(const ghoul::Dictionary& dictionary) +RenderableGalaxy::RenderableGalaxy(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _volumeRenderingEnabled(VolumeRenderingEnabledInfo, true) , _starRenderingEnabled(StarRenderingEnabledInfo, true) @@ -164,7 +170,7 @@ namespace openspace { if (dictionary.hasKeyAndValue(VolumeRenderingEnabledInfo.identifier)) { _volumeRenderingEnabled = dictionary.value( VolumeRenderingEnabledInfo.identifier - ); + ); } if (dictionary.hasKeyAndValue(StarRenderingEnabledInfo.identifier)) { @@ -248,9 +254,7 @@ namespace openspace { LINFO("Number of raycasting steps not specified. Using default value."); } - _downScaleVolumeRendering.setVisibility( - openspace::properties::Property::Visibility::Developer - ); + _downScaleVolumeRendering.setVisibility(properties::Property::Visibility::Developer); if (volumeDictionary.hasKey(DownscaleVolumeRenderingInfo.identifier)) { _downScaleVolumeRendering = volumeDictionary.value(DownscaleVolumeRenderingInfo.identifier); @@ -272,7 +276,7 @@ namespace openspace { if (pointsDictionary.hasKeyAndValue(EnabledPointsRatioInfo.identifier)) { _enabledPointsRatio = static_cast( pointsDictionary.value(EnabledPointsRatioInfo.identifier) - ); + ); } std::string pointSpreadFunctionTexturePath; @@ -292,6 +296,7 @@ void RenderableGalaxy::initializeGL() { _aspect = static_cast(_volumeDimensions); _aspect /= std::max(std::max(_aspect.x, _aspect.y), _aspect.z); + // The volume volume::RawVolumeReader> reader( _volumeFilename, _volumeDimensions @@ -304,10 +309,11 @@ void RenderableGalaxy::initializeGL() { GL_RGBA, GL_UNSIGNED_BYTE, ghoul::opengl::Texture::FilterMode::Linear, - ghoul::opengl::Texture::WrappingMode::ClampToEdge); + ghoul::opengl::Texture::WrappingMode::ClampToEdge + ); - _texture->setPixelData(reinterpret_cast( - _volume->data()), + _texture->setPixelData( + reinterpret_cast(_volume->data()), ghoul::opengl::Texture::TakeOwnership::No ); @@ -374,7 +380,7 @@ void RenderableGalaxy::initializeGL() { _pointSpreadFunctionFile = std::make_unique( _pointSpreadFunctionTexturePath - ); + ); } ghoul::opengl::updateUniformLocations( @@ -395,48 +401,40 @@ void RenderableGalaxy::initializeGL() { GLint positionAttrib = _pointsProgram->attributeLocation("in_position"); GLint colorAttrib = _pointsProgram->attributeLocation("in_color"); - std::ifstream pointFile(_pointsFilename, std::ios::in); std::vector pointPositions; std::vector pointColors; - int64_t nPoints; - // Read header for OFF (Object File Format) - std::string line; - std::getline(pointFile, line); + std::string cachedPointsFile = FileSys.cacheManager()->cachedFilename( + _pointsFilename, + ghoul::filesystem::CacheManager::Persistent::Yes + ); + const bool hasCachedFile = FileSys.fileExists(cachedPointsFile); + if (hasCachedFile) { + LINFO(fmt::format("Cached file '{}' used for galaxy point file '{}'", + cachedPointsFile, _pointsFilename + )); - // Read point count - std::getline(pointFile, line); - std::istringstream iss(line); - iss >> nPoints; - - // Prepare point reading - _nPoints = static_cast(nPoints); - float maxdist = 0; - - // Read points - float x, y, z, r, g, b, a; - for (size_t i = 0; - i < static_cast(_nPoints * _enabledPointsRatio.maxValue()) + 1; - ++i) - { - std::getline(pointFile, line); - std::istringstream issp(line); - issp >> x >> y >> z >> r >> g >> b >> a; - - //Convert klioparsec to meters - glm::vec3 position = glm::vec3(x, y, z); - position *= (openspace::distanceconstants::Parsec * 100); - - maxdist = std::max(maxdist, glm::length(position)); - - pointPositions.emplace_back(position); - pointColors.emplace_back(r, g, b); + Result res = loadCachedFile(cachedPointsFile); + if (res.success) { + pointPositions = std::move(res.positions); + pointColors = std::move(res.color); + } + else { + FileSys.cacheManager()->removeCacheFile(_pointsFilename); + Result res = loadPointFile(_pointsFilename); + pointPositions = std::move(res.positions); + pointColors = std::move(res.color); + saveCachedFile(cachedPointsFile, pointPositions, pointColors); + } + } + else { + Result res = loadPointFile(_pointsFilename); + ghoul_assert(res.success, "Point file loading failed"); + pointPositions = std::move(res.positions); + pointColors = std::move(res.color); + saveCachedFile(cachedPointsFile, pointPositions, pointColors); } - - pointFile.close(); - - std::cout << maxdist << std::endl; glGenVertexArrays(1, &_pointsVao); glGenBuffers(1, &_positionVbo); @@ -736,4 +734,126 @@ float RenderableGalaxy::safeLength(const glm::vec3& vector) const { return glm::length(vector / maxComponent) * maxComponent; } +RenderableGalaxy::Result RenderableGalaxy::loadPointFile(const std::string& file) { + std::vector pointPositions; + std::vector pointColors; + int64_t nPoints; + + std::ifstream pointFile(_pointsFilename, std::ios::in); + + // Read header for OFF (Object File Format) + std::string line; + std::getline(pointFile, line); + + // Read point count + std::getline(pointFile, line); + std::istringstream iss(line); + iss >> nPoints; + + // Prepare point reading + _nPoints = static_cast(nPoints); + + // Read points + float x, y, z, r, g, b, a; + for (size_t i = 0; + i < static_cast(_nPoints * _enabledPointsRatio.maxValue()) + 1; + ++i) + { + std::getline(pointFile, line); + std::istringstream issp(line); + issp >> x >> y >> z >> r >> g >> b >> a; + + // Convert kiloparsec to meters + glm::vec3 position = glm::vec3(x, y, z); + position *= (distanceconstants::Parsec * 100); + + pointPositions.emplace_back(position); + pointColors.emplace_back(r, g, b); + } + + Result res; + res.success = true; + res.positions = std::move(pointPositions); + res.color = std::move(pointColors); + return res; +} + +RenderableGalaxy::Result RenderableGalaxy::loadCachedFile(const std::string& file) { + std::ifstream fileStream(file, std::ifstream::binary); + if (!fileStream.good()) { + LERROR(fmt::format("Error opening file '{}' for loading cache file", file)); + return { false, {}, {} }; + } + + int8_t cacheVersion; + fileStream.read(reinterpret_cast(&cacheVersion), sizeof(int8_t)); + if (cacheVersion != CurrentCacheVersion) { + LINFO(fmt::format("Removing cache file '{}' as the version changed")); + return { false, {}, {} }; + } + + int64_t nPoints; + fileStream.read(reinterpret_cast(&nPoints), sizeof(int64_t)); + _nPoints = static_cast(nPoints); + + float enabledPointsRatio; + fileStream.read(reinterpret_cast(&enabledPointsRatio), sizeof(float)); + _enabledPointsRatio = enabledPointsRatio; + + uint64_t nPositions; + fileStream.read(reinterpret_cast(&nPositions), sizeof(uint64_t)); + std::vector positions; + positions.resize(nPositions); + fileStream.read( + reinterpret_cast(positions.data()), + nPositions * sizeof(glm::vec3) + ); + + uint64_t nColors; + fileStream.read(reinterpret_cast(&nColors), sizeof(uint64_t)); + std::vector colors; + colors.resize(nColors); + fileStream.read( + reinterpret_cast(colors.data()), + nColors * sizeof(glm::vec3) + ); + + Result result; + result.success = true; + result.positions = std::move(positions); + result.color = std::move(colors); + return result; +} + +void RenderableGalaxy::saveCachedFile(const std::string& file, + const std::vector& positions, + const std::vector& colors) +{ + int64_t nPoints = static_cast(_nPoints); + float pointsRatio = _enabledPointsRatio; + + std::ofstream fileStream(file, std::ofstream::binary); + + if (!fileStream.good()) { + LERROR(fmt::format("Error opening file '{}' for save cache file", file)); + return; + } + + fileStream.write(reinterpret_cast(&CurrentCacheVersion), sizeof(int8_t)); + fileStream.write(reinterpret_cast(&nPoints), sizeof(int64_t)); + fileStream.write(reinterpret_cast(&pointsRatio), sizeof(float)); + uint64_t nPositions = static_cast(positions.size()); + fileStream.write(reinterpret_cast(&nPositions), sizeof(uint64_t)); + fileStream.write( + reinterpret_cast(positions.data()), + positions.size() * sizeof(glm::vec3) + ); + uint64_t nColors = static_cast(colors.size()); + fileStream.write(reinterpret_cast(&nColors), sizeof(uint64_t)); + fileStream.write( + reinterpret_cast(colors.data()), + colors.size() * sizeof(glm::vec3) + ); +} + } // namespace openspace diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index d074bd848b..0ed16f2225 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -33,9 +33,7 @@ #include #include -namespace ghoul::opengl { - class ProgramObject; -} // namespace ghoul::opengl +namespace ghoul::opengl { class ProgramObject; } namespace openspace { @@ -60,6 +58,16 @@ private: void renderBillboards(const RenderData& data); float safeLength(const glm::vec3& vector) const; + struct Result { + bool success; + std::vector positions; + std::vector color; + }; + Result loadPointFile(const std::string& file); + Result loadCachedFile(const std::string& file); + void saveCachedFile(const std::string& file, const std::vector& positions, + const std::vector& colors); + glm::vec3 _volumeSize; glm::vec3 _pointScaling; properties::BoolProperty _volumeRenderingEnabled; From 5f200d439450658381975b606c8c980c93c00a5b Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 27 Dec 2019 19:51:33 +0100 Subject: [PATCH 38/42] Some cleanup --- modules/galaxy/rendering/renderablegalaxy.cpp | 689 +++++++++--------- modules/galaxy/rendering/renderablegalaxy.h | 2 - 2 files changed, 357 insertions(+), 334 deletions(-) diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 17f95d1a48..ecdd0c276f 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -51,17 +51,18 @@ namespace { constexpr int8_t CurrentCacheVersion = 1; constexpr const char* GlslRaycastPath = - "${MODULES}/galaxy/shaders/galaxyraycast.glsl"; + "${MODULE_GALAXY}/shaders/galaxyraycast.glsl"; constexpr const char* GlslBoundsVsPath = - "${MODULES}/galaxy/shaders/raycasterbounds_vs.glsl"; + "${MODULE_GALAXY}/shaders/raycasterbounds_vs.glsl"; constexpr const char* GlslBoundsFsPath = - "${MODULES}/galaxy/shaders/raycasterbounds_fs.glsl"; - constexpr const char* _loggerCat = "Renderable Galaxy"; + "${MODULE_GALAXY}/shaders/raycasterbounds_fs.glsl"; + constexpr const char* _loggerCat = "Renderable Galaxy"; constexpr const std::array UniformNamesPoints = { "modelMatrix", "cameraViewProjectionMatrix", "eyePosition", "opacityCoefficient" }; + constexpr const std::array UniformNamesBillboards = { "modelMatrix", "cameraViewProjectionMatrix", "cameraUp", "eyePosition", "psfTexture" @@ -136,6 +137,35 @@ namespace { "Number of RayCasting Steps", "This value set the number of integration steps during the raycasting procedure." }; + + void saveCachedFile(const std::string& file, const std::vector& positions, + const std::vector& colors, int64_t nPoints, + float pointsRatio) + { + std::ofstream fileStream(file, std::ofstream::binary); + + if (!fileStream.good()) { + LERROR(fmt::format("Error opening file '{}' for save cache file", file)); + return; + } + + fileStream.write(reinterpret_cast(&CurrentCacheVersion), sizeof(int8_t)); + fileStream.write(reinterpret_cast(&nPoints), sizeof(int64_t)); + fileStream.write(reinterpret_cast(&pointsRatio), sizeof(float)); + uint64_t nPositions = static_cast(positions.size()); + fileStream.write(reinterpret_cast(&nPositions), sizeof(uint64_t)); + fileStream.write( + reinterpret_cast(positions.data()), + positions.size() * sizeof(glm::vec3) + ); + uint64_t nColors = static_cast(colors.size()); + fileStream.write(reinterpret_cast(&nColors), sizeof(uint64_t)); + fileStream.write( + reinterpret_cast(colors.data()), + colors.size() * sizeof(glm::vec3) + ); + } + } // namespace namespace openspace { @@ -246,8 +276,8 @@ RenderableGalaxy::RenderableGalaxy(const ghoul::Dictionary& dictionary) } if (volumeDictionary.hasKey(NumberOfRayCastingStepsInfo.identifier)) { - _numberOfRayCastingSteps = static_cast( - volumeDictionary.value(NumberOfRayCastingStepsInfo.identifier) + _numberOfRayCastingSteps = static_cast( + volumeDictionary.value(NumberOfRayCastingStepsInfo.identifier) ); } else { @@ -349,123 +379,137 @@ void RenderableGalaxy::initializeGL() { addProperty(_numberOfRayCastingSteps); // initialize points. - if (!_pointsFilename.empty()) { - _pointsProgram = global::renderEngine.buildRenderProgram( - "Galaxy points", - absPath("${MODULE_GALAXY}/shaders/points_vs.glsl"), - absPath("${MODULE_GALAXY}/shaders/points_fs.glsl") - ); - _billboardsProgram = global::renderEngine.buildRenderProgram( - "Galaxy billboard", - absPath("${MODULE_GALAXY}/shaders/billboard_vs.glsl"), - absPath("${MODULE_GALAXY}/shaders/billboard_fs.glsl"), - absPath("${MODULE_GALAXY}/shaders/billboard_ge.glsl") + if (_pointsFilename.empty()) { + return; + } + + _pointsProgram = global::renderEngine.buildRenderProgram( + "Galaxy points", + absPath("${MODULE_GALAXY}/shaders/points_vs.glsl"), + absPath("${MODULE_GALAXY}/shaders/points_fs.glsl") + ); + _billboardsProgram = global::renderEngine.buildRenderProgram( + "Galaxy billboard", + absPath("${MODULE_GALAXY}/shaders/billboard_vs.glsl"), + absPath("${MODULE_GALAXY}/shaders/billboard_fs.glsl"), + absPath("${MODULE_GALAXY}/shaders/billboard_ge.glsl") + ); + + if (!_pointSpreadFunctionTexturePath.empty()) { + _pointSpreadFunctionTexture = ghoul::io::TextureReader::ref().loadTexture( + absPath(_pointSpreadFunctionTexturePath) ); - if (!_pointSpreadFunctionTexturePath.empty()) { - _pointSpreadFunctionTexture = ghoul::io::TextureReader::ref().loadTexture( + if (_pointSpreadFunctionTexture) { + LDEBUG(fmt::format( + "Loaded texture from '{}'", absPath(_pointSpreadFunctionTexturePath) - ); - - if (_pointSpreadFunctionTexture) { - LDEBUG(fmt::format( - "Loaded texture from '{}'", - absPath(_pointSpreadFunctionTexturePath) - )); - _pointSpreadFunctionTexture->uploadTexture(); - } - _pointSpreadFunctionTexture->setFilter( - ghoul::opengl::Texture::FilterMode::AnisotropicMipMap - ); - - _pointSpreadFunctionFile = std::make_unique( - _pointSpreadFunctionTexturePath - ); - } - - ghoul::opengl::updateUniformLocations( - *_pointsProgram, - _uniformCachePoints, - UniformNamesPoints - ); - ghoul::opengl::updateUniformLocations( - *_billboardsProgram, - _uniformCacheBillboards, - UniformNamesBillboards - ); - - _pointsProgram->setIgnoreUniformLocationError( - ghoul::opengl::ProgramObject::IgnoreError::Yes - ); - - GLint positionAttrib = _pointsProgram->attributeLocation("in_position"); - GLint colorAttrib = _pointsProgram->attributeLocation("in_color"); - - - std::vector pointPositions; - std::vector pointColors; - - std::string cachedPointsFile = FileSys.cacheManager()->cachedFilename( - _pointsFilename, - ghoul::filesystem::CacheManager::Persistent::Yes - ); - const bool hasCachedFile = FileSys.fileExists(cachedPointsFile); - if (hasCachedFile) { - LINFO(fmt::format("Cached file '{}' used for galaxy point file '{}'", - cachedPointsFile, _pointsFilename )); - - Result res = loadCachedFile(cachedPointsFile); - if (res.success) { - pointPositions = std::move(res.positions); - pointColors = std::move(res.color); - } - else { - FileSys.cacheManager()->removeCacheFile(_pointsFilename); - Result res = loadPointFile(_pointsFilename); - pointPositions = std::move(res.positions); - pointColors = std::move(res.color); - saveCachedFile(cachedPointsFile, pointPositions, pointColors); - } + _pointSpreadFunctionTexture->uploadTexture(); } - else { - Result res = loadPointFile(_pointsFilename); - ghoul_assert(res.success, "Point file loading failed"); + _pointSpreadFunctionTexture->setFilter( + ghoul::opengl::Texture::FilterMode::AnisotropicMipMap + ); + + _pointSpreadFunctionFile = std::make_unique( + _pointSpreadFunctionTexturePath + ); + } + + ghoul::opengl::updateUniformLocations( + *_pointsProgram, + _uniformCachePoints, + UniformNamesPoints + ); + ghoul::opengl::updateUniformLocations( + *_billboardsProgram, + _uniformCacheBillboards, + UniformNamesBillboards + ); + + _pointsProgram->setIgnoreUniformLocationError( + ghoul::opengl::ProgramObject::IgnoreError::Yes + ); + + GLint positionAttrib = _pointsProgram->attributeLocation("in_position"); + GLint colorAttrib = _pointsProgram->attributeLocation("in_color"); + + + std::vector pointPositions; + std::vector pointColors; + + std::string cachedPointsFile = FileSys.cacheManager()->cachedFilename( + _pointsFilename, + ghoul::filesystem::CacheManager::Persistent::Yes + ); + const bool hasCachedFile = FileSys.fileExists(cachedPointsFile); + if (hasCachedFile) { + LINFO(fmt::format("Cached file '{}' used for galaxy point file '{}'", + cachedPointsFile, _pointsFilename + )); + + Result res = loadCachedFile(cachedPointsFile); + if (res.success) { pointPositions = std::move(res.positions); pointColors = std::move(res.color); - saveCachedFile(cachedPointsFile, pointPositions, pointColors); } - - glGenVertexArrays(1, &_pointsVao); - glGenBuffers(1, &_positionVbo); - glGenBuffers(1, &_colorVbo); - - glBindVertexArray(_pointsVao); - glBindBuffer(GL_ARRAY_BUFFER, _positionVbo); - glBufferData(GL_ARRAY_BUFFER, - pointPositions.size() * sizeof(glm::vec3), - pointPositions.data(), - GL_STATIC_DRAW - ); - - glBindBuffer(GL_ARRAY_BUFFER, _colorVbo); - glBufferData(GL_ARRAY_BUFFER, - pointColors.size() * sizeof(glm::vec3), - pointColors.data(), - GL_STATIC_DRAW - ); - - glBindBuffer(GL_ARRAY_BUFFER, _positionVbo); - glEnableVertexAttribArray(positionAttrib); - glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr); - - glBindBuffer(GL_ARRAY_BUFFER, _colorVbo); - glEnableVertexAttribArray(colorAttrib); - glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr); - - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); + else { + FileSys.cacheManager()->removeCacheFile(_pointsFilename); + Result res = loadPointFile(_pointsFilename); + pointPositions = std::move(res.positions); + pointColors = std::move(res.color); + saveCachedFile( + cachedPointsFile, + pointPositions, + pointColors, + _nPoints, + _enabledPointsRatio + ); + } } + else { + Result res = loadPointFile(_pointsFilename); + ghoul_assert(res.success, "Point file loading failed"); + pointPositions = std::move(res.positions); + pointColors = std::move(res.color); + saveCachedFile( + cachedPointsFile, + pointPositions, + pointColors, + _nPoints, + _enabledPointsRatio + ); + } + + glGenVertexArrays(1, &_pointsVao); + glGenBuffers(1, &_positionVbo); + glGenBuffers(1, &_colorVbo); + + glBindVertexArray(_pointsVao); + glBindBuffer(GL_ARRAY_BUFFER, _positionVbo); + glBufferData(GL_ARRAY_BUFFER, + pointPositions.size() * sizeof(glm::vec3), + pointPositions.data(), + GL_STATIC_DRAW + ); + + glBindBuffer(GL_ARRAY_BUFFER, _colorVbo); + glBufferData(GL_ARRAY_BUFFER, + pointColors.size() * sizeof(glm::vec3), + pointColors.data(), + GL_STATIC_DRAW + ); + + glBindBuffer(GL_ARRAY_BUFFER, _positionVbo); + glEnableVertexAttribArray(positionAttrib); + glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr); + + glBindBuffer(GL_ARRAY_BUFFER, _colorVbo); + glEnableVertexAttribArray(colorAttrib); + glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); } void RenderableGalaxy::deinitializeGL() { @@ -473,6 +517,10 @@ void RenderableGalaxy::deinitializeGL() { global::raycasterManager.detachRaycaster(*_raycaster); _raycaster = nullptr; } + + glDeleteVertexArrays(1, &_pointsVao); + glDeleteBuffers(1, &_positionVbo); + glDeleteBuffers(1, &_colorVbo); } bool RenderableGalaxy::isReady() const { @@ -480,43 +528,44 @@ bool RenderableGalaxy::isReady() const { } void RenderableGalaxy::update(const UpdateData& data) { - if (_raycaster) { - //glm::mat4 transform = glm::translate(, static_cast(_translation)); - const glm::vec3 eulerRotation = static_cast(_rotation); - glm::mat4 transform = glm::rotate( - glm::mat4(1.0), - eulerRotation.x, - glm::vec3(1, 0, 0) - ); - transform = glm::rotate(transform, eulerRotation.y, glm::vec3(0, 1, 0)); - transform = glm::rotate(transform, eulerRotation.z, glm::vec3(0, 0, 1)); - - glm::mat4 volumeTransform = glm::scale(transform, _volumeSize); - _pointTransform = transform; - //_pointTransform = glm::scale(transform, _pointScaling); - - const glm::vec4 translation = glm::vec4(_translation.value()*_volumeSize, 0.0); - - // Todo: handle floating point overflow, to actually support translation. - - volumeTransform[3] += translation; - _pointTransform[3] += translation; - - _raycaster->setDownscaleRender(_downScaleVolumeRendering); - _raycaster->setMaxSteps(_numberOfRayCastingSteps); - _raycaster->setStepSize(_stepSize); - _raycaster->setAspect(_aspect); - _raycaster->setModelTransform(volumeTransform); - _raycaster->setAbsorptionMultiplier(_absorptionMultiply); - _raycaster->setEmissionMultiplier(_emissionMultiply); - _raycaster->setTime(data.time.j2000Seconds()); + if (!_raycaster) { + return; } + //glm::mat4 transform = glm::translate(, static_cast(_translation)); + const glm::vec3 eulerRotation = static_cast(_rotation); + glm::mat4 transform = glm::rotate( + glm::mat4(1.0), + eulerRotation.x, + glm::vec3(1, 0, 0) + ); + transform = glm::rotate(transform, eulerRotation.y, glm::vec3(0, 1, 0)); + transform = glm::rotate(transform, eulerRotation.z, glm::vec3(0, 0, 1)); + + glm::mat4 volumeTransform = glm::scale(transform, _volumeSize); + _pointTransform = transform; + //_pointTransform = glm::scale(transform, _pointScaling); + + const glm::vec4 translation = glm::vec4(_translation.value()*_volumeSize, 0.0); + + // Todo: handle floating point overflow, to actually support translation. + + volumeTransform[3] += translation; + _pointTransform[3] += translation; + + _raycaster->setDownscaleRender(_downScaleVolumeRendering); + _raycaster->setMaxSteps(_numberOfRayCastingSteps); + _raycaster->setStepSize(_stepSize); + _raycaster->setAspect(_aspect); + _raycaster->setModelTransform(volumeTransform); + _raycaster->setAbsorptionMultiplier(_absorptionMultiply); + _raycaster->setEmissionMultiplier(_emissionMultiply); + _raycaster->setTime(data.time.j2000Seconds()); } void RenderableGalaxy::render(const RenderData& data, RendererTasks& tasks) { // Render the volume if (_raycaster && _volumeRenderingEnabled) { - RaycasterTask task{ _raycaster.get(), data }; + RaycasterTask task { _raycaster.get(), data }; const glm::vec3 position = data.camera.positionVec3(); const float length = safeLength(position); @@ -533,15 +582,19 @@ void RenderableGalaxy::render(const RenderData& data, RendererTasks& tasks) { float opacityCoefficient = 1.f; if (length < lowerRampStart) { opacityCoefficient = 0.f; // camera really close - } else if (length < lowerRampEnd) { + } + else if (length < lowerRampEnd) { opacityCoefficient = (length - lowerRampStart) / (lowerRampEnd - lowerRampStart); - } else if (length < upperRampStart) { + } + else if (length < upperRampStart) { opacityCoefficient = 1.f; // sweet spot (max) - } else if (length < upperRampEnd) { + } + else if (length < upperRampEnd) { opacityCoefficient = 1.f - (length - upperRampStart) / (upperRampEnd - upperRampStart); //fade out - } else { + } + else { opacityCoefficient = 0; } @@ -568,163 +621,166 @@ void RenderableGalaxy::render(const RenderData& data, RendererTasks& tasks) { } void RenderableGalaxy::renderPoints(const RenderData& data) { - if (_pointsProgram) { - // Saving current OpenGL state - GLenum blendEquationRGB; - GLenum blendEquationAlpha; - GLenum blendDestAlpha; - GLenum blendDestRGB; - GLenum blendSrcAlpha; - GLenum blendSrcRGB; - GLboolean depthMask; - - glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); - glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); - glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); - glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); - glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); - glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); - - glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); - - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glDepthMask(false); - glDisable(GL_DEPTH_TEST); - - _pointsProgram->activate(); - - glm::dmat4 rotMatrix = glm::rotate( - glm::dmat4(1.0), - glm::pi(), - glm::dvec3(1.0, 0.0, 0.0)) * - glm::rotate(glm::dmat4(1.0), 3.1248, glm::dvec3(0.0, 1.0, 0.0)) * - glm::rotate(glm::dmat4(1.0), 4.45741, glm::dvec3(0.0, 0.0, 1.0) - ); - - glm::dmat4 modelMatrix = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * - glm::dmat4(data.modelTransform.rotation) * rotMatrix * - glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); - - glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); - - glm::dmat4 cameraViewProjectionMatrix = projectionMatrix * - data.camera.combinedViewMatrix(); - - _pointsProgram->setUniform(_uniformCachePoints.modelMatrix, modelMatrix); - _pointsProgram->setUniform( - _uniformCachePoints.cameraViewProjectionMatrix, - cameraViewProjectionMatrix - ); - - glm::dvec3 eyePosition = glm::dvec3( - glm::inverse(data.camera.combinedViewMatrix()) * - glm::dvec4(0.0, 0.0, 0.0, 1.0) - ); - _pointsProgram->setUniform(_uniformCachePoints.eyePosition, eyePosition); - _pointsProgram->setUniform( - _uniformCachePoints.opacityCoefficient, - _opacityCoefficient - ); - - glBindVertexArray(_pointsVao); - glDrawArrays(GL_POINTS, 0, static_cast(_nPoints * _enabledPointsRatio)); - - glBindVertexArray(0); - - _pointsProgram->deactivate(); - - glEnable(GL_DEPTH_TEST); - glDepthMask(true); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - // Restores OpenGL blending state - glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); - glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); - glDepthMask(depthMask); + if (!_pointsProgram) { + return; } + // Saving current OpenGL state + GLenum blendEquationRGB; + GLenum blendEquationAlpha; + GLenum blendDestAlpha; + GLenum blendDestRGB; + GLenum blendSrcAlpha; + GLenum blendSrcRGB; + GLboolean depthMask; + + glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); + glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); + glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); + glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); + glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); + + glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); + + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glDepthMask(false); + glDisable(GL_DEPTH_TEST); + + _pointsProgram->activate(); + + glm::dmat4 rotMatrix = glm::rotate( + glm::dmat4(1.0), + glm::pi(), + glm::dvec3(1.0, 0.0, 0.0)) * + glm::rotate(glm::dmat4(1.0), 3.1248, glm::dvec3(0.0, 1.0, 0.0)) * + glm::rotate(glm::dmat4(1.0), 4.45741, glm::dvec3(0.0, 0.0, 1.0) + ); + + glm::dmat4 modelMatrix = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + glm::dmat4(data.modelTransform.rotation) * rotMatrix * + glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); + + glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); + + glm::dmat4 cameraViewProjectionMatrix = projectionMatrix * + data.camera.combinedViewMatrix(); + + _pointsProgram->setUniform(_uniformCachePoints.modelMatrix, modelMatrix); + _pointsProgram->setUniform( + _uniformCachePoints.cameraViewProjectionMatrix, + cameraViewProjectionMatrix + ); + + glm::dvec3 eyePosition = glm::dvec3( + glm::inverse(data.camera.combinedViewMatrix()) * + glm::dvec4(0.0, 0.0, 0.0, 1.0) + ); + _pointsProgram->setUniform(_uniformCachePoints.eyePosition, eyePosition); + _pointsProgram->setUniform( + _uniformCachePoints.opacityCoefficient, + _opacityCoefficient + ); + + glBindVertexArray(_pointsVao); + glDrawArrays(GL_POINTS, 0, static_cast(_nPoints * _enabledPointsRatio)); + + glBindVertexArray(0); + + _pointsProgram->deactivate(); + + glEnable(GL_DEPTH_TEST); + glDepthMask(true); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Restores OpenGL blending state + glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); + glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); + glDepthMask(depthMask); } void RenderableGalaxy::renderBillboards(const RenderData& data) { - if (_billboardsProgram) { - // Saving current OpenGL state - GLenum blendEquationRGB; - GLenum blendEquationAlpha; - GLenum blendDestAlpha; - GLenum blendDestRGB; - GLenum blendSrcAlpha; - GLenum blendSrcRGB; - GLboolean depthMask; - - glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); - glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); - glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); - glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); - glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); - glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); - - glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); - - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glDepthMask(false); - glDisable(GL_DEPTH_TEST); - - _billboardsProgram->activate(); - - glm::dmat4 rotMatrix = glm::rotate( - glm::dmat4(1.0), - glm::pi(), - glm::dvec3(1.0, 0.0, 0.0)) * - glm::rotate(glm::dmat4(1.0), 3.1248, glm::dvec3(0.0, 1.0, 0.0)) * - glm::rotate(glm::dmat4(1.0), 4.45741, glm::dvec3(0.0, 0.0, 1.0) - ); - - glm::dmat4 modelMatrix = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * - glm::dmat4(data.modelTransform.rotation) * rotMatrix * - glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); - - glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); - - glm::dmat4 cameraViewProjectionMatrix = projectionMatrix * - data.camera.combinedViewMatrix(); - - _billboardsProgram->setUniform(_uniformCacheBillboards.modelMatrix, modelMatrix); - _billboardsProgram->setUniform( - _uniformCacheBillboards.cameraViewProjectionMatrix, - cameraViewProjectionMatrix - ); - - glm::dvec3 eyePosition = glm::dvec3( - glm::inverse(data.camera.combinedViewMatrix()) * - glm::dvec4(0.0, 0.0, 0.0, 1.0) - ); - _billboardsProgram->setUniform(_uniformCacheBillboards.eyePosition, eyePosition); - - glm::dvec3 cameraUp = data.camera.lookUpVectorWorldSpace(); - _billboardsProgram->setUniform(_uniformCacheBillboards.cameraUp, cameraUp); - - ghoul::opengl::TextureUnit psfUnit; - psfUnit.activate(); - _pointSpreadFunctionTexture->bind(); - _billboardsProgram->setUniform(_uniformCacheBillboards.psfTexture, psfUnit); - - glBindVertexArray(_pointsVao); - glDrawArrays(GL_POINTS, 0, static_cast(_nPoints * _enabledPointsRatio)); - - glBindVertexArray(0); - - _billboardsProgram->deactivate(); - - glEnable(GL_DEPTH_TEST); - glDepthMask(true); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - // Restores OpenGL blending state - glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); - glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); - glDepthMask(depthMask); + if (!_billboardsProgram) { + return; } + + // Saving current OpenGL state + GLenum blendEquationRGB; + GLenum blendEquationAlpha; + GLenum blendDestAlpha; + GLenum blendDestRGB; + GLenum blendSrcAlpha; + GLenum blendSrcRGB; + GLboolean depthMask; + + glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB); + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); + glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); + glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB); + glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); + glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB); + + glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); + + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glDepthMask(false); + glDisable(GL_DEPTH_TEST); + + _billboardsProgram->activate(); + + glm::dmat4 rotMatrix = glm::rotate( + glm::dmat4(1.0), + glm::pi(), + glm::dvec3(1.0, 0.0, 0.0)) * + glm::rotate(glm::dmat4(1.0), 3.1248, glm::dvec3(0.0, 1.0, 0.0)) * + glm::rotate(glm::dmat4(1.0), 4.45741, glm::dvec3(0.0, 0.0, 1.0) + ); + + glm::dmat4 modelMatrix = + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + glm::dmat4(data.modelTransform.rotation) * rotMatrix * + glm::dmat4(glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale))); + + glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); + + glm::dmat4 cameraViewProjectionMatrix = projectionMatrix * + data.camera.combinedViewMatrix(); + + _billboardsProgram->setUniform(_uniformCacheBillboards.modelMatrix, modelMatrix); + _billboardsProgram->setUniform( + _uniformCacheBillboards.cameraViewProjectionMatrix, + cameraViewProjectionMatrix + ); + + glm::dvec3 eyePosition = glm::dvec3( + glm::inverse(data.camera.combinedViewMatrix()) * + glm::dvec4(0.0, 0.0, 0.0, 1.0) + ); + _billboardsProgram->setUniform(_uniformCacheBillboards.eyePosition, eyePosition); + + glm::dvec3 cameraUp = data.camera.lookUpVectorWorldSpace(); + _billboardsProgram->setUniform(_uniformCacheBillboards.cameraUp, cameraUp); + + ghoul::opengl::TextureUnit psfUnit; + psfUnit.activate(); + _pointSpreadFunctionTexture->bind(); + _billboardsProgram->setUniform(_uniformCacheBillboards.psfTexture, psfUnit); + + glBindVertexArray(_pointsVao); + glDrawArrays(GL_POINTS, 0, static_cast(_nPoints * _enabledPointsRatio)); + + glBindVertexArray(0); + + _billboardsProgram->deactivate(); + + glEnable(GL_DEPTH_TEST); + glDepthMask(true); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Restores OpenGL blending state + glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); + glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); + glDepthMask(depthMask); } float RenderableGalaxy::safeLength(const glm::vec3& vector) const { @@ -825,35 +881,4 @@ RenderableGalaxy::Result RenderableGalaxy::loadCachedFile(const std::string& fil return result; } -void RenderableGalaxy::saveCachedFile(const std::string& file, - const std::vector& positions, - const std::vector& colors) -{ - int64_t nPoints = static_cast(_nPoints); - float pointsRatio = _enabledPointsRatio; - - std::ofstream fileStream(file, std::ofstream::binary); - - if (!fileStream.good()) { - LERROR(fmt::format("Error opening file '{}' for save cache file", file)); - return; - } - - fileStream.write(reinterpret_cast(&CurrentCacheVersion), sizeof(int8_t)); - fileStream.write(reinterpret_cast(&nPoints), sizeof(int64_t)); - fileStream.write(reinterpret_cast(&pointsRatio), sizeof(float)); - uint64_t nPositions = static_cast(positions.size()); - fileStream.write(reinterpret_cast(&nPositions), sizeof(uint64_t)); - fileStream.write( - reinterpret_cast(positions.data()), - positions.size() * sizeof(glm::vec3) - ); - uint64_t nColors = static_cast(colors.size()); - fileStream.write(reinterpret_cast(&nColors), sizeof(uint64_t)); - fileStream.write( - reinterpret_cast(colors.data()), - colors.size() * sizeof(glm::vec3) - ); -} - } // namespace openspace diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index 0ed16f2225..2f8c4ff570 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -65,8 +65,6 @@ private: }; Result loadPointFile(const std::string& file); Result loadCachedFile(const std::string& file); - void saveCachedFile(const std::string& file, const std::vector& positions, - const std::vector& colors); glm::vec3 _volumeSize; glm::vec3 _pointScaling; From ce7795a67b22a06b5022dc008dae9ee5ff67d9a6 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 27 Dec 2019 20:10:48 +0100 Subject: [PATCH 39/42] Do not assume that the GuiName or a DashboardItem is provided (closes #1006) Do not try to load an empty URL as it triggers an assert --- modules/cefwebgui/cefwebguimodule.cpp | 4 +++- src/rendering/dashboarditem.cpp | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/modules/cefwebgui/cefwebguimodule.cpp b/modules/cefwebgui/cefwebguimodule.cpp index 44c3ffa24b..e0a1de88e7 100644 --- a/modules/cefwebgui/cefwebguimodule.cpp +++ b/modules/cefwebgui/cefwebguimodule.cpp @@ -103,7 +103,9 @@ void CefWebGuiModule::startOrStopGui() { new GUIKeyboardHandler ); _instance->initialize(); - _instance->loadUrl(_url); + if (!_url.value().empty()) { + _instance->loadUrl(_url); + } } if (_visible) { webBrowserModule->attachEventHandler(_instance.get()); diff --git a/src/rendering/dashboarditem.cpp b/src/rendering/dashboarditem.cpp index d7ee5306cd..42fef0b961 100644 --- a/src/rendering/dashboarditem.cpp +++ b/src/rendering/dashboarditem.cpp @@ -111,8 +111,10 @@ DashboardItem::DashboardItem(const ghoul::Dictionary& dictionary) std::string identifier = dictionary.value(IdentifierInfo.identifier); setIdentifier(std::move(identifier)); - std::string guiName = dictionary.value(GuiNameInfo.identifier); - setGuiName(std::move(guiName)); + if (dictionary.hasKeyAndValue(GuiNameInfo.identifier)) { + std::string guiName = dictionary.value(GuiNameInfo.identifier); + setGuiName(std::move(guiName)); + } addProperty(_isEnabled); } From a51cee1f3622e0e2ad79d2f14000e017060d47d6 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 27 Dec 2019 21:25:22 +0100 Subject: [PATCH 40/42] Add a method for creating a unique name for screenspace renderable (closes #652) --- .../rendering/screenspacerenderable.h | 2 ++ .../base/rendering/screenspacedashboard.cpp | 23 ++++++------------- .../base/rendering/screenspaceimagelocal.cpp | 23 ++++++------------- .../base/rendering/screenspaceimageonline.cpp | 23 ++++++------------- modules/spout/renderableplanespout.cpp | 6 ++--- modules/spout/screenspacespout.cpp | 23 ++++++------------- modules/webbrowser/src/screenspacebrowser.cpp | 15 +++++++----- src/rendering/screenspacerenderable.cpp | 23 +++++++++++++++++-- 8 files changed, 63 insertions(+), 75 deletions(-) diff --git a/include/openspace/rendering/screenspacerenderable.h b/include/openspace/rendering/screenspacerenderable.h index d5dfabef94..abb4a498c9 100644 --- a/include/openspace/rendering/screenspacerenderable.h +++ b/include/openspace/rendering/screenspacerenderable.h @@ -75,6 +75,8 @@ public: protected: void createShaders(); + std::string makeUniqueIdentifier(std::string name); + glm::mat4 scaleMatrix(); glm::mat4 globalRotationMatrix(); glm::mat4 translationMatrix(); diff --git a/modules/base/rendering/screenspacedashboard.cpp b/modules/base/rendering/screenspacedashboard.cpp index d86376d06f..c0530f8491 100644 --- a/modules/base/rendering/screenspacedashboard.cpp +++ b/modules/base/rendering/screenspacedashboard.cpp @@ -151,24 +151,15 @@ ScreenSpaceDashboard::ScreenSpaceDashboard(const ghoul::Dictionary& dictionary) "ScreenSpaceDashboard" ); - int iIdentifier = 0; - if (_identifier.empty()) { - static int id = 0; - iIdentifier = id; - - if (iIdentifier == 0) { - setIdentifier("ScreenSpaceDashboard"); - } - else { - setIdentifier("ScreenSpaceDashboard" + std::to_string(iIdentifier)); - } - ++id; + std::string identifier; + if (dictionary.hasKeyAndValue(KeyIdentifier)) { + identifier = dictionary.value(KeyIdentifier); } - - if (_guiName.empty()) { - // Adding an extra space to the user-facing name as it looks nicer - setGuiName("ScreenSpaceDashboard " + std::to_string(iIdentifier)); + else { + identifier = "ScreenSpaceDashboard"; } + identifier = makeUniqueIdentifier(identifier); + setIdentifier(std::move(identifier)); if (dictionary.hasKey(UseMainInfo.identifier)) { _useMainDashboard = dictionary.value(UseMainInfo.identifier); diff --git a/modules/base/rendering/screenspaceimagelocal.cpp b/modules/base/rendering/screenspaceimagelocal.cpp index 392a8952d0..6e0896ab21 100644 --- a/modules/base/rendering/screenspaceimagelocal.cpp +++ b/modules/base/rendering/screenspaceimagelocal.cpp @@ -78,24 +78,15 @@ ScreenSpaceImageLocal::ScreenSpaceImageLocal(const ghoul::Dictionary& dictionary "ScreenSpaceImageLocal" ); - int iIdentifier = 0; - if (_identifier.empty()) { - static int id = 0; - iIdentifier = id; - - if (iIdentifier == 0) { - setIdentifier("ScreenSpaceImageLocal"); - } - else { - setIdentifier("ScreenSpaceImageLocal" + std::to_string(iIdentifier)); - } - ++id; + std::string identifier; + if (dictionary.hasKeyAndValue(KeyIdentifier)) { + identifier = dictionary.value(KeyIdentifier); } - - if (_guiName.empty()) { - // Adding an extra space to the user-facing name as it looks nicer - setGuiName("ScreenSpaceImageLocal " + std::to_string(iIdentifier)); + else { + identifier = "ScreenSpaceImageLocal"; } + identifier = makeUniqueIdentifier(identifier); + setIdentifier(identifier); _texturePath.onChange([this]() { if (!FileSys.fileExists(FileSys.absolutePath(_texturePath))) { diff --git a/modules/base/rendering/screenspaceimageonline.cpp b/modules/base/rendering/screenspaceimageonline.cpp index 83026445cc..b3df9654b4 100644 --- a/modules/base/rendering/screenspaceimageonline.cpp +++ b/modules/base/rendering/screenspaceimageonline.cpp @@ -80,24 +80,15 @@ ScreenSpaceImageOnline::ScreenSpaceImageOnline(const ghoul::Dictionary& dictiona "ScreenSpaceImageOnline" ); - int iIdentifier = 0; - if (_identifier.empty()) { - static int id = 0; - iIdentifier = id; - - if (iIdentifier == 0) { - setIdentifier("ScreenSpaceImageOnline"); - } - else { - setIdentifier("ScreenSpaceImageOnline" + std::to_string(iIdentifier)); - } - ++id; + std::string identifier; + if (dictionary.hasKeyAndValue(KeyIdentifier)) { + identifier = dictionary.value(KeyIdentifier); } - - if (_guiName.empty()) { - // Adding an extra space to the user-facing name as it looks nicer - setGuiName("ScreenSpaceImageOnline " + std::to_string(iIdentifier)); + else { + identifier = "ScreenSpaceImageOnline"; } + identifier = makeUniqueIdentifier(identifier); + setIdentifier(std::move(identifier)); _texturePath.onChange([this]() { _textureIsDirty = true; }); addProperty(_texturePath); diff --git a/modules/spout/renderableplanespout.cpp b/modules/spout/renderableplanespout.cpp index f3c2eb2dac..c398898adc 100644 --- a/modules/spout/renderableplanespout.cpp +++ b/modules/spout/renderableplanespout.cpp @@ -101,17 +101,17 @@ RenderablePlaneSpout::RenderablePlaneSpout(const ghoul::Dictionary& dictionary) iIdentifier = id; if (iIdentifier == 0) { - setIdentifier("ScreenSpaceSpout"); + setIdentifier("RenderablePlaneSpout"); } else { - setIdentifier("ScreenSpaceSpout" + std::to_string(iIdentifier)); + setIdentifier("RenderablePlaneSpout" + std::to_string(iIdentifier)); } ++id; } if (_guiName.empty()) { // Adding an extra space to the user-facing name as it looks nicer - setGuiName("ScreenSpaceSpout " + std::to_string(iIdentifier)); + setGuiName("RenderablePlaneSpout " + std::to_string(iIdentifier)); } if (dictionary.hasKey(NameInfo.identifier)) { diff --git a/modules/spout/screenspacespout.cpp b/modules/spout/screenspacespout.cpp index 5d8f23f430..b3204f0135 100644 --- a/modules/spout/screenspacespout.cpp +++ b/modules/spout/screenspacespout.cpp @@ -93,24 +93,15 @@ ScreenSpaceSpout::ScreenSpaceSpout(const ghoul::Dictionary& dictionary) "ScreenSpaceSpout" ); - int iIdentifier = 0; - if (_identifier.empty()) { - static int id = 0; - iIdentifier = id; - - if (iIdentifier == 0) { - setIdentifier("ScreenSpaceSpout"); - } - else { - setIdentifier("ScreenSpaceSpout" + std::to_string(iIdentifier)); - } - ++id; + std::string identifier; + if (dictionary.hasKeyAndValue(KeyIdentifier)) { + identifier = dictionary.value(KeyIdentifier); } - - if (_guiName.empty()) { - // Adding an extra space to the user-facing name as it looks nicer - setGuiName("ScreenSpaceSpout " + std::to_string(iIdentifier)); + else { + identifier = "ScreenSpaceSpout"; } + identifier = makeUniqueIdentifier(identifier); + setIdentifier(std::move(identifier)); if (dictionary.hasKey(NameInfo.identifier)) { _spoutName = dictionary.value(NameInfo.identifier); diff --git a/modules/webbrowser/src/screenspacebrowser.cpp b/modules/webbrowser/src/screenspacebrowser.cpp index 1c69bb0b4c..72621a96cc 100644 --- a/modules/webbrowser/src/screenspacebrowser.cpp +++ b/modules/webbrowser/src/screenspacebrowser.cpp @@ -72,13 +72,16 @@ ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary &dictionary) , _dimensions(DimensionsInfo, glm::vec2(0.f), glm::vec2(0.f), glm::vec2(3000.f)) , _reload(ReloadInfo) { - if (dictionary.hasKey(KeyIdentifier)) { - setIdentifier(dictionary.value(KeyIdentifier)); - } else { - static int id = 0; - setIdentifier("ScreenSpaceBrowser " + std::to_string(id)); - ++id; + + std::string identifier; + if (dictionary.hasKeyAndValue(KeyIdentifier)) { + identifier = dictionary.value(KeyIdentifier); } + else { + identifier = "ScreenSpaceBrowser"; + } + identifier = makeUniqueIdentifier(identifier); + setIdentifier(identifier); if (dictionary.hasKeyAndValue(UrlInfo.identifier)) { _url = dictionary.value(UrlInfo.identifier); diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index 9a3b01f0dc..6fe7813bc8 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -206,8 +206,6 @@ namespace { wrap(elevation, -glm::pi(), glm::pi()) ); } - - } // namespace namespace openspace { @@ -314,6 +312,27 @@ std::unique_ptr ScreenSpaceRenderable::createFromDictiona ); } +std::string ScreenSpaceRenderable::makeUniqueIdentifier(std::string name) { + std::vector r = global::renderEngine.screenSpaceRenderables(); + + auto nameTaken = [&r](const std::string& name) { + bool nameTaken = std::any_of( + r.begin(), + r.end(), + [&name](ScreenSpaceRenderable* r) { return r->identifier() == name; } + ); + return nameTaken; + }; + + std::string baseName = name; + int i = 1; + while (nameTaken(name)) { + name = baseName + std::to_string(i); + i++; + } + return name; +} + ScreenSpaceRenderable::ScreenSpaceRenderable(const ghoul::Dictionary& dictionary) : properties::PropertyOwner({ "" }) , _enabled(EnabledInfo, true) From 207db3c82486d526cae0291f98f06898dc65260b Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 27 Dec 2019 23:29:28 +0100 Subject: [PATCH 41/42] Remove PowerScaledCoordinates and rename PowerScaledSphere to Sphere (closes #4) --- include/openspace/properties/property.h | 4 +- include/openspace/util/camera.h | 2 - .../openspace/util/powerscaledcoordinate.h | 114 ------- .../util/{powerscaledsphere.h => sphere.h} | 18 +- include/openspace/util/updatestructures.h | 1 - .../rendering/atmospheredeferredcaster.cpp | 1 - modules/base/rendering/renderablesphere.cpp | 6 +- modules/base/rendering/renderablesphere.h | 4 +- modules/base/shaders/imageplane_vs.glsl | 4 +- modules/iswa/rendering/datasphere.cpp | 4 +- modules/iswa/rendering/datasphere.h | 4 +- modules/iswa/rendering/iswacygnet.cpp | 6 +- .../space/rendering/simplespheregeometry.cpp | 6 +- .../space/rendering/simplespheregeometry.h | 4 +- .../rendering/renderablemodelprojection.cpp | 6 +- .../rendering/renderableplaneprojection.cpp | 30 +- .../rendering/toyvolumeraycaster.cpp | 1 - .../volume/rendering/basicvolumeraycaster.cpp | 1 - src/CMakeLists.txt | 6 +- src/util/powerscaledcoordinate.cpp | 322 ------------------ .../{powerscaledsphere.cpp => sphere.cpp} | 17 +- tests/main.cpp | 1 - tests/test_powerscalecoordinates.inl | 63 ---- 23 files changed, 56 insertions(+), 569 deletions(-) delete mode 100644 include/openspace/util/powerscaledcoordinate.h rename include/openspace/util/{powerscaledsphere.h => sphere.h} (86%) delete mode 100644 src/util/powerscaledcoordinate.cpp rename src/util/{powerscaledsphere.cpp => sphere.cpp} (93%) delete mode 100644 tests/test_powerscalecoordinates.inl diff --git a/include/openspace/properties/property.h b/include/openspace/properties/property.h index 6d7bbc3d3f..1b2f9fdbec 100644 --- a/include/openspace/properties/property.h +++ b/include/openspace/properties/property.h @@ -395,9 +395,7 @@ public: /** * Default view options that can be used in the Property::setViewOption method. The * values are: Property::ViewOptions::Color = \c color, - * Property::ViewOptions::LightPosition = \c lightPosition, - * Property::ViewOptions::PowerScaledScalar = \c powerScaledScalar, and - * Property::ViewOptions::PowerScaledCoordinate = \c powerScaledCoordinate. + * Property::ViewOptions::LightPosition = \c lightPosition */ struct ViewOptions { static const char* Color; diff --git a/include/openspace/util/camera.h b/include/openspace/util/camera.h index 8131d04191..8335329b31 100644 --- a/include/openspace/util/camera.h +++ b/include/openspace/util/camera.h @@ -25,7 +25,6 @@ #ifndef __OPENSPACE_CORE___CAMERA___H__ #define __OPENSPACE_CORE___CAMERA___H__ -#include #include #include #include @@ -36,7 +35,6 @@ class SceneGraphNode; /** * This class still needs some more love. Suggested improvements: - * - Remove psc from the camera class interface. * - Accessors should return constant references to double precision class members. * - Remove the scaling variable (What is it used for?) * - Remove the maxFov and sinMaxfov variables. Redundant since the fov is embedded diff --git a/include/openspace/util/powerscaledcoordinate.h b/include/openspace/util/powerscaledcoordinate.h deleted file mode 100644 index 64f258940c..0000000000 --- a/include/openspace/util/powerscaledcoordinate.h +++ /dev/null @@ -1,114 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2019 * - * * - * 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_CORE___POWERSCALEDCOORDINATE___H__ -#define __OPENSPACE_CORE___POWERSCALEDCOORDINATE___H__ - -#include - -namespace openspace { - -class PowerScaledScalar; - -class PowerScaledCoordinate { -public: - // constructors - PowerScaledCoordinate() = default; - - PowerScaledCoordinate(PowerScaledCoordinate&& rhs); - PowerScaledCoordinate(const PowerScaledCoordinate& rhs); - - // Sets the power scaled coordinates directly - PowerScaledCoordinate(glm::vec4 v); - PowerScaledCoordinate(float f1, float f2, float f3, float f4); - // Sets the power scaled coordinates with w = 0 - PowerScaledCoordinate(glm::vec3 v); - - static PowerScaledCoordinate CreatePowerScaledCoordinate(double d1, double d2, - double d3); - - // get functions - // return the full, unmodified PSC - const glm::vec4& vec4() const; - - // returns the rescaled, "normal" coordinates - glm::vec3 vec3() const; - - // return the full psc as dvec4() - glm::dvec4 dvec4() const; - - // rescaled return as dvec3 - glm::dvec3 dvec3() const; - - // length of the vector as a pss - float length() const; - glm::vec3 direction() const; - - // operator overloading - PowerScaledCoordinate& operator=(const PowerScaledCoordinate& rhs); - PowerScaledCoordinate& operator=(PowerScaledCoordinate&& rhs); - PowerScaledCoordinate& operator+=(const PowerScaledCoordinate& rhs); - PowerScaledCoordinate operator+(const PowerScaledCoordinate& rhs) const; - PowerScaledCoordinate& operator-=(const PowerScaledCoordinate& rhs); - PowerScaledCoordinate operator-(const PowerScaledCoordinate& rhs) const; - float& operator[](unsigned int idx); - float operator[](unsigned int idx) const; - double dot(const PowerScaledCoordinate& rhs) const; - double angle(const PowerScaledCoordinate& rhs) const; - - // scalar operators - PowerScaledCoordinate operator*(const double& rhs) const; - PowerScaledCoordinate operator*(const float& rhs) const; - PowerScaledCoordinate operator*(const glm::mat4& matrix) const; - - - // comparison - bool operator==(const PowerScaledCoordinate& other) const; - bool operator!=(const PowerScaledCoordinate& other) const; - bool operator<(const PowerScaledCoordinate& other) const; - bool operator>(const PowerScaledCoordinate& other) const; - bool operator<=(const PowerScaledCoordinate& other) const; - bool operator>=(const PowerScaledCoordinate& other) const; - - // glm integration - PowerScaledCoordinate& operator=(const glm::dvec4& rhs); - PowerScaledCoordinate& operator=(const glm::vec4& rhs); - PowerScaledCoordinate& operator=(const glm::dvec3& rhs); - PowerScaledCoordinate& operator=(const glm::vec3& rhs); - - friend std::ostream& operator<<(std::ostream& os, const PowerScaledCoordinate& rhs); - - // allow the power scaled scalars to access private members - friend class PowerScaledScalar; - -private: - // internal glm vector - glm::vec4 _vec = glm::vec4(0.f); -}; - -typedef PowerScaledCoordinate psc; - -} // namespace openspace - -#endif // __OPENSPACE_CORE___POWERSCALEDCOORDINATE___H__ diff --git a/include/openspace/util/powerscaledsphere.h b/include/openspace/util/sphere.h similarity index 86% rename from include/openspace/util/powerscaledsphere.h rename to include/openspace/util/sphere.h index 8be00b6f0b..47ff24e061 100644 --- a/include/openspace/util/powerscaledsphere.h +++ b/include/openspace/util/sphere.h @@ -22,22 +22,20 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___POWERSCALEDSPHERE___H__ -#define __OPENSPACE_CORE___POWERSCALEDSPHERE___H__ +#ifndef __OPENSPACE_CORE___SPHERE___H__ +#define __OPENSPACE_CORE___SPHERE___H__ #include #include namespace openspace { -class PowerScaledSphere; - -class PowerScaledSphere { +class Sphere { public: - PowerScaledSphere(float radius, int segments = 8); - PowerScaledSphere(glm::vec3 radius, int segments); - PowerScaledSphere(const PowerScaledSphere& cpy); - ~PowerScaledSphere(); + Sphere(float radius, int segments = 8); + Sphere(glm::vec3 radius, int segments); + Sphere(const Sphere& cpy); + ~Sphere(); bool initialize(); @@ -62,4 +60,4 @@ public: } // namespace openspace -#endif // __OPENSPACE_CORE___POWERSCALEDSPHERE___H__ +#endif // __OPENSPACE_CORE___SPHERE___H__ diff --git a/include/openspace/util/updatestructures.h b/include/openspace/util/updatestructures.h index f6ecef64a4..406181eebc 100644 --- a/include/openspace/util/updatestructures.h +++ b/include/openspace/util/updatestructures.h @@ -26,7 +26,6 @@ #define __OPENSPACE_CORE___UPDATESTRUCTURES___H__ #include -#include #include namespace openspace { diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 3e5dec47ad..3cb7b040ff 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -60,7 +60,6 @@ #include #include -#include #include #include #include diff --git a/modules/base/rendering/renderablesphere.cpp b/modules/base/rendering/renderablesphere.cpp index 1d653791fd..c3ffa2dc70 100644 --- a/modules/base/rendering/renderablesphere.cpp +++ b/modules/base/rendering/renderablesphere.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -304,7 +304,7 @@ bool RenderableSphere::isReady() const { } void RenderableSphere::initializeGL() { - _sphere = std::make_unique(_size, _segments); + _sphere = std::make_unique(_size, _segments); _sphere->initialize(); _shader = BaseModule::ProgramObjectManager.request( @@ -467,7 +467,7 @@ void RenderableSphere::update(const UpdateData&) { } if (_sphereIsDirty) { - _sphere = std::make_unique(_size, _segments); + _sphere = std::make_unique(_size, _segments); _sphere->initialize(); _sphereIsDirty = false; } diff --git a/modules/base/rendering/renderablesphere.h b/modules/base/rendering/renderablesphere.h index b7ff144fbd..e8e195eb71 100644 --- a/modules/base/rendering/renderablesphere.h +++ b/modules/base/rendering/renderablesphere.h @@ -40,7 +40,7 @@ namespace ghoul::opengl { namespace openspace { -class PowerScaledSphere; +class Sphere; struct RenderData; struct UpdateData; @@ -80,7 +80,7 @@ private: ghoul::opengl::ProgramObject* _shader = nullptr; std::unique_ptr _texture; - std::unique_ptr _sphere; + std::unique_ptr _sphere; UniformCache(opacity, modelViewProjection, modelViewRotation, colorTexture, _mirrorTexture) _uniformCache; diff --git a/modules/base/shaders/imageplane_vs.glsl b/modules/base/shaders/imageplane_vs.glsl index 0962157b38..995c35950c 100644 --- a/modules/base/shaders/imageplane_vs.glsl +++ b/modules/base/shaders/imageplane_vs.glsl @@ -22,6 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +// @TODO (abock, 2019-12-27) Move this file to the spacecraftinstruments module + #version __CONTEXT__ #include "PowerScaling/powerScaling_vs.hglsl" @@ -36,7 +38,7 @@ uniform mat4 modelViewProjectionTransform; void main() { - vec4 position = vec4(in_position.xyz * pow(10, in_position.w), 1); + vec4 position = vec4(in_position.xyz, 1); vec4 positionClipSpace = modelViewProjectionTransform * position; vec4 positionScreenSpace = z_normalization(positionClipSpace); diff --git a/modules/iswa/rendering/datasphere.cpp b/modules/iswa/rendering/datasphere.cpp index 10cdc263a2..cb68d437c7 100644 --- a/modules/iswa/rendering/datasphere.cpp +++ b/modules/iswa/rendering/datasphere.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -88,7 +88,7 @@ void DataSphere::initializeGL() { bool DataSphere::createGeometry() { const float radius = 6.371f * _radius * glm::pow(10.f, 6.f); int segments = 100; - _sphere = std::make_unique(radius, segments); + _sphere = std::make_unique(radius, segments); _sphere->initialize(); return true; } diff --git a/modules/iswa/rendering/datasphere.h b/modules/iswa/rendering/datasphere.h index 2ec89762ea..66b5948a93 100644 --- a/modules/iswa/rendering/datasphere.h +++ b/modules/iswa/rendering/datasphere.h @@ -29,7 +29,7 @@ namespace openspace { -class PowerScaledSphere; +class Sphere; /** * DataSphere is a concrete IswaCygnet with data files as its input source. The class @@ -53,7 +53,7 @@ protected: void setUniforms() override; std::vector textureData() override; - std::unique_ptr _sphere; + std::unique_ptr _sphere; float _radius; }; diff --git a/modules/iswa/rendering/iswacygnet.cpp b/modules/iswa/rendering/iswacygnet.cpp index 663ba6dca4..967613f9bf 100644 --- a/modules/iswa/rendering/iswacygnet.cpp +++ b/modules/iswa/rendering/iswacygnet.cpp @@ -29,7 +29,6 @@ #include #include #include -#include #include #include #include @@ -157,12 +156,13 @@ void IswaCygnet::render(const RenderData& data, RendererTasks&) { } transform = transform * _rotation; - psc position = + glm::vec4 pposition = static_cast(glm::dvec4(data.modelTransform.translation, 0.0)) + transform * glm::vec4( _data.spatialScale.x * _data.offset, _data.spatialScale.w ); + glm::vec3 position = glm::vec3(pposition) * pow(10.f, pposition.w); // Activate shader _shader->activate(); @@ -173,7 +173,7 @@ void IswaCygnet::render(const RenderData& data, RendererTasks&) { _shader->setUniform("ModelTransform", transform); _shader->setUniform("campos", glm::vec4(data.camera.positionVec3(), 1.f)); - _shader->setUniform("objpos", glm::vec4(position.vec3(), 0.f)); + _shader->setUniform("objpos", glm::vec4(position, 0.f)); _shader->setUniform("camrot", glm::mat4(data.camera.viewRotationMatrix())); _shader->setUniform("scaling", glm::vec2(1.f, 0.f)); diff --git a/modules/space/rendering/simplespheregeometry.cpp b/modules/space/rendering/simplespheregeometry.cpp index 347752cc3c..4b8fcdd514 100644 --- a/modules/space/rendering/simplespheregeometry.cpp +++ b/modules/space/rendering/simplespheregeometry.cpp @@ -25,9 +25,9 @@ #include #include -#include #include -#include +#include +#include namespace { constexpr openspace::properties::Property::PropertyInfo RadiusInfo = { @@ -124,7 +124,7 @@ void SimpleSphereGeometry::createSphere() { const glm::vec3 radius = _radius.value(); delete _sphere; - _sphere = new PowerScaledSphere(radius, _segments); + _sphere = new Sphere(radius, _segments); _sphere->initialize(); } diff --git a/modules/space/rendering/simplespheregeometry.h b/modules/space/rendering/simplespheregeometry.h index 8148ec052e..abed585ab9 100644 --- a/modules/space/rendering/simplespheregeometry.h +++ b/modules/space/rendering/simplespheregeometry.h @@ -32,7 +32,7 @@ namespace openspace { class Renderable; - class PowerScaledSphere; + class Sphere; } // namespace openspace namespace openspace::documentation { struct Documentation; } @@ -57,7 +57,7 @@ private: properties::Vec3Property _radius; properties::IntProperty _segments; - PowerScaledSphere* _sphere; + Sphere* _sphere; }; } // namespace openspace::planetgeometry diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp index 8dba28ee8d..556c946e1f 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp @@ -461,11 +461,7 @@ void RenderableModelProjection::attitudeParameters(double time) { lightTime ); - // @TODO: Remove this and replace with cpos = p * 1000 ? - psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z); - - position[3] += 4; - const glm::vec3 cpos = position.vec3(); + const glm::vec3 cpos = p * 10000.0; const float distance = glm::length(cpos); const float radius = boundingSphere(); diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp index 48508ce2f8..85eed498c2 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp @@ -227,8 +227,7 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime ); // The apparent position, CN+S, makes image align best with target - // @TODO: Remove these powerscaled coordinates - psc projection[4]; + glm::dvec3 projection[4]; for (size_t j = 0; j < bounds.size(); ++j) { bounds[j] = SpiceManager::ref().frameTransformationMatrix( frame, @@ -246,12 +245,8 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime currentTime ) * cornerPosition; - projection[j] = PowerScaledCoordinate::CreatePowerScaledCoordinate( - cornerPosition[0], - cornerPosition[1], - cornerPosition[2] - ); - projection[j][3] += 3; + // km -> m + projection[j] = cornerPosition * 1000.0; } if (!_moving) { @@ -264,21 +259,28 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime } } + glm::vec3 p[4] = { + glm::vec3(projection[0]), + glm::vec3(projection[1]), + glm::vec3(projection[2]), + glm::vec3(projection[3]) + + }; const GLfloat vertex_data[] = { // square of two triangles drawn within fov in target coordinates // x y z w s t // Lower left 1 - projection[1][0], projection[1][1], projection[1][2], projection[1][3], 0, 0, + p[1].x, p[1].y, p[1].z, 0.f, 0.f, 0.f, // Upper right 2 - projection[3][0], projection[3][1], projection[3][2], projection[3][3], 1, 1, + p[3].x, p[3].y, p[3].z, 0.f, 1.f, 1.f, // Upper left 3 - projection[2][0], projection[2][1], projection[2][2], projection[2][3], 0, 1, + p[2].x, p[2].y, p[2].z, 0.f, 0.f, 1.f, // Lower left 4 = 1 - projection[1][0], projection[1][1], projection[1][2], projection[1][3], 0, 0, + p[1].x, p[1].y, p[1].z, 0.f, 0.f, 0.f, // Lower right 5 - projection[0][0], projection[0][1], projection[0][2], projection[0][3], 1, 0, + p[0].x, p[0].y, p[0].z, 0.f, 1.f, 0.f, // Upper left 6 = 2 - projection[3][0], projection[3][1], projection[3][2], projection[3][3], 1, 1, + p[3].x, p[3].y, p[3].z, 0.f, 1.f, 1.f, }; glBindVertexArray(_quad); diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.cpp b/modules/toyvolume/rendering/toyvolumeraycaster.cpp index 2f5f82f0ac..97d71c05bf 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.cpp +++ b/modules/toyvolume/rendering/toyvolumeraycaster.cpp @@ -24,7 +24,6 @@ #include -#include #include #include #include diff --git a/modules/volume/rendering/basicvolumeraycaster.cpp b/modules/volume/rendering/basicvolumeraycaster.cpp index f81912cfeb..b404d97bb3 100644 --- a/modules/volume/rendering/basicvolumeraycaster.cpp +++ b/modules/volume/rendering/basicvolumeraycaster.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d6bae69e26..bba42b68da 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -177,11 +177,10 @@ set(OPENSPACE_SOURCE ${OPENSPACE_BASE_DIR}/src/util/httprequest.cpp ${OPENSPACE_BASE_DIR}/src/util/keys.cpp ${OPENSPACE_BASE_DIR}/src/util/openspacemodule.cpp - ${OPENSPACE_BASE_DIR}/src/util/powerscaledcoordinate.cpp - ${OPENSPACE_BASE_DIR}/src/util/powerscaledsphere.cpp ${OPENSPACE_BASE_DIR}/src/util/progressbar.cpp ${OPENSPACE_BASE_DIR}/src/util/resourcesynchronization.cpp ${OPENSPACE_BASE_DIR}/src/util/screenlog.cpp + ${OPENSPACE_BASE_DIR}/src/util/sphere.cpp ${OPENSPACE_BASE_DIR}/src/util/spicemanager.cpp ${OPENSPACE_BASE_DIR}/src/util/spicemanager_lua.inl ${OPENSPACE_BASE_DIR}/src/util/syncbuffer.cpp @@ -371,11 +370,10 @@ set(OPENSPACE_HEADER ${OPENSPACE_BASE_DIR}/include/openspace/util/keys.h ${OPENSPACE_BASE_DIR}/include/openspace/util/mouse.h ${OPENSPACE_BASE_DIR}/include/openspace/util/openspacemodule.h - ${OPENSPACE_BASE_DIR}/include/openspace/util/powerscaledcoordinate.h - ${OPENSPACE_BASE_DIR}/include/openspace/util/powerscaledsphere.h ${OPENSPACE_BASE_DIR}/include/openspace/util/progressbar.h ${OPENSPACE_BASE_DIR}/include/openspace/util/resourcesynchronization.h ${OPENSPACE_BASE_DIR}/include/openspace/util/screenlog.h + ${OPENSPACE_BASE_DIR}/include/openspace/util/sphere.h ${OPENSPACE_BASE_DIR}/include/openspace/util/spicemanager.h ${OPENSPACE_BASE_DIR}/include/openspace/util/syncable.h ${OPENSPACE_BASE_DIR}/include/openspace/util/syncbuffer.h diff --git a/src/util/powerscaledcoordinate.cpp b/src/util/powerscaledcoordinate.cpp deleted file mode 100644 index e5d1f5df75..0000000000 --- a/src/util/powerscaledcoordinate.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2019 * - * * - * 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 - -namespace { - constexpr const double k = 10.0; -} // namespace - -namespace openspace { - -PowerScaledCoordinate::PowerScaledCoordinate(PowerScaledCoordinate&& rhs) { - _vec = std::move(rhs._vec); -} - -PowerScaledCoordinate::PowerScaledCoordinate(glm::vec4 v) { - _vec = std::move(v); -} - -PowerScaledCoordinate::PowerScaledCoordinate(glm::vec3 v) { - _vec = glm::vec4(v, 0.f); -} - -PowerScaledCoordinate::PowerScaledCoordinate(float f1, float f2, float f3, float f4) { - _vec = glm::vec4(f1, f2, f3, f4); -} - -PowerScaledCoordinate::PowerScaledCoordinate(const PowerScaledCoordinate& rhs) { - _vec = rhs._vec; -} - -PowerScaledCoordinate -PowerScaledCoordinate::CreatePowerScaledCoordinate(double d1, double d2, double d3) -{ - char buff[600]; - - // find the number with maximum number of digits - double ad1 = std::abs(d1); - double ad2 = std::abs(d2); - double ad3 = std::abs(d3); - double max = (ad2 > ad1) ? ad2 : (ad3 > ad1) ? ad3 : ad1; - - // find out how many digits - // TODO: profile the next two lines and replace with something more efficient (ab) -#ifdef _MSC_VER - sprintf_s(buff, 600, "%.0f", max); - //sprintf(buff, "%.0f", max); -#else - sprintf(buff, "%.0f", max); -#endif - size_t digits = strlen(buff); - - //digits += 3; - - // rescale and return - double tp = 1.0 / pow(k, digits); - return PowerScaledCoordinate( - static_cast(d1 * tp), - static_cast(d2 * tp), - static_cast(d3 * tp), - static_cast(digits)); -} - -const glm::vec4& PowerScaledCoordinate::vec4() const -{ - return _vec; -} - -glm::vec3 PowerScaledCoordinate::vec3() const -{ - return glm::vec3(_vec[0] * pow(k, _vec[3]), _vec[1] * pow(k, _vec[3]), - _vec[2] * pow(k, _vec[3])); -} - -glm::dvec4 PowerScaledCoordinate::dvec4() const -{ - //return _vec; - return glm::dvec4(_vec); -} - -glm::dvec3 PowerScaledCoordinate::dvec3() const -{ - double p = pow(static_cast(k), static_cast(_vec[3])); - return glm::dvec3( static_cast(_vec[0]) * p, static_cast(_vec[1]) * p, - static_cast(_vec[2]) * p); -} - -float PowerScaledCoordinate::length() const -{ - return glm::length(glm::vec3(_vec[0], _vec[1], _vec[2])) * std::pow(10, _vec[3]); -} - -glm::vec3 PowerScaledCoordinate::direction() const -{ - glm::vec3 tmp(_vec[0], _vec[1], _vec[2]); - return glm::normalize(glm::vec3(_vec[0], _vec[1], _vec[2])); -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator=(const PowerScaledCoordinate& rhs) -{ - if (this != &rhs) { - _vec = rhs._vec; - } - return *this; // Return a reference to myself. -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator=(const glm::vec4& rhs) { - _vec = rhs; - return *this; // Return a reference to myself. -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator=(const glm::vec3& rhs) { - _vec = glm::vec4(rhs[0], rhs[1], rhs[2], 0.0); - return *this; // Return a reference to myself. -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator=(const glm::dvec4& rhs) { - _vec = glm::vec4(rhs); - return *this; // Return a reference to myself. -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator=(const glm::dvec3& rhs) { - _vec = glm::vec4(rhs[0], rhs[1], rhs[2], 0.0); - return *this; // Return a reference to myself. -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator=(PowerScaledCoordinate&& rhs) { - _vec = std::move(rhs._vec); - return *this; -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator+=(const PowerScaledCoordinate& rhs) -{ - double ds = _vec[3] - rhs._vec[3]; - if (ds >= 0.0) { - double p = pow(k, -ds); - *this = PowerScaledCoordinate(static_cast(rhs._vec[0] * p + _vec[0]), - static_cast(rhs._vec[1] * p + _vec[1]), - static_cast(rhs._vec[2] * p + _vec[2]), - _vec[3]); - } else { - double p = pow(k, ds); - *this = PowerScaledCoordinate(static_cast(rhs._vec[0] + _vec[0] * p), - static_cast(rhs._vec[1] + _vec[1] * p), - static_cast(rhs._vec[2] + _vec[2] * p), - rhs._vec[3]); - } - - return *this; -} - -PowerScaledCoordinate PowerScaledCoordinate:: - operator+(const PowerScaledCoordinate& rhs) const -{ - return PowerScaledCoordinate(*this) += rhs; -} - -PowerScaledCoordinate& PowerScaledCoordinate::operator-=(const PowerScaledCoordinate& rhs) -{ - double ds = this->_vec[3] - rhs._vec[3]; - if (ds >= 0.0) { - double p = pow(k, -ds); - *this = PowerScaledCoordinate(static_cast(-rhs._vec[0] * p + _vec[0]), - static_cast(-rhs._vec[1] * p + _vec[1]), - static_cast(-rhs._vec[2] * p + _vec[2]), - _vec[3]); - } else { - double p = pow(k, ds); - *this = PowerScaledCoordinate(static_cast(-rhs._vec[0] + _vec[0] * p), - static_cast(-rhs._vec[1] + _vec[1] * p), - static_cast(-rhs._vec[2] + _vec[2] * p), - rhs._vec[3]); - } - - return *this; -} - -PowerScaledCoordinate PowerScaledCoordinate::operator*(const double& rhs) const -{ - return PowerScaledCoordinate(static_cast(_vec[0] * rhs), - static_cast(_vec[1] * rhs), - static_cast(_vec[2] * rhs), _vec[3]); -} - -PowerScaledCoordinate PowerScaledCoordinate::operator*(const float& rhs) const -{ - return PowerScaledCoordinate(_vec[0] * rhs, _vec[1] * rhs, _vec[2] * rhs, _vec[3]); -} - -PowerScaledCoordinate PowerScaledCoordinate::operator*(const glm::mat4& matrix) const -{ - return matrix * _vec; -} - -PowerScaledCoordinate PowerScaledCoordinate:: - operator-(const PowerScaledCoordinate& rhs) const -{ - return PowerScaledCoordinate(*this) -= rhs; -} - -float& PowerScaledCoordinate::operator[](unsigned int idx) -{ - return _vec[idx]; -} - -float PowerScaledCoordinate::operator[](unsigned int idx) const -{ - return _vec[idx]; -} - -double PowerScaledCoordinate::dot(const PowerScaledCoordinate& rhs) const -{ - double ds = _vec[3] - rhs._vec[3]; - if (ds >= 0.0) { - double p = pow(k, -ds); - glm::dvec3 uPowerScaledCoordinatealed(rhs._vec[0] * p, rhs._vec[1] * p, - rhs._vec[2] * p); - glm::dvec3 shortened(_vec[0], _vec[1], _vec[2]); - return glm::dot(uPowerScaledCoordinatealed, shortened); - } else { - double p = pow(k, ds); - glm::dvec3 uPowerScaledCoordinatealed(_vec[0] * p, _vec[1] * p, _vec[2] * p); - glm::dvec3 shortened(rhs._vec[0], rhs._vec[1], rhs._vec[2]); - return glm::dot(uPowerScaledCoordinatealed, shortened); - } -} - -double PowerScaledCoordinate::angle(const PowerScaledCoordinate& rhs) const -{ - glm::dvec3 uPowerScaledCoordinatealed(rhs._vec[0], rhs._vec[1], rhs._vec[2]); - glm::dvec3 shortened(_vec[0], _vec[1], _vec[2]); - uPowerScaledCoordinatealed = glm::normalize(uPowerScaledCoordinatealed); - shortened = glm::normalize(shortened); - - return acos(glm::dot(uPowerScaledCoordinatealed, shortened)); -} - -bool PowerScaledCoordinate::operator==(const PowerScaledCoordinate& other) const -{ - return _vec == other._vec; -} - -bool PowerScaledCoordinate::operator!=(const PowerScaledCoordinate& other) const -{ - return _vec != other._vec; -} - -bool PowerScaledCoordinate::operator<(const PowerScaledCoordinate& other) const -{ - double ds = _vec[3] - other._vec[3]; - if (ds >= 0) { - double p = pow(k, -ds); - glm::dvec3 upscaled(other._vec[0] * p, other._vec[1] * p, - other._vec[2] * p); - glm::dvec3 shortened(_vec[0], _vec[1], _vec[2]); - return glm::length(shortened) < glm::length(upscaled); - } else { - double p = pow(k, ds); - glm::dvec3 upscaled(_vec[0] * p, _vec[1] * p, _vec[2] * p); - glm::dvec3 shortened(other._vec[0], other._vec[1], other._vec[2]); - return glm::length(shortened) < glm::length(upscaled); - } -} - -bool PowerScaledCoordinate::operator>(const PowerScaledCoordinate& other) const -{ - double ds = this->_vec[3] - other._vec[3]; - if (ds >= 0) { - double p = pow(k, -ds); - glm::dvec3 upscaled(other._vec[0] * p, other._vec[1] * p, - other._vec[2] * p); - glm::dvec3 shortened(_vec[0], _vec[1], _vec[2]); - return glm::length(shortened) > glm::length(upscaled); - } else { - double p = pow(k, ds); - glm::dvec3 upscaled(_vec[0] * p, _vec[1] * p, _vec[2] * p); - glm::dvec3 shortened(other._vec[0], other._vec[1], other._vec[2]); - return glm::length(shortened) > glm::length(upscaled); - } -} - -bool PowerScaledCoordinate::operator<=(const PowerScaledCoordinate& other) const -{ - return *this < other || *this == other; -} - -bool PowerScaledCoordinate::operator>=(const PowerScaledCoordinate& other) const -{ - return *this > other || *this == other; -} - -std::ostream& operator<<(::std::ostream& os, const PowerScaledCoordinate& rhs) -{ - os << "(" << rhs[0] << ", " << rhs[1] << ", " << rhs[2] << "; " << rhs[3] << ")"; - return os; -} - -} // namespace openspace diff --git a/src/util/powerscaledsphere.cpp b/src/util/sphere.cpp similarity index 93% rename from src/util/powerscaledsphere.cpp rename to src/util/sphere.cpp index 25319ddba1..cbd3cfc4dc 100644 --- a/src/util/powerscaledsphere.cpp +++ b/src/util/sphere.cpp @@ -22,9 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#include +#include -#include #include #include @@ -34,12 +33,12 @@ namespace { namespace openspace { -PowerScaledSphere::PowerScaledSphere(float radius, int segments) - : PowerScaledSphere(glm::vec3(radius), segments) +Sphere::Sphere(float radius, int segments) + : Sphere(glm::vec3(radius), segments) {} // Alternative Constructor for using accurate triaxial ellipsoid -PowerScaledSphere::PowerScaledSphere(glm::vec3 radius, int segments) +Sphere::Sphere(glm::vec3 radius, int segments) : _isize(6 * segments * segments) , _vsize((segments + 1) * (segments + 1)) , _varray(new Vertex[_vsize]) @@ -110,7 +109,7 @@ PowerScaledSphere::PowerScaledSphere(glm::vec3 radius, int segments) } } -PowerScaledSphere::PowerScaledSphere(const PowerScaledSphere& cpy) +Sphere::Sphere(const Sphere& cpy) : _vaoID(cpy._vaoID) , _vBufferID(cpy._vBufferID) , _iBufferID(cpy._iBufferID) @@ -125,7 +124,7 @@ PowerScaledSphere::PowerScaledSphere(const PowerScaledSphere& cpy) std::memcpy(_iarray, cpy._iarray, _isize * sizeof(int)); } -PowerScaledSphere::~PowerScaledSphere() { +Sphere::~Sphere() { delete[] _varray; delete[] _iarray; @@ -137,7 +136,7 @@ PowerScaledSphere::~PowerScaledSphere() { glDeleteVertexArrays(1, &_vaoID); } -bool PowerScaledSphere::initialize() { +bool Sphere::initialize() { // Initialize and upload to graphics card if (_vaoID == 0) { glGenVertexArrays(1, &_vaoID); @@ -197,7 +196,7 @@ bool PowerScaledSphere::initialize() { return true; } -void PowerScaledSphere::render() { +void Sphere::render() { glBindVertexArray(_vaoID); // select first VAO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID); glDrawElements(GL_TRIANGLES, _isize, GL_UNSIGNED_INT, nullptr); diff --git a/tests/main.cpp b/tests/main.cpp index b5c3cd717f..8fa9ef3765 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -66,7 +66,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/test_powerscalecoordinates.inl b/tests/test_powerscalecoordinates.inl deleted file mode 100644 index 23b22a70a9..0000000000 --- a/tests/test_powerscalecoordinates.inl +++ /dev/null @@ -1,63 +0,0 @@ -/***************************************************************************************** - * * - * OpenSpace * - * * - * Copyright (c) 2014-2019 * - * * - * 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 - -class PowerscaleCoordinatesTest : public testing::Test { -protected: - PowerscaleCoordinatesTest() { - } - - ~PowerscaleCoordinatesTest() { - } - - void reset() { - } - - openspace::Scene* scenegraph; -}; - - -TEST_F(PowerscaleCoordinatesTest, psc) { - - openspace::psc reference(2.f, 1.f, 1.1f, 1.f); - - openspace::psc first(1.f, 0.f, 1.f, 0.f); - openspace::psc second(1.9f, 1.f, 1.f, 1.f); - - EXPECT_EQ(reference, first + second); - EXPECT_TRUE(reference == (first + second)); - - openspace::psc third = first; - first[0] = 0.0; - - EXPECT_TRUE(third != first); - - -} - - - From e3afd82c4700536a2221fc76f64fdc873c93e964 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Sat, 28 Dec 2019 00:25:17 +0100 Subject: [PATCH 42/42] Move the mapping target->frame from SpiceManager to SpacecraftInstrumentModule (#closes 21) --- include/openspace/util/spicemanager.h | 52 ------------------- .../rendering/renderablefov.cpp | 15 ++++-- .../rendering/renderableplaneprojection.cpp | 5 +- .../spacecraftinstrumentsmodule.cpp | 27 ++++++++++ .../spacecraftinstrumentsmodule.h | 6 +++ src/util/spicemanager.cpp | 45 ---------------- 6 files changed, 49 insertions(+), 101 deletions(-) diff --git a/include/openspace/util/spicemanager.h b/include/openspace/util/spicemanager.h index 8aab7b6094..634a836571 100644 --- a/include/openspace/util/spicemanager.h +++ b/include/openspace/util/spicemanager.h @@ -652,36 +652,6 @@ public: FieldOfViewMethod method, AberrationCorrection aberrationCorrection, double& ephemerisTime) const; - /** - * Determine whether a specific \p target is in the field-of-view of a specified - * \p instrument or an \p observer at a given time. The reference frame used is - * derived from the \p target by converting it into an \c IAU inertial reference - * frame. - * - * \param target The name or NAIF ID code string of the target - * \param observer The name or NAIF ID code string of the observer - * \param instrument The name or NAIF ID code string of the instrument - * \param method The type of shape model used for the target - * \param aberrationCorrection The aberration correction method - * \param ephemerisTime Time of the observation (seconds past J2000) - * \return \c true if the target is visible, \c false otherwise - * - * \throw SpiceException If the \p target or \p observer do not name valid - * NAIF objects, the \p target or \p observer name the same NAIF object, the - * \p instrument does not name a valid NAIF object, or insufficient kernel - * information has been loaded. - * \pre \p target must not be empty. - * \pre \p observer must not be empty. - * \pre \p target and \p observer must not be different strings - * \pre \p referenceFrame must not be empty. - * \pre \p instrument must not be empty. - * - * \sa http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/fovtrg_c.html - */ - bool isTargetInFieldOfView(const std::string& target, const std::string& observer, - const std::string& instrument, FieldOfViewMethod method, - AberrationCorrection aberrationCorrection, double& ephemerisTime) const; - /// Struct that is used as the return value from the #targetState method struct TargetStateResult { /// The target position @@ -902,26 +872,6 @@ public: AberrationCorrection aberrationCorrection, double ephemerisTime, int numberOfTerminatorPoints); - /** - * This function adds a frame to a body. - * - * \param body - the name of the body - * \param frame - the name of the frame - * \return false if the arguments are empty - * - * \todo I think this function should die ---abock - */ - bool addFrame(std::string body, std::string frame); - - /** - * This function returns the frame of a body if defined, otherwise it returns - * IAU_ + body (most frames are known by the International Astronomical Union) - * \param body - the name of the body - * \return the frame of the body - * \todo I think this function should die ---abock - */ - std::string frameFromBody(const std::string& body) const; - /** * Sets the SpiceManager's exception handling. If UseException::No is passed to this * function, all subsequent calls will not throw an error, but fail silently instead. @@ -1048,8 +998,6 @@ private: std::map>> _spkIntervals; std::map> _ckCoverageTimes; std::map> _spkCoverageTimes; - // Vector of pairs: Body, Frame - std::vector> _frameByBody; /// Stores whether the SpiceManager throws exceptions (Yes) or fails silently (No) UseException _useExceptions = UseException::Yes; diff --git a/modules/spacecraftinstruments/rendering/renderablefov.cpp b/modules/spacecraftinstruments/rendering/renderablefov.cpp index ab4e0696e9..d4396b270e 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.cpp +++ b/modules/spacecraftinstruments/rendering/renderablefov.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -151,7 +152,6 @@ namespace { return 0.5 * bisect(p1, half, testFunction, half); } } - } // namespace namespace openspace { @@ -294,7 +294,10 @@ RenderableFov::RenderableFov(const ghoul::Dictionary& dictionary) if (dictionary.hasKey(KeyFrameConversions)) { ghoul::Dictionary fc = dictionary.value(KeyFrameConversions); for (const std::string& key : fc.keys()) { - openspace::SpiceManager::ref().addFrame(key, fc.value(key)); + global::moduleEngine.module()->addFrame( + key, + fc.value(key) + ); } } @@ -524,7 +527,12 @@ void RenderableFov::computeIntercepts(const UpdateData& data, const std::string& { const bool convert = (ref.find("IAU_") == std::string::npos); if (convert) { - return { SpiceManager::ref().frameFromBody(target), true }; + return { + global::moduleEngine.module()->frameFromBody( + target + ), + true + }; } else { return { ref, false }; @@ -917,6 +925,7 @@ std::pair RenderableFov::determineTarget(double time) { bool inFOV = SpiceManager::ref().isTargetInFieldOfView( pt, _instrument.spacecraft, + global::moduleEngine.module()->frameFromBody(pt), _instrument.name, SpiceManager::FieldOfViewMethod::Ellipsoid, _instrument.aberrationCorrection, diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp index 85eed498c2..64b7864e70 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp @@ -24,8 +24,10 @@ #include +#include #include #include +#include #include #include #include @@ -309,7 +311,8 @@ void RenderablePlaneProjection::setTarget(std::string body) { return; } - _target.frame = SpiceManager::ref().frameFromBody(body); + _target.frame = + global::moduleEngine.module()->frameFromBody(body); _target.body = std::move(body); } diff --git a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp index 3e2bf6847a..460418b055 100644 --- a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp +++ b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp @@ -94,4 +94,31 @@ SpacecraftInstrumentsModule::documentations() const }; } +bool SpacecraftInstrumentsModule::addFrame(std::string body, std::string frame) { + if (body.empty() || frame.empty()) { + return false; + } + else { + _frameByBody.emplace_back(body, frame); + return true; + } +} + +std::string SpacecraftInstrumentsModule::frameFromBody(const std::string& body) { + for (const std::pair& pair : _frameByBody) { + if (pair.first == body) { + return pair.second; + } + } + + constexpr const char* unionPrefix = "IAU_"; + + if (body.find(unionPrefix) == std::string::npos) { + return unionPrefix + body; + } + else { + return body; + } +} + } // namespace openspace diff --git a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.h b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.h index d05fefe8c5..fc37bd53bb 100644 --- a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.h +++ b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.h @@ -41,10 +41,16 @@ public: static ghoul::opengl::ProgramObjectManager ProgramObjectManager; + bool addFrame(std::string body, std::string frame); + std::string frameFromBody(const std::string& body); + protected: void internalInitialize(const ghoul::Dictionary&) override; void internalDeinitialize() override; void internalDeinitializeGL() override; + +private: + std::vector> _frameByBody; }; } // namespace openspace diff --git a/src/util/spicemanager.cpp b/src/util/spicemanager.cpp index 9aa2e51803..bd65b59db5 100644 --- a/src/util/spicemanager.cpp +++ b/src/util/spicemanager.cpp @@ -687,24 +687,6 @@ bool SpiceManager::isTargetInFieldOfView(const std::string& target, return visible == SPICETRUE; } -bool SpiceManager::isTargetInFieldOfView(const std::string& target, - const std::string& observer, - const std::string& instrument, - FieldOfViewMethod method, - AberrationCorrection aberrationCorrection, - double& ephemerisTime) const -{ - return isTargetInFieldOfView( - target, - observer, - frameFromBody(target), - instrument, - method, - aberrationCorrection, - ephemerisTime - ); -} - SpiceManager::TargetStateResult SpiceManager::targetState(const std::string& target, const std::string& observer, const std::string& referenceFrame, @@ -913,33 +895,6 @@ SpiceManager::TerminatorEllipseResult SpiceManager::terminatorEllipse( return res; } -bool SpiceManager::addFrame(std::string body, std::string frame) { - if (body.empty() || frame.empty()) { - return false; - } - else { - _frameByBody.emplace_back(body, frame); - return true; - } -} - -std::string SpiceManager::frameFromBody(const std::string& body) const { - for (const std::pair& pair : _frameByBody) { - if (pair.first == body) { - return pair.second; - } - } - - constexpr const char* unionPrefix = "IAU_"; - - if (body.find(unionPrefix) == std::string::npos) { - return unionPrefix + body; - } - else { - return body; - } -} - void SpiceManager::findCkCoverage(const std::string& path) { ghoul_assert(!path.empty(), "Empty file path"); ghoul_assert(FileSys.fileExists(path), fmt::format("File '{}' does not exist", path));