Index: ps/trunk/source/graphics/Overlay.cpp =================================================================== --- ps/trunk/source/graphics/Overlay.cpp (revision 20620) +++ ps/trunk/source/graphics/Overlay.cpp (revision 20621) @@ -1,39 +1,59 @@ -/* Copyright (C) 2011 Wildfire Games. +/* Copyright (C) 2017 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "Overlay.h" +#include "graphics/TextureManager.h" #include "ps/CStr.h" +#include "renderer/Renderer.h" SOverlayTexturedLine::LineCapType SOverlayTexturedLine::StrToLineCapType(const std::wstring& str) { if (str == L"round") return LINECAP_ROUND; else if (str == L"sharp") return LINECAP_SHARP; else if (str == L"square") return LINECAP_SQUARE; else if (str == L"flat") return LINECAP_FLAT; else { debug_warn(L"[Overlay] Unrecognized line cap type identifier"); return LINECAP_FLAT; } } +void SOverlayTexturedLine::CreateOverlayTexture(const SOverlayDescriptor* overlayDescriptor) +{ + CTextureProperties texturePropsBase(overlayDescriptor->m_LineTexture.c_str()); + texturePropsBase.SetWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE); + texturePropsBase.SetMaxAnisotropy(4.f); + + CTextureProperties texturePropsMask(overlayDescriptor->m_LineTextureMask.c_str()); + texturePropsMask.SetWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE); + texturePropsMask.SetMaxAnisotropy(4.f); + + m_AlwaysVisible = false; + m_Closed = true; + m_Thickness = overlayDescriptor->m_LineThickness; + m_TextureBase = g_Renderer.GetTextureManager().CreateTexture(texturePropsBase); + m_TextureMask = g_Renderer.GetTextureManager().CreateTexture(texturePropsMask); + + ENSURE(m_TextureBase); +} Index: ps/trunk/source/graphics/Overlay.h =================================================================== --- ps/trunk/source/graphics/Overlay.h (revision 20620) +++ ps/trunk/source/graphics/Overlay.h (revision 20621) @@ -1,190 +1,196 @@ /* Copyright (C) 2017 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #ifndef INCLUDED_GRAPHICS_OVERLAY #define INCLUDED_GRAPHICS_OVERLAY #include "graphics/Texture.h" #include "maths/Vector2D.h" #include "maths/Vector3D.h" #include "maths/FixedVector3D.h" #include "ps/CStrIntern.h" #include "ps/Shapes.h" class CTerrain; class CSimContext; class CTexturedLineRData; +struct SOverlayDescriptor; /** * Line-based overlay, with world-space coordinates, rendered in the world * potentially behind other objects. Designed for selection circles and debug info. */ struct SOverlayLine { SOverlayLine() : m_Thickness(1) { } CColor m_Color; std::vector m_Coords; // (x, y, z) vertex coordinate triples; shape is not automatically closed u8 m_Thickness; // in pixels void PushCoords(const CVector3D& v) { PushCoords(v.X, v.Y, v.Z); } void PushCoords(const float x, const float y, const float z) { m_Coords.push_back(x); m_Coords.push_back(y); m_Coords.push_back(z); } }; /** * Textured line overlay, with world-space coordinates, rendered in the world onto the terrain. * Designed for relatively static textured lines, i.e. territory borders, originally. * * Once submitted for rendering, instances must not be copied afterwards. The reason is that they * are assigned rendering data that is unique to the submitted instance, and non-transferable to * any copies that would otherwise be made. Amongst others, this restraint includes that they must * not be submitted by their address inside a std::vector storing them by value. */ struct SOverlayTexturedLine { enum LineCapType { LINECAP_FLAT, ///< no line ending; abrupt stop of the line (aka. butt ending) /** * Semi-circular line ending. The texture is mapped by curving the left vertical edge * around the semi-circle's rim. That is, the center point has UV coordinates (0.5;0.5), * and the rim vertices all have U coordinate 0 and a V coordinate that ranges from 0 to * 1 as the rim is traversed. */ LINECAP_ROUND, LINECAP_SHARP, ///< sharp point ending LINECAP_SQUARE, ///< square end that extends half the line width beyond the line end }; SOverlayTexturedLine() : m_Thickness(1.0f), m_Closed(false), m_AlwaysVisible(false), m_StartCapType(LINECAP_FLAT), m_EndCapType(LINECAP_FLAT), m_SimContext(NULL) { } CTexturePtr m_TextureBase; CTexturePtr m_TextureMask; /// Color to apply to the line texture, where indicated by the mask. CColor m_Color; /// (x, z) vertex coordinate pairs; y is computed automatically. std::vector m_Coords; /// Half-width of the line, in world-space units. float m_Thickness; /// Should this line be treated as a closed loop? If set, any end cap settings are ignored. bool m_Closed; /// Should this line be rendered fully visible at all times, even under the SoD? bool m_AlwaysVisible; LineCapType m_StartCapType; LineCapType m_EndCapType; /** * Simulation context applicable for this overlay line; used to obtain terrain information * during automatic computation of Y coordinates. */ const CSimContext* m_SimContext; /** * Cached renderer data, because expensive to compute. Allocated by the renderer when necessary * for rendering purposes. * * Note: the rendering data may be shared between copies of this object to prevent having to * recompute it, while at the same time maintaining copyability of this object (see also docs on * CTexturedLineRData). */ shared_ptr m_RenderData; /** * Converts a string line cap type into its corresponding LineCap enum value, and returns * the resulting value. If the input string is unrecognized, a warning is issued and a * default value is returned. */ static LineCapType StrToLineCapType(const std::wstring& str); + /** + * Creates the texture specified by the given overlay descriptor and assigns it to this overlay. + */ + void CreateOverlayTexture(const SOverlayDescriptor* overlayDescriptor); + void PushCoords(const float x, const float z) { m_Coords.push_back(x); m_Coords.push_back(z); } void PushCoords(const CVector2D& v) { PushCoords(v.X, v.Y); } void PushCoords(const std::vector& points) { for (size_t i = 0; i < points.size(); ++i) PushCoords(points[i]); } }; /** * Billboard sprite overlay, with world-space coordinates, rendered on top * of all other objects. Designed for health bars and rank icons. */ struct SOverlaySprite { CTexturePtr m_Texture; CColor m_Color; CVector3D m_Position; // base position float m_X0, m_Y0, m_X1, m_Y1; // billboard corner coordinates, relative to base position }; /** * Rectangular single-quad terrain overlay, in world space coordinates. The vertices of the quad * are not required to be coplanar; the quad is arbitrarily triangulated with no effort being made * to find a best fit to the underlying terrain. */ struct SOverlayQuad { CTexturePtr m_Texture; CTexturePtr m_TextureMask; CVector3D m_Corners[4]; CColor m_Color; }; struct SOverlaySphere { SOverlaySphere() : m_Radius(0) { } CVector3D m_Center; float m_Radius; CColor m_Color; }; enum EOverlayType { /// A single textured quad overlay, intended for entities that move around much, like units (e.g. foot soldiers, etc). DYNAMIC_QUAD, /// A more complex textured line overlay, composed of several textured line segments. STATIC_OUTLINE, }; struct SOverlayDescriptor { EOverlayType m_Type; CStrIntern m_QuadTexture; CStrIntern m_QuadTextureMask; CStrIntern m_LineTexture; CStrIntern m_LineTextureMask; float m_LineThickness; int m_Radius; SOverlayDescriptor() : m_LineThickness(0) { } }; // TODO: OverlayText #endif // INCLUDED_GRAPHICS_OVERLAY Index: ps/trunk/source/simulation2/components/CCmpSelectable.cpp =================================================================== --- ps/trunk/source/simulation2/components/CCmpSelectable.cpp (revision 20620) +++ ps/trunk/source/simulation2/components/CCmpSelectable.cpp (revision 20621) @@ -1,718 +1,673 @@ /* Copyright (C) 2017 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "ICmpSelectable.h" #include "graphics/Overlay.h" #include "graphics/Terrain.h" #include "graphics/TextureManager.h" #include "maths/Ease.h" #include "maths/MathUtil.h" #include "maths/Matrix3D.h" #include "maths/Vector3D.h" #include "maths/Vector2D.h" #include "ps/Profile.h" #include "renderer/Scene.h" #include "renderer/Renderer.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpPosition.h" #include "simulation2/components/ICmpFootprint.h" #include "simulation2/components/ICmpVisual.h" #include "simulation2/components/ICmpTerrain.h" #include "simulation2/components/ICmpOwnership.h" #include "simulation2/components/ICmpPlayer.h" #include "simulation2/components/ICmpPlayerManager.h" #include "simulation2/components/ICmpWaterManager.h" #include "simulation2/helpers/Render.h" #include "simulation2/system/Component.h" // Minimum alpha value for always visible overlays [0 fully transparent, 1 fully opaque] static const float MIN_ALPHA_ALWAYS_VISIBLE = 0.65f; // Minimum alpha value for other overlays static const float MIN_ALPHA_UNSELECTED = 0.0f; // Desaturation value for unselected, always visible overlays (0.33 = 33% desaturated or 66% of original saturation) static const float RGB_DESATURATION = 0.333333f; class CCmpSelectable : public ICmpSelectable { public: static void ClassInit(CComponentManager& componentManager) { componentManager.SubscribeToMessageType(MT_OwnershipChanged); componentManager.SubscribeToMessageType(MT_PlayerColorChanged); componentManager.SubscribeToMessageType(MT_PositionChanged); componentManager.SubscribeToMessageType(MT_TerrainChanged); componentManager.SubscribeToMessageType(MT_WaterChanged); } DEFAULT_COMPONENT_ALLOCATOR(Selectable) CCmpSelectable() : m_DebugBoundingBoxOverlay(NULL), m_DebugSelectionBoxOverlay(NULL), m_BuildingOverlay(NULL), m_UnitOverlay(NULL), m_RangeOverlayData(), m_FadeBaselineAlpha(0.f), m_FadeDeltaAlpha(0.f), m_FadeProgress(0.f), m_Selected(false), m_Cached(false), m_Visible(false) { m_Color = CColor(0, 0, 0, m_FadeBaselineAlpha); } ~CCmpSelectable() { delete m_DebugBoundingBoxOverlay; delete m_DebugSelectionBoxOverlay; delete m_BuildingOverlay; delete m_UnitOverlay; for (RangeOverlayData& rangeOverlay : m_RangeOverlayData) delete rangeOverlay.second; } static std::string GetSchema() { return "Allows this entity to be selected by the player." "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""; } virtual void Init(const CParamNode& paramNode) { m_EditorOnly = paramNode.GetChild("EditorOnly").IsOk(); // Certain special units always have their selection overlay shown m_AlwaysVisible = paramNode.GetChild("Overlay").GetChild("AlwaysVisible").IsOk(); if (m_AlwaysVisible) { m_AlphaMin = MIN_ALPHA_ALWAYS_VISIBLE; m_Color.a = m_AlphaMin; } else m_AlphaMin = MIN_ALPHA_UNSELECTED; const CParamNode& textureNode = paramNode.GetChild("Overlay").GetChild("Texture"); const CParamNode& outlineNode = paramNode.GetChild("Overlay").GetChild("Outline"); // Save some memory by using interned file paths in these descriptors (almost all actors and // entities have this component, and many use the same textures). if (textureNode.IsOk()) { // textured quad mode (dynamic, for units) m_OverlayDescriptor.m_Type = DYNAMIC_QUAD; m_OverlayDescriptor.m_QuadTexture = CStrIntern(TEXTUREBASEPATH + textureNode.GetChild("MainTexture").ToUTF8()); m_OverlayDescriptor.m_QuadTextureMask = CStrIntern(TEXTUREBASEPATH + textureNode.GetChild("MainTextureMask").ToUTF8()); } else if (outlineNode.IsOk()) { // textured outline mode (static, for buildings) m_OverlayDescriptor.m_Type = STATIC_OUTLINE; m_OverlayDescriptor.m_LineTexture = CStrIntern(TEXTUREBASEPATH + outlineNode.GetChild("LineTexture").ToUTF8()); m_OverlayDescriptor.m_LineTextureMask = CStrIntern(TEXTUREBASEPATH + outlineNode.GetChild("LineTextureMask").ToUTF8()); m_OverlayDescriptor.m_LineThickness = outlineNode.GetChild("LineThickness").ToFloat(); } m_EnabledInterpolate = false; m_EnabledRenderSubmit = false; UpdateMessageSubscriptions(); } virtual void Deinit() { } virtual void Serialize(ISerializer& UNUSED(serialize)) { // Nothing to do here (the overlay object is not worth saving, it'll get // reconstructed by the GUI soon enough, I think) } virtual void Deserialize(const CParamNode& paramNode, IDeserializer& UNUSED(deserialize)) { // Need to call Init to reload the template properties Init(paramNode); } virtual void HandleMessage(const CMessage& msg, bool UNUSED(global)); virtual void SetSelectionHighlight(const CColor& color, bool selected) { m_Selected = selected; m_Color.r = color.r; m_Color.g = color.g; m_Color.b = color.b; // Always-visible overlays will be desaturated if their parent unit is deselected. if (m_AlwaysVisible && !selected) { float max; // Reduce saturation by one-third, the quick-and-dirty way. if (m_Color.r > m_Color.b) max = (m_Color.r > m_Color.g) ? m_Color.r : m_Color.g; else max = (m_Color.b > m_Color.g) ? m_Color.b : m_Color.g; m_Color.r += (max - m_Color.r) * RGB_DESATURATION; m_Color.g += (max - m_Color.g) * RGB_DESATURATION; m_Color.b += (max - m_Color.b) * RGB_DESATURATION; } SetSelectionHighlightAlpha(color.a); } virtual void AddRangeOverlay(float radius, const std::string& texture, const std::string& textureMask, float thickness) { if (!CRenderer::IsInitialised()) return; SOverlayDescriptor rangeOverlayDescriptor; SOverlayTexturedLine* rangeOverlay = nullptr; rangeOverlayDescriptor.m_Radius = radius; rangeOverlayDescriptor.m_LineTexture = CStrIntern(TEXTUREBASEPATH + texture); rangeOverlayDescriptor.m_LineTextureMask = CStrIntern(TEXTUREBASEPATH + textureMask); rangeOverlayDescriptor.m_LineThickness = thickness; m_RangeOverlayData.push_back({rangeOverlayDescriptor, rangeOverlay}); } virtual void SetSelectionHighlightAlpha(float alpha) { alpha = std::max(m_AlphaMin, alpha); // set up fading from the current value (as the baseline) to the target value m_FadeBaselineAlpha = m_Color.a; m_FadeDeltaAlpha = alpha - m_FadeBaselineAlpha; m_FadeProgress = 0.f; UpdateMessageSubscriptions(); } virtual void SetVisibility(bool visible) { m_Visible = visible; UpdateMessageSubscriptions(); } virtual bool IsEditorOnly() const { return m_EditorOnly; } void RenderSubmit(SceneCollector& collector); /** * Draw a textured line overlay. The selection overlays for structures are based solely on footprint shape. */ void UpdateTexturedLineOverlay(const SOverlayDescriptor* overlayDescriptor, SOverlayTexturedLine& overlay, float frameOffset, bool buildingOverlay); /** * Called from the interpolation handler; responsible for ensuring the dynamic overlay (provided we're * using one) is up-to-date and ready to be submitted to the next rendering run. */ void UpdateDynamicOverlay(float frameOffset); /// Explicitly invalidates the static overlay. void InvalidateStaticOverlay(); /** * Subscribe/unsubscribe to MT_Interpolate, MT_RenderSubmit, depending on * whether we will do any actual work when receiving them. (This is to avoid * the performance cost of receiving messages in the typical case when the * entity is not selected.) * * Must be called after changing m_Visible, m_FadeDeltaAlpha, m_Color.a */ void UpdateMessageSubscriptions(); /** * Delete all range overlays. */ void ResetRangeOverlays(); /** * Set the color of the current owner. */ void UpdatePlayerColor(); private: SOverlayDescriptor m_OverlayDescriptor; SOverlayTexturedLine* m_BuildingOverlay; SOverlayQuad* m_UnitOverlay; // Holds the data for all range overlays typedef std::pair RangeOverlayData; std::vector m_RangeOverlayData; SOverlayLine* m_DebugBoundingBoxOverlay; SOverlayLine* m_DebugSelectionBoxOverlay; bool m_EnabledInterpolate; bool m_EnabledRenderSubmit; // Whether the selectable will be rendered. bool m_Visible; // Whether the entity is only selectable in Atlas editor bool m_EditorOnly; // Whether the selection overlay is always visible bool m_AlwaysVisible; /// Whether the parent entity is selected (caches GUI's selection state). bool m_Selected; /// Current selection overlay color. Alpha component is subject to fading. CColor m_Color; /// Whether the selectable's player color has been cached for rendering. bool m_Cached; /// Minimum value for current selection overlay alpha. float m_AlphaMin; /// Baseline alpha value to start fading from. Constant during a single fade. float m_FadeBaselineAlpha; /// Delta between target and baseline alpha. Constant during a single fade. Can be positive or negative. float m_FadeDeltaAlpha; /// Linear time progress of the fade, between 0 and m_FadeDuration. float m_FadeProgress; /// Total duration of a single fade, in seconds. Assumed constant for now; feel free to change this into /// a member variable if you need to adjust it per component. static const double FADE_DURATION; static const char* TEXTUREBASEPATH; }; const double CCmpSelectable::FADE_DURATION = 0.3; const char* CCmpSelectable::TEXTUREBASEPATH = "art/textures/selection/"; void CCmpSelectable::HandleMessage(const CMessage& msg, bool UNUSED(global)) { switch (msg.GetType()) { case MT_Interpolate: { PROFILE("Selectable::Interpolate"); const CMessageInterpolate& msgData = static_cast (msg); if (m_FadeDeltaAlpha != 0.f) { m_FadeProgress += msgData.deltaRealTime; if (m_FadeProgress >= FADE_DURATION) { const float targetAlpha = m_FadeBaselineAlpha + m_FadeDeltaAlpha; // stop the fade m_Color.a = targetAlpha; m_FadeBaselineAlpha = targetAlpha; m_FadeDeltaAlpha = 0.f; m_FadeProgress = FADE_DURATION; // will need to be reset to start the next fade again } else { m_Color.a = Ease::QuartOut(m_FadeProgress, m_FadeBaselineAlpha, m_FadeDeltaAlpha, FADE_DURATION); } } // update dynamic overlay only when visible if (m_Color.a > 0) { UpdateDynamicOverlay(msgData.offset); for (RangeOverlayData& rangeOverlay : m_RangeOverlayData) { delete rangeOverlay.second; rangeOverlay.second = new SOverlayTexturedLine; UpdateTexturedLineOverlay(&rangeOverlay.first, *rangeOverlay.second, msgData.offset, false); } } UpdateMessageSubscriptions(); break; } case MT_OwnershipChanged: { const CMessageOwnershipChanged& msgData = static_cast (msg); // Ignore newly constructed entities, as they receive their color upon first selection // Ignore deleted entities because they won't be rendered if (msgData.from == INVALID_PLAYER || msgData.to == INVALID_PLAYER) break; UpdatePlayerColor(); InvalidateStaticOverlay(); break; } case MT_PlayerColorChanged: { const CMessagePlayerColorChanged& msgData = static_cast (msg); CmpPtr cmpOwnership(GetEntityHandle()); if (!cmpOwnership || msgData.player != cmpOwnership->GetOwner()) break; UpdatePlayerColor(); break; } case MT_PositionChanged: { if (m_AlwaysVisible) { const CMessagePositionChanged& msgData = static_cast (msg); if (!msgData.inWorld) m_Color.a = m_AlphaMin = MIN_ALPHA_UNSELECTED; else if (!m_Selected) m_Color.a = m_AlphaMin = MIN_ALPHA_ALWAYS_VISIBLE; } InvalidateStaticOverlay(); break; } case MT_TerrainChanged: case MT_WaterChanged: InvalidateStaticOverlay(); break; case MT_RenderSubmit: { PROFILE("Selectable::RenderSubmit"); const CMessageRenderSubmit& msgData = static_cast (msg); RenderSubmit(msgData.collector); break; } } } void CCmpSelectable::UpdatePlayerColor() { CmpPtr cmpOwnership(GetEntityHandle()); CmpPtr cmpPlayerManager(GetSystemEntity()); if (!cmpPlayerManager) return; // Default to white if there's no owner (e.g. decorative, editor-only actors) CColor color(1.0, 1.0, 1.0, 1.0); if (cmpOwnership) { CmpPtr cmpPlayer(GetSimContext(), cmpPlayerManager->GetPlayerByID(cmpOwnership->GetOwner())); if (cmpPlayer) color = cmpPlayer->GetColor(); } // Update the highlight color, while keeping the current alpha target value intact // (i.e. baseline + delta), so that any ongoing fades simply continue with the new color. color.a = m_FadeBaselineAlpha + m_FadeDeltaAlpha; SetSelectionHighlight(color, m_Selected); } void CCmpSelectable::ResetRangeOverlays() { for (RangeOverlayData& rangeOverlay : m_RangeOverlayData) delete rangeOverlay.second; m_RangeOverlayData.clear(); UpdateMessageSubscriptions(); } void CCmpSelectable::UpdateMessageSubscriptions() { bool needInterpolate = false; bool needRenderSubmit = false; if (m_FadeDeltaAlpha != 0.f || m_Color.a > 0) needInterpolate = true; if (m_Visible && m_Color.a > 0) needRenderSubmit = true; if (needInterpolate != m_EnabledInterpolate) { GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_Interpolate, this, needInterpolate); m_EnabledInterpolate = needInterpolate; } if (needRenderSubmit != m_EnabledRenderSubmit) { GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_RenderSubmit, this, needRenderSubmit); m_EnabledRenderSubmit = needRenderSubmit; } } void CCmpSelectable::InvalidateStaticOverlay() { SAFE_DELETE(m_BuildingOverlay); } void CCmpSelectable::UpdateTexturedLineOverlay(const SOverlayDescriptor* overlayDescriptor, SOverlayTexturedLine& overlay, float frameOffset, bool buildingOverlay) { if (!CRenderer::IsInitialised()) return; CmpPtr cmpPosition(GetEntityHandle()); CmpPtr cmpFootprint(GetEntityHandle()); if (!cmpFootprint || !cmpPosition || !cmpPosition->IsInWorld()) return; ICmpFootprint::EShape fpShape; entity_pos_t fpSize0_fixed, fpSize1_fixed, fpHeight_fixed; cmpFootprint->GetShape(fpShape, fpSize0_fixed, fpSize1_fixed, fpHeight_fixed); float rotY; CVector2D origin; cmpPosition->GetInterpolatedPosition2D(frameOffset, origin.X, origin.Y, rotY); - CFixedVector3D rotation = cmpPosition->GetRotation(); - CTextureProperties texturePropsBase(overlayDescriptor->m_LineTexture.c_str()); - texturePropsBase.SetWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE); - texturePropsBase.SetMaxAnisotropy(4.f); - - CTextureProperties texturePropsMask(overlayDescriptor->m_LineTextureMask.c_str()); - texturePropsMask.SetWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE); - texturePropsMask.SetMaxAnisotropy(4.f); - - overlay.m_AlwaysVisible = false; - overlay.m_Closed = true; overlay.m_SimContext = &GetSimContext(); - overlay.m_Thickness = overlayDescriptor->m_LineThickness; - overlay.m_TextureBase = g_Renderer.GetTextureManager().CreateTexture(texturePropsBase); - overlay.m_TextureMask = g_Renderer.GetTextureManager().CreateTexture(texturePropsMask); overlay.m_Color = m_Color; + overlay.CreateOverlayTexture(overlayDescriptor); if (buildingOverlay && fpShape == ICmpFootprint::SQUARE) - { - float s = sinf(-rotation.Y.ToFloat()); - float c = cosf(-rotation.Y.ToFloat()); - CVector2D unitX(c, s); - CVector2D unitZ(-s, c); - - // Add half the line thickness to the radius so that we get an 'outside' stroke of the footprint shape - const float halfSizeX = fpSize0_fixed.ToFloat() / 2.f + overlay.m_Thickness / 2.f; - const float halfSizeZ = fpSize1_fixed.ToFloat() / 2.f + overlay.m_Thickness / 2.f; - - std::vector points; - points.push_back(CVector2D(origin + unitX * halfSizeX + unitZ * (-halfSizeZ))); - points.push_back(CVector2D(origin + unitX * (-halfSizeX) + unitZ * (-halfSizeZ))); - points.push_back(CVector2D(origin + unitX * (-halfSizeX) + unitZ * halfSizeZ)); - points.push_back(CVector2D(origin + unitX * halfSizeX + unitZ * halfSizeZ)); - - SimRender::SubdividePoints(points, TERRAIN_TILE_SIZE / 3.f, overlay.m_Closed); - overlay.PushCoords(points); - } + SimRender::ConstructTexturedLineBox(overlay, origin, cmpPosition->GetRotation(), fpSize0_fixed.ToFloat(), fpSize1_fixed.ToFloat()); else - { - const float radius = (buildingOverlay ? fpSize0_fixed.ToFloat() : overlayDescriptor->m_Radius) + overlay.m_Thickness / 3.f; - - u32 numSteps = ceilf(float(2 * M_PI) * radius / (TERRAIN_TILE_SIZE / 3.f)); - for (u32 i = 0; i < numSteps; ++i) - { - float angle = i * float(2 * M_PI) / numSteps; - float px = origin.X + radius * sinf(angle); - float pz = origin.Y + radius * cosf(angle); - - overlay.PushCoords(px, pz); - } - } - - ENSURE(overlay.m_TextureBase); + SimRender::ConstructTexturedLineCircle(overlay, origin, buildingOverlay ? fpSize0_fixed.ToFloat() : overlayDescriptor->m_Radius); } void CCmpSelectable::UpdateDynamicOverlay(float frameOffset) { // Dynamic overlay lines are allocated once and never deleted. Since they are expected to change frequently, // they are assumed dirty on every call to this function, and we should therefore use this function more // thoughtfully than calling it right before every frame render. if (m_OverlayDescriptor.m_Type != DYNAMIC_QUAD) return; if (!CRenderer::IsInitialised()) return; CmpPtr cmpPosition(GetEntityHandle()); CmpPtr cmpFootprint(GetEntityHandle()); if (!cmpFootprint || !cmpPosition || !cmpPosition->IsInWorld()) return; float rotY; CVector2D position; cmpPosition->GetInterpolatedPosition2D(frameOffset, position.X, position.Y, rotY); CmpPtr cmpWaterManager(GetSystemEntity()); CmpPtr cmpTerrain(GetSystemEntity()); ENSURE(cmpWaterManager && cmpTerrain); CTerrain* terrain = cmpTerrain->GetCTerrain(); ENSURE(terrain); ICmpFootprint::EShape fpShape; entity_pos_t fpSize0_fixed, fpSize1_fixed, fpHeight_fixed; cmpFootprint->GetShape(fpShape, fpSize0_fixed, fpSize1_fixed, fpHeight_fixed); // --------------------------------------------------------------------------------- if (!m_UnitOverlay) { m_UnitOverlay = new SOverlayQuad; // Assuming we don't need the capability of swapping textures on-demand. CTextureProperties texturePropsBase(m_OverlayDescriptor.m_QuadTexture.c_str()); texturePropsBase.SetWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE); texturePropsBase.SetMaxAnisotropy(4.f); CTextureProperties texturePropsMask(m_OverlayDescriptor.m_QuadTextureMask.c_str()); texturePropsMask.SetWrap(GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE); texturePropsMask.SetMaxAnisotropy(4.f); m_UnitOverlay->m_Texture = g_Renderer.GetTextureManager().CreateTexture(texturePropsBase); m_UnitOverlay->m_TextureMask = g_Renderer.GetTextureManager().CreateTexture(texturePropsMask); } m_UnitOverlay->m_Color = m_Color; // TODO: some code duplication here :< would be nice to factor out getting the corner points of an // entity based on its footprint sizes (and regardless of whether it's a circle or a square) float s = sinf(-rotY); float c = cosf(-rotY); CVector2D unitX(c, s); CVector2D unitZ(-s, c); float halfSizeX = fpSize0_fixed.ToFloat(); float halfSizeZ = fpSize1_fixed.ToFloat(); if (fpShape == ICmpFootprint::SQUARE) { halfSizeX /= 2.0f; halfSizeZ /= 2.0f; } std::vector points; points.push_back(CVector2D(position + unitX *(-halfSizeX) + unitZ * halfSizeZ)); // top left points.push_back(CVector2D(position + unitX *(-halfSizeX) + unitZ *(-halfSizeZ))); // bottom left points.push_back(CVector2D(position + unitX * halfSizeX + unitZ *(-halfSizeZ))); // bottom right points.push_back(CVector2D(position + unitX * halfSizeX + unitZ * halfSizeZ)); // top right for (int i=0; i < 4; i++) { float quadY = std::max( terrain->GetExactGroundLevel(points[i].X, points[i].Y), cmpWaterManager->GetExactWaterLevel(points[i].X, points[i].Y) ); m_UnitOverlay->m_Corners[i] = CVector3D(points[i].X, quadY, points[i].Y); } } void CCmpSelectable::RenderSubmit(SceneCollector& collector) { // don't render selection overlay if it's not gonna be visible if (!ICmpSelectable::m_OverrideVisible) return; if (m_Visible && m_Color.a > 0) { if (!m_Cached) { UpdatePlayerColor(); m_Cached = true; } switch (m_OverlayDescriptor.m_Type) { case STATIC_OUTLINE: { if (!m_BuildingOverlay) { // Static overlays are allocated once and not updated until they are explicitly deleted again // (see InvalidateStaticOverlay). Since they are expected to change rarely (if ever) during // normal gameplay, this saves us doing all the work below on each frame. m_BuildingOverlay = new SOverlayTexturedLine; UpdateTexturedLineOverlay(&m_OverlayDescriptor, *m_BuildingOverlay, 0, true); } m_BuildingOverlay->m_Color = m_Color; // done separately so alpha changes don't require a full update call collector.Submit(m_BuildingOverlay); } break; case DYNAMIC_QUAD: { if (m_UnitOverlay) collector.Submit(m_UnitOverlay); } break; default: break; } for (const RangeOverlayData& rangeOverlay : m_RangeOverlayData) if (rangeOverlay.second) collector.Submit(rangeOverlay.second); } // Render bounding box debug overlays if we have a positive target alpha value. This ensures // that the debug overlays respond immediately to deselection without delay from fading out. if (m_FadeBaselineAlpha + m_FadeDeltaAlpha > 0) { if (ICmpSelectable::ms_EnableDebugOverlays) { // allocate debug overlays on-demand if (!m_DebugBoundingBoxOverlay) m_DebugBoundingBoxOverlay = new SOverlayLine; if (!m_DebugSelectionBoxOverlay) m_DebugSelectionBoxOverlay = new SOverlayLine; CmpPtr cmpVisual(GetEntityHandle()); if (cmpVisual) { SimRender::ConstructBoxOutline(cmpVisual->GetBounds(), *m_DebugBoundingBoxOverlay); m_DebugBoundingBoxOverlay->m_Thickness = 2; m_DebugBoundingBoxOverlay->m_Color = CColor(1.f, 0.f, 0.f, 1.f); SimRender::ConstructBoxOutline(cmpVisual->GetSelectionBox(), *m_DebugSelectionBoxOverlay); m_DebugSelectionBoxOverlay->m_Thickness = 2; m_DebugSelectionBoxOverlay->m_Color = CColor(0.f, 1.f, 0.f, 1.f); collector.Submit(m_DebugBoundingBoxOverlay); collector.Submit(m_DebugSelectionBoxOverlay); } } else { // reclaim debug overlay line memory when no longer debugging (and make sure to set to zero after deletion) if (m_DebugBoundingBoxOverlay) SAFE_DELETE(m_DebugBoundingBoxOverlay); if (m_DebugSelectionBoxOverlay) SAFE_DELETE(m_DebugSelectionBoxOverlay); } } } REGISTER_COMPONENT_TYPE(Selectable) Index: ps/trunk/source/simulation2/helpers/Render.cpp =================================================================== --- ps/trunk/source/simulation2/helpers/Render.cpp (revision 20620) +++ ps/trunk/source/simulation2/helpers/Render.cpp (revision 20621) @@ -1,602 +1,640 @@ /* Copyright (C) 2017 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "Render.h" #include "graphics/Overlay.h" #include "graphics/Terrain.h" #include "maths/BoundingBoxAligned.h" #include "maths/BoundingBoxOriented.h" #include "maths/MathUtil.h" #include "maths/Quaternion.h" #include "maths/Vector2D.h" #include "ps/Profile.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpTerrain.h" #include "simulation2/components/ICmpWaterManager.h" #include "simulation2/helpers/Geometry.h" void SimRender::ConstructLineOnGround(const CSimContext& context, const std::vector& xz, SOverlayLine& overlay, bool floating, float heightOffset) { PROFILE("ConstructLineOnGround"); overlay.m_Coords.clear(); CmpPtr cmpTerrain(context, SYSTEM_ENTITY); if (!cmpTerrain) return; if (xz.size() < 2) return; float water = 0.f; if (floating) { CmpPtr cmpWaterManager(context, SYSTEM_ENTITY); if (cmpWaterManager) water = cmpWaterManager->GetExactWaterLevel(xz[0], xz[1]); } overlay.m_Coords.reserve(xz.size()/2 * 3); for (size_t i = 0; i < xz.size(); i += 2) { float px = xz[i]; float pz = xz[i+1]; float py = std::max(water, cmpTerrain->GetExactGroundLevel(px, pz)) + heightOffset; overlay.m_Coords.push_back(px); overlay.m_Coords.push_back(py); overlay.m_Coords.push_back(pz); } } static void ConstructCircleOrClosedArc( const CSimContext& context, float x, float z, float radius, bool isCircle, float start, float end, SOverlayLine& overlay, bool floating, float heightOffset) { overlay.m_Coords.clear(); CmpPtr cmpTerrain(context, SYSTEM_ENTITY); if (!cmpTerrain) return; float water = 0.f; if (floating) { CmpPtr cmpWaterManager(context, SYSTEM_ENTITY); if (cmpWaterManager) water = cmpWaterManager->GetExactWaterLevel(x, z); } // Adapt the circle resolution to look reasonable for small and largeish radiuses size_t numPoints = clamp((size_t)(radius*(end-start)), (size_t)12, (size_t)48); if (!isCircle) overlay.m_Coords.reserve((numPoints + 1 + 2) * 3); else overlay.m_Coords.reserve((numPoints + 1) * 3); float cy; if (!isCircle) { // Start at the center point cy = std::max(water, cmpTerrain->GetExactGroundLevel(x, z)) + heightOffset; overlay.m_Coords.push_back(x); overlay.m_Coords.push_back(cy); overlay.m_Coords.push_back(z); } for (size_t i = 0; i <= numPoints; ++i) // use '<=' so it's a closed loop { float a = start + (float)i * (end - start) / (float)numPoints; float px = x + radius * cosf(a); float pz = z + radius * sinf(a); float py = std::max(water, cmpTerrain->GetExactGroundLevel(px, pz)) + heightOffset; overlay.m_Coords.push_back(px); overlay.m_Coords.push_back(py); overlay.m_Coords.push_back(pz); } if (!isCircle) { // Return to the center point overlay.m_Coords.push_back(x); overlay.m_Coords.push_back(cy); overlay.m_Coords.push_back(z); } } void SimRender::ConstructCircleOnGround( const CSimContext& context, float x, float z, float radius, SOverlayLine& overlay, bool floating, float heightOffset) { ConstructCircleOrClosedArc(context, x, z, radius, true, 0.0f, 2.0f*(float)M_PI, overlay, floating, heightOffset); } void SimRender::ConstructClosedArcOnGround( const CSimContext& context, float x, float z, float radius, float start, float end, SOverlayLine& overlay, bool floating, float heightOffset) { ConstructCircleOrClosedArc(context, x, z, radius, false, start, end, overlay, floating, heightOffset); } // This method splits up a straight line into a number of line segments each having a length ~= TERRAIN_TILE_SIZE static void SplitLine(std::vector >& coords, float x1, float y1, float x2, float y2) { float length = sqrtf(SQR(x1 - x2) + SQR(y1 - y2)); size_t pieces = ((int)length) / TERRAIN_TILE_SIZE; if (pieces > 0) { float xPieceLength = (x1 - x2) / (float)pieces; float yPieceLength = (y1 - y2) / (float)pieces; for (size_t i = 1; i <= (pieces - 1); ++i) { coords.emplace_back(x1 - (xPieceLength * (float)i), y1 - (yPieceLength * (float)i)); } } coords.emplace_back(x2, y2); } void SimRender::ConstructSquareOnGround(const CSimContext& context, float x, float z, float w, float h, float a, SOverlayLine& overlay, bool floating, float heightOffset) { overlay.m_Coords.clear(); CmpPtr cmpTerrain(context, SYSTEM_ENTITY); if (!cmpTerrain) return; float water = 0.f; if (floating) { CmpPtr cmpWaterManager(context, SYSTEM_ENTITY); if (cmpWaterManager) water = cmpWaterManager->GetExactWaterLevel(x, z); } float c = cosf(a); float s = sinf(a); std::vector > coords; // Add the first vertex, since SplitLine will be adding only the second end-point of the each line to // the coordinates list. We don't have to worry about the other lines, since the end-point of one line // will be the starting point of the next coords.emplace_back(x - w/2*c + h/2*s, z + w/2*s + h/2*c); SplitLine(coords, x - w/2*c + h/2*s, z + w/2*s + h/2*c, x - w/2*c - h/2*s, z + w/2*s - h/2*c); SplitLine(coords, x - w/2*c - h/2*s, z + w/2*s - h/2*c, x + w/2*c - h/2*s, z - w/2*s - h/2*c); SplitLine(coords, x + w/2*c - h/2*s, z - w/2*s - h/2*c, x + w/2*c + h/2*s, z - w/2*s + h/2*c); SplitLine(coords, x + w/2*c + h/2*s, z - w/2*s + h/2*c, x - w/2*c + h/2*s, z + w/2*s + h/2*c); overlay.m_Coords.reserve(coords.size() * 3); for (size_t i = 0; i < coords.size(); ++i) { float px = coords[i].first; float pz = coords[i].second; float py = std::max(water, cmpTerrain->GetExactGroundLevel(px, pz)) + heightOffset; overlay.m_Coords.push_back(px); overlay.m_Coords.push_back(py); overlay.m_Coords.push_back(pz); } } void SimRender::ConstructBoxOutline(const CBoundingBoxAligned& bound, SOverlayLine& overlayLine) { overlayLine.m_Coords.clear(); if (bound.IsEmpty()) return; const CVector3D& pMin = bound[0]; const CVector3D& pMax = bound[1]; // floor square overlayLine.PushCoords(pMin.X, pMin.Y, pMin.Z); overlayLine.PushCoords(pMax.X, pMin.Y, pMin.Z); overlayLine.PushCoords(pMax.X, pMin.Y, pMax.Z); overlayLine.PushCoords(pMin.X, pMin.Y, pMax.Z); overlayLine.PushCoords(pMin.X, pMin.Y, pMin.Z); // roof square overlayLine.PushCoords(pMin.X, pMax.Y, pMin.Z); overlayLine.PushCoords(pMax.X, pMax.Y, pMin.Z); overlayLine.PushCoords(pMax.X, pMax.Y, pMax.Z); overlayLine.PushCoords(pMin.X, pMax.Y, pMax.Z); overlayLine.PushCoords(pMin.X, pMax.Y, pMin.Z); } void SimRender::ConstructBoxOutline(const CBoundingBoxOriented& box, SOverlayLine& overlayLine) { overlayLine.m_Coords.clear(); if (box.IsEmpty()) return; CVector3D corners[8]; box.GetCorner(-1, -1, -1, corners[0]); box.GetCorner( 1, -1, -1, corners[1]); box.GetCorner( 1, -1, 1, corners[2]); box.GetCorner(-1, -1, 1, corners[3]); box.GetCorner(-1, 1, -1, corners[4]); box.GetCorner( 1, 1, -1, corners[5]); box.GetCorner( 1, 1, 1, corners[6]); box.GetCorner(-1, 1, 1, corners[7]); overlayLine.PushCoords(corners[0]); overlayLine.PushCoords(corners[1]); overlayLine.PushCoords(corners[2]); overlayLine.PushCoords(corners[3]); overlayLine.PushCoords(corners[0]); overlayLine.PushCoords(corners[4]); overlayLine.PushCoords(corners[5]); overlayLine.PushCoords(corners[6]); overlayLine.PushCoords(corners[7]); overlayLine.PushCoords(corners[4]); } void SimRender::ConstructGimbal(const CVector3D& center, float radius, SOverlayLine& out, size_t numSteps) { ENSURE(numSteps > 0 && numSteps % 4 == 0); // must be a positive multiple of 4 out.m_Coords.clear(); size_t fullCircleSteps = numSteps; const float angleIncrement = 2.f*M_PI/fullCircleSteps; const CVector3D X_UNIT(1, 0, 0); const CVector3D Y_UNIT(0, 1, 0); const CVector3D Z_UNIT(0, 0, 1); CVector3D rotationVector(0, 0, radius); // directional vector based in the center that we will be rotating to get the gimbal points // first draw a quarter of XZ gimbal; then complete the XY gimbal; then continue the XZ gimbal and finally add the YZ gimbal // (that way we can keep a single continuous line) // -- XZ GIMBAL (PART 1/2) ----------------------------------------------- CQuaternion xzRotation; xzRotation.FromAxisAngle(Y_UNIT, angleIncrement); for (size_t i = 0; i < fullCircleSteps/4; ++i) // complete only a quarter of the way { out.PushCoords(center + rotationVector); rotationVector = xzRotation.Rotate(rotationVector); } // -- XY GIMBAL ---------------------------------------------------------- // now complete the XY gimbal while the XZ gimbal is interrupted CQuaternion xyRotation; xyRotation.FromAxisAngle(Z_UNIT, angleIncrement); for (size_t i = 0; i < fullCircleSteps; ++i) // note the <; the last point of the XY gimbal isn't added, because the XZ gimbal will add it { out.PushCoords(center + rotationVector); rotationVector = xyRotation.Rotate(rotationVector); } // -- XZ GIMBAL (PART 2/2) ----------------------------------------------- // resume the XZ gimbal to completion for (size_t i = fullCircleSteps/4; i < fullCircleSteps; ++i) // exclude the last point of the circle so the YZ gimbal can add it { out.PushCoords(center + rotationVector); rotationVector = xzRotation.Rotate(rotationVector); } // -- YZ GIMBAL ---------------------------------------------------------- CQuaternion yzRotation; yzRotation.FromAxisAngle(X_UNIT, angleIncrement); for (size_t i = 0; i <= fullCircleSteps; ++i) { out.PushCoords(center + rotationVector); rotationVector = yzRotation.Rotate(rotationVector); } } void SimRender::ConstructAxesMarker(const CMatrix3D& coordSystem, SOverlayLine& outX, SOverlayLine& outY, SOverlayLine& outZ) { outX.m_Coords.clear(); outY.m_Coords.clear(); outZ.m_Coords.clear(); outX.m_Color = CColor(1, 0, 0, .5f); // X axis; red outY.m_Color = CColor(0, 1, 0, .5f); // Y axis; green outZ.m_Color = CColor(0, 0, 1, .5f); // Z axis; blue outX.m_Thickness = 2; outY.m_Thickness = 2; outZ.m_Thickness = 2; CVector3D origin = coordSystem.GetTranslation(); outX.PushCoords(origin); outY.PushCoords(origin); outZ.PushCoords(origin); outX.PushCoords(origin + CVector3D(coordSystem(0,0), coordSystem(1,0), coordSystem(2,0))); outY.PushCoords(origin + CVector3D(coordSystem(0,1), coordSystem(1,1), coordSystem(2,1))); outZ.PushCoords(origin + CVector3D(coordSystem(0,2), coordSystem(1,2), coordSystem(2,2))); } void SimRender::SmoothPointsAverage(std::vector& points, bool closed) { PROFILE("SmoothPointsAverage"); size_t n = points.size(); if (n < 2) return; // avoid out-of-bounds array accesses, and leave the points unchanged std::vector newPoints; newPoints.resize(points.size()); // Handle the end points appropriately if (closed) { newPoints[0] = (points[n-1] + points[0] + points[1]) / 3.f; newPoints[n-1] = (points[n-2] + points[n-1] + points[0]) / 3.f; } else { newPoints[0] = points[0]; newPoints[n-1] = points[n-1]; } // Average all the intermediate points for (size_t i = 1; i < n-1; ++i) newPoints[i] = (points[i-1] + points[i] + points[i+1]) / 3.f; points.swap(newPoints); } static CVector2D EvaluateSpline(float t, CVector2D a0, CVector2D a1, CVector2D a2, CVector2D a3, float offset) { // Compute position on spline CVector2D p = a0*(t*t*t) + a1*(t*t) + a2*t + a3; // Compute unit-vector direction of spline CVector2D dp = (a0*(3*t*t) + a1*(2*t) + a2).Normalized(); // Offset position perpendicularly return p + CVector2D(dp.Y*-offset, dp.X*offset); } void SimRender::InterpolatePointsRNS(std::vector& points, bool closed, float offset, int segmentSamples /* = 4 */) { PROFILE("InterpolatePointsRNS"); ENSURE(segmentSamples > 0); std::vector newPoints; // (This does some redundant computations for adjacent vertices, // but it's fairly fast (<1ms typically) so we don't worry about it yet) // TODO: Instead of doing a fixed number of line segments between each // control point, it should probably be somewhat adaptive to get a nicer // curve with fewer points size_t n = points.size(); if (closed) { if (n < 1) return; // we need at least a single point to not crash } else { if (n < 2) return; // in non-closed mode, we need at least n=2 to not crash } size_t imax = closed ? n : n-1; newPoints.reserve(imax*segmentSamples); // these are primarily used inside the loop, but for open paths we need them outside the loop once to compute the last point CVector2D a0; CVector2D a1; CVector2D a2; CVector2D a3; for (size_t i = 0; i < imax; ++i) { // Get the relevant points for this spline segment; each step interpolates the segment between p1 and p2; p0 and p3 are the points // before p1 and after p2, respectively; they're needed to compute tangents and whatnot. CVector2D p0; // normally points[(i-1+n)%n], but it's a bit more complicated due to open/closed paths -- see below CVector2D p1 = points[i]; CVector2D p2 = points[(i+1)%n]; CVector2D p3; // normally points[(i+2)%n], but it's a bit more complicated due to open/closed paths -- see below if (!closed && (i == 0)) // p0's point index is out of bounds, and we can't wrap around because we're in non-closed mode -- create an artificial point // that extends p1 -> p0 (i.e. the first segment's direction) p0 = points[0] + (points[0] - points[1]); else // standard wrap-around case p0 = points[(i-1+n)%n]; // careful; don't use (i-1)%n here, as the result is machine-dependent for negative operands (e.g. if i==0, the result could be either -1 or n-1) if (!closed && (i == n-2)) // p3's point index is out of bounds; create an artificial point that extends p_(n-2) -> p_(n-1) (i.e. the last segment's direction) // (note that p2's index should not be out of bounds, because in non-closed mode imax is reduced by 1) p3 = points[n-1] + (points[n-1] - points[n-2]); else // standard wrap-around case p3 = points[(i+2)%n]; // Do the RNS computation (based on GPG4 "Nonuniform Splines") float l1 = (p2 - p1).Length(); // length of spline segment (i)..(i+1) CVector2D s0 = (p1 - p0).Normalized(); // unit vector of spline segment (i-1)..(i) CVector2D s1 = (p2 - p1).Normalized(); // unit vector of spline segment (i)..(i+1) CVector2D s2 = (p3 - p2).Normalized(); // unit vector of spline segment (i+1)..(i+2) CVector2D v1 = (s0 + s1).Normalized() * l1; // spline velocity at i CVector2D v2 = (s1 + s2).Normalized() * l1; // spline velocity at i+1 // Compute standard cubic spline parameters a0 = p1*2 + p2*-2 + v1 + v2; a1 = p1*-3 + p2*3 + v1*-2 + v2*-1; a2 = v1; a3 = p1; // Interpolate at regular points across the interval for (int sample = 0; sample < segmentSamples; sample++) newPoints.push_back(EvaluateSpline(sample/((float) segmentSamples), a0, a1, a2, a3, offset)); } if (!closed) // if the path is open, we should take care to include the last control point // NOTE: we can't just do push_back(points[n-1]) here because that ignores the offset newPoints.push_back(EvaluateSpline(1.f, a0, a1, a2, a3, offset)); points.swap(newPoints); } void SimRender::ConstructDashedLine(const std::vector& keyPoints, SDashedLine& dashedLineOut, const float dashLength, const float blankLength) { // sanity checks if (dashLength <= 0) return; if (blankLength <= 0) return; if (keyPoints.size() < 2) return; dashedLineOut.m_Points.clear(); dashedLineOut.m_StartIndices.clear(); // walk the line, counting the total length so far at each node point. When the length exceeds dashLength, cut the last segment at the // required length and continue for blankLength along the line to start a new dash segment. // TODO: we should probably extend this function to also allow for closed lines. I was thinking of slightly scaling the dash/blank length // so that it fits the length of the curve, but that requires knowing the length of the curve upfront which is sort of expensive to compute // (O(n) and lots of square roots). bool buildingDash = true; // true if we're building a dash, false if a blank float curDashLength = 0; // builds up the current dash/blank's length as we walk through the line nodes CVector2D dashLastPoint = keyPoints[0]; // last point of the current dash/blank being built. // register the first starting node of the first dash dashedLineOut.m_Points.push_back(keyPoints[0]); dashedLineOut.m_StartIndices.push_back(0); // index of the next key point on the path. Must always point to a node that is further along the path than dashLastPoint, so we can // properly take a direction vector along the path. size_t i = 0; while(i < keyPoints.size() - 1) { // get length of this segment CVector2D segmentVector = keyPoints[i + 1] - dashLastPoint; // vector from our current point along the path to nextNode float segmentLength = segmentVector.Length(); float targetLength = (buildingDash ? dashLength : blankLength); if (curDashLength + segmentLength > targetLength) { // segment is longer than the dash length we still have to go, so we'll need to cut it; create a cut point along the segment // line that is of just the required length to complete the dash, then make it the base point for the next dash/blank. float cutLength = targetLength - curDashLength; CVector2D cutPoint = dashLastPoint + (segmentVector.Normalized() * cutLength); // start a new dash or blank in the next iteration curDashLength = 0; buildingDash = !buildingDash; // flip from dash to blank and vice-versa dashLastPoint = cutPoint; // don't increment i, we haven't fully traversed this segment yet so we still need to use the same point to take the // direction vector with in the next iteration // this cut point is either the end of the current dash or the beginning of a new dash; either way, we're gonna need it // in the points array. dashedLineOut.m_Points.push_back(cutPoint); if (buildingDash) { // if we're gonna be building a new dash, then cutPoint is now the base point of that new dash, so let's register its // index as a start index of a dash. dashedLineOut.m_StartIndices.push_back(dashedLineOut.m_Points.size() - 1); } } else { // the segment from lastDashPoint to keyPoints[i+1] doesn't suffice to complete the dash, so we need to add keyPoints[i+1] // to this dash's points and continue from there if (buildingDash) // still building the dash, add it to the output (we don't need to store the blanks) dashedLineOut.m_Points.push_back(keyPoints[i+1]); curDashLength += segmentLength; dashLastPoint = keyPoints[i+1]; i++; } } } // TODO: this serves a similar purpose to SplitLine above, but is more general. Also, SplitLine seems to be implemented more // efficiently, might be nice to take some cues from it void SimRender::SubdividePoints(std::vector& points, float maxSegmentLength, bool closed) { size_t numControlPoints = points.size(); if (numControlPoints < 2) return; ENSURE(maxSegmentLength > 0); size_t endIndex = numControlPoints; if (!closed && numControlPoints > 2) endIndex--; std::vector newPoints; for (size_t i = 0; i < endIndex; i++) { const CVector2D& curPoint = points[i]; const CVector2D& nextPoint = points[(i+1) % numControlPoints]; const CVector2D line(nextPoint - curPoint); CVector2D lineDirection = line.Normalized(); // include control point i + a list of intermediate points between i and i + 1 (excluding i+1 itself) newPoints.push_back(curPoint); // calculate how many intermediate points are needed so that each segment is of length <= maxSegmentLength float lineLength = line.Length(); size_t numSegments = (size_t) ceilf(lineLength / maxSegmentLength); float segmentLength = lineLength / numSegments; for (size_t s = 1; s < numSegments; ++s) // start at one, we already included curPoint { newPoints.push_back(curPoint + lineDirection * (s * segmentLength)); } } points.swap(newPoints); } + +void SimRender::ConstructTexturedLineBox(SOverlayTexturedLine& overlay, const CVector2D& origin, + const CFixedVector3D& rotation, const float sizeX, const float sizeZ) +{ + float s = sinf(-rotation.Y.ToFloat()); + float c = cosf(-rotation.Y.ToFloat()); + + CVector2D unitX(c, s); + CVector2D unitZ(-s, c); + + // Add half the line thickness to the radius so that we get an 'outside' stroke of the footprint shape + const float halfSizeX = sizeX / 2.f + overlay.m_Thickness / 2.f; + const float halfSizeZ = sizeZ / 2.f + overlay.m_Thickness / 2.f; + + std::vector points; + points.push_back(CVector2D(origin + unitX * halfSizeX + unitZ * (-halfSizeZ))); + points.push_back(CVector2D(origin + unitX * (-halfSizeX) + unitZ * (-halfSizeZ))); + points.push_back(CVector2D(origin + unitX * (-halfSizeX) + unitZ * halfSizeZ)); + points.push_back(CVector2D(origin + unitX * halfSizeX + unitZ * halfSizeZ)); + + SimRender::SubdividePoints(points, TERRAIN_TILE_SIZE / 3.f, overlay.m_Closed); + overlay.PushCoords(points); +} + +void SimRender::ConstructTexturedLineCircle(SOverlayTexturedLine& overlay, const CVector2D& origin, const float overlay_radius) +{ + const float radius = overlay_radius + overlay.m_Thickness / 3.f; + + size_t numSteps = ceilf(float(2 * M_PI) * radius / (TERRAIN_TILE_SIZE / 3.f)); + for (size_t i = 0; i < numSteps; ++i) + { + float angle = i * float(2 * M_PI) / numSteps; + float px = origin.X + radius * sinf(angle); + float pz = origin.Y + radius * cosf(angle); + + overlay.PushCoords(px, pz); + } +} Index: ps/trunk/source/simulation2/helpers/Render.h =================================================================== --- ps/trunk/source/simulation2/helpers/Render.h (revision 20620) +++ ps/trunk/source/simulation2/helpers/Render.h (revision 20621) @@ -1,195 +1,201 @@ /* Copyright (C) 2017 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #ifndef INCLUDED_HELPER_RENDER #define INCLUDED_HELPER_RENDER -/** - * @file - * Helper functions related to rendering - */ - -#include "maths/Vector2D.h" - class CSimContext; class CVector2D; class CVector3D; +class CFixedVector3D; class CMatrix3D; class CBoundingBoxAligned; class CBoundingBoxOriented; + struct SOverlayLine; +struct SOverlayTexturedLine; struct SDashedLine { /// Packed array of consecutive dashes' points. Use m_StartIndices to navigate it. std::vector m_Points; /** * Start indices in m_Points of each dash. Dash n starts at point m_StartIndices[n] and ends at the point with index * m_StartIndices[n+1] - 1, or at the end of the m_Points vector. Use the GetEndIndex(n) convenience method to abstract away the * difference and get the (exclusive) end index of dash n. */ std::vector m_StartIndices; /// Returns the (exclusive) end point index (i.e. index within m_Points) of dash n. size_t GetEndIndex(size_t i) { // for the last dash, there is no next starting index, so we need to use the end index of the m_Points array instead return (i < m_StartIndices.size() - 1 ? m_StartIndices[i+1] : m_Points.size()); } }; namespace SimRender { /** * Constructs overlay line from given points, conforming to terrain. * * @param[in] xz List of x,z coordinate pairs representing the line. * @param[in,out] overlay Updated overlay line now conforming to terrain. * @param[in] floating If true, the line conforms to water as well. * @param[in] heightOffset Height above terrain to offset the line. */ void ConstructLineOnGround( const CSimContext& context, const std::vector& xz, SOverlayLine& overlay, bool floating, float heightOffset = 0.25f); /** * Constructs overlay line as a circle with given center and radius, conforming to terrain. * * @param[in] x,z Coordinates of center of circle. * @param[in] radius Radius of circle to construct. * @param[in,out] overlay Updated overlay line representing this circle. * @param[in] floating If true, the circle conforms to water as well. * @param[in] heightOffset Height above terrain to offset the circle. * @param heightOffset The vertical offset to apply to points, to raise the line off the terrain a bit. */ void ConstructCircleOnGround( const CSimContext& context, float x, float z, float radius, SOverlayLine& overlay, bool floating, float heightOffset = 0.25f); /** * Constructs overlay line as an outlined circle sector (an arc with straight lines between the * endpoints and the circle's center), conforming to terrain. */ void ConstructClosedArcOnGround( const CSimContext& context, float x, float z, float radius, float start, float end, SOverlayLine& overlay, bool floating, float heightOffset = 0.25f); /** * Constructs overlay line as rectangle with given center and dimensions, conforming to terrain. * * @param[in] x,z Coordinates of center of rectangle. * @param[in] w,h Width/height dimensions of the rectangle. * @param[in] a Clockwise angle to orient the rectangle. * @param[in,out] overlay Updated overlay line representing this rectangle. * @param[in] floating If true, the rectangle conforms to water as well. * @param[in] heightOffset Height above terrain to offset the rectangle. */ void ConstructSquareOnGround( const CSimContext& context, float x, float z, float w, float h, float a, SOverlayLine& overlay, bool floating, float heightOffset = 0.25f); /** * Constructs a solid outline of an arbitrarily-aligned bounding @p box. * * @param[in] box * @param[in,out] overlayLine Updated overlay line representing the oriented box. */ void ConstructBoxOutline(const CBoundingBoxOriented& box, SOverlayLine& overlayLine); /** * Constructs a solid outline of an axis-aligned bounding @p box. * * @param[in] bound * @param[in,out] overlayLine Updated overlay line representing the AABB. */ void ConstructBoxOutline(const CBoundingBoxAligned& box, SOverlayLine& overlayLine); /** * Constructs a simple gimbal outline with the given radius and center. * * @param[in] center * @param[in] radius * @param[in,out] out Updated overlay line representing the gimbal. * @param[in] numSteps The amount of steps to trace a circle's complete outline. Must be a (strictly) positive multiple of four. * For small radii, you can get away with small values; setting this to 4 will create a diamond shape. */ void ConstructGimbal(const CVector3D& center, float radius, SOverlayLine& out, size_t numSteps = 16); /** * Constructs 3D axis marker overlay lines for the given coordinate system. * The XYZ axes are colored RGB, respectively. * * @param[in] coordSystem Specifies the coordinate system. * @param[out] outX,outY,outZ Constructed overlay lines for each axes. */ void ConstructAxesMarker(const CMatrix3D& coordSystem, SOverlayLine& outX, SOverlayLine& outY, SOverlayLine& outZ); /** * Updates the given points so each point is averaged with its neighbours, resulting in * a somewhat smoother curve, assuming the points are roughly equally spaced. * * @param[in,out] points List of points to smooth. * @param[in] closed if true, then the points are treated as a closed path (the last is connected * to the first). */ void SmoothPointsAverage(std::vector& points, bool closed); /** * Updates the given points to include intermediate points interpolating between the original * control points, using a rounded nonuniform spline. * * @param[in,out] points List of points to interpolate. * @param[in] closed if true, then the points are treated as a closed path (the last is connected * to the first). * @param[in] offset The points are shifted by this distance in a direction 90 degrees clockwise from * the direction of the curve. * @param[in] segmentSamples Amount of intermediate points to sample between every two control points. */ void InterpolatePointsRNS(std::vector& points, bool closed, float offset, int segmentSamples = 4); /** * Creates a dashed line from the given line, dash length, and blank space between. * * @param[in] linePoints List of points specifying the input line. * @param[out] dashedLineOut The dashed line returned as a list of smaller lines * @param[in] dashLength Length of a single dash. Must be strictly positive. * @param[in] blankLength Length of a single blank between dashes. Must be strictly positive. */ void ConstructDashedLine(const std::vector& linePoints, SDashedLine& dashedLineOut, const float dashLength, const float blankLength); /** * Subdivides a list of @p points into segments of maximum length @p maxSegmentLength that are of equal size between every two * control points. The resulting subdivided list of points is written back to @p points. * * @param points The list of intermediate points to subdivide. * @param maxSegmentLength The maximum length of a single segment after subdivision. Must be strictly positive. * @param closed Should the provided list of points be treated as a closed shape? If true, the resulting list of points will include * extra subdivided points between the last and the first point. */ void SubdividePoints(std::vector& points, float maxSegmentLength, bool closed); +/** + * Sets the coordinates of a rectangular textured overlay, for example used by selection rings of structures. + */ +void ConstructTexturedLineBox(SOverlayTexturedLine& overlay, const CVector2D& origin, const CFixedVector3D& rotation, const float sizeX, const float sizeZ); + +/** + * Sets the coordinates of a circular textured overlay, for example by selection rings of units or attack range visualization. + */ +void ConstructTexturedLineCircle(SOverlayTexturedLine& overlay, const CVector2D& origin, const float overlay_radius); + } // namespace #endif // INCLUDED_HELPER_RENDER