diff --git a/include/polyscope/context.h b/include/polyscope/context.h index 9a339bf2..f63f60cf 100644 --- a/include/polyscope/context.h +++ b/include/polyscope/context.h @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -101,6 +102,11 @@ struct Context { glm::vec3 flightTargetViewT, flightInitialViewT; float flightTargetFov, flightInitialFov; + // Viewports + std::vector viewportParameters; + int activeViewportIndex = -1; + bool viewportsShareNavigation = true; + // ====================================================== // === Picking globals from pick.h / pick.cpp // ====================================================== diff --git a/include/polyscope/internal.h b/include/polyscope/internal.h index 435e5602..1e5cdbca 100644 --- a/include/polyscope/internal.h +++ b/include/polyscope/internal.h @@ -49,7 +49,6 @@ extern float rightWindowsWidth; // Cached versions of lazy properties used for updates namespace lazy { extern TransparencyMode transparencyMode; -extern ProjectionMode projectionMode; extern int transparencyRenderPasses; extern int ssaaFactor; extern float uiScale; diff --git a/include/polyscope/persistent_value.h b/include/polyscope/persistent_value.h index 6a07831c..5ffdcd06 100644 --- a/include/polyscope/persistent_value.h +++ b/include/polyscope/persistent_value.h @@ -132,6 +132,7 @@ class PersistentValue { namespace detail { extern PersistentCache persistentCache_int32_t; +extern PersistentCache persistentCache_uint64_t; extern PersistentCache persistentCache_double; extern PersistentCache persistentCache_float; extern PersistentCache persistentCache_bool; @@ -151,6 +152,7 @@ extern PersistentCache persistentCache_MeshSelectionMode; extern PersistentCache persistentCache_SparseVolumeGridRenderMode; template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_int32_t; } +template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_uint64_t; } template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_double; } template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_float; } template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_bool; } diff --git a/include/polyscope/pick.h b/include/polyscope/pick.h index 72d4ff99..299fe3c7 100644 --- a/include/polyscope/pick.h +++ b/include/polyscope/pick.h @@ -33,8 +33,22 @@ struct PickResult { std::string structureType = ""; std::string structureName = ""; std::string quantityName = ""; + + // Where the pick was evaluated, in two coordinate frames. See the notes in view.h on screen coords vs. buffer inds. + // + // `screenCoords` and `bufferInds` are GLOBAL: they are positions in the whole window, regardless of viewport. + // When using a single viewport, these are all you need. glm::vec2 screenCoords; glm::ivec2 bufferInds; + // + // The `viewport*` members are LOCAL to the viewport that the pick landed in, which is `viewportInd`: the origin is + // the top-left of that viewport. These are the coordinates to use with pickViewportAtScreenCoords() and + // pickViewportAtBufferInds(), so that pickViewportAtBufferInds(r.viewportBufferInds, r.viewportInd) round-trips. + // With a single viewport (viewportInd == 0, covering the whole window), these equal the global values above. + int32_t viewportInd = 0; + glm::vec2 viewportScreenCoords; + glm::ivec2 viewportBufferInds; + glm::vec3 position; float depth; uint64_t localIndex = INVALID_IND_64; @@ -42,9 +56,15 @@ struct PickResult { // Query functions to evaluate a pick. // Internally, these do a render pass to populate relevant information, then query the resulting buffers. +// If using viewports, these assume inputs are GLOBAL coordinates on the whole window, and internally route to the +// appropriate viewport. PickResult pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinates PickResult pickAtBufferInds(glm::ivec2 bufferInds); // takes indices into render buffer +// Viewport-explicit pick variants: coordinates are LOCAL to the given viewport (origin at viewport top-left). +// Pass viewportInd=-1 to use the current active viewport. +PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd = -1); +PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd = -1); // == Stateful picking: track and update a current selection @@ -61,11 +81,17 @@ namespace pick { // Old, deprecated picking API. Use the above functions instead. // Get the structure which was clicked on (nullptr if none), and the pick ID in local indices for that structure (such // that 0 is the first index as returned from requestPickBufferRange()) -std::pair pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinates -std::pair pickAtBufferCoords(int xPos, int yPos); // takes indices into the buffer -std::pair evaluatePickQuery(int xPos, int yPos); // old, badly named. takes buffer coordinates. -std::tuple evaluatePickQueryFull(int xPos, - int yPos); // badly named. takes buffer coordinates. +// +// When using multiple viewports, the coordinates are LOCAL to the viewport iView, where iView<0 means the active +// viewport, as with other viewport-aware functions. With a single viewport, these all behave as they always did. To +// pick using global window coordinates and have the viewport found automatically, use the functions above. +std::pair pickAtScreenCoords(glm::vec2 screenCoords, + int32_t iView = -1); // takes screen coordinates +std::pair pickAtBufferCoords(int xPos, int yPos, + int32_t iView = -1); // takes indices into the buffer +std::pair evaluatePickQuery(int xPos, int yPos, int32_t iView = -1); +std::tuple +evaluatePickQueryFull(int xPos, int yPos, int32_t iView = -1); // badly named. takes buffer coordinates. // == Helpers diff --git a/include/polyscope/render/engine.h b/include/polyscope/render/engine.h index de20d714..7dbf3282 100644 --- a/include/polyscope/render/engine.h +++ b/include/polyscope/render/engine.h @@ -19,8 +19,9 @@ namespace polyscope { // Forward declarations for ManagedBuffer integration namespace render { - class ManagedBufferBase; - template class ManagedBuffer; +class ManagedBufferBase; +template +class ManagedBuffer; } // namespace render // == A few enums that control behavior @@ -262,7 +263,7 @@ class RenderBuffer { public: // abstract class: use the factory methods from the Engine class RenderBuffer(RenderBufferType type_, unsigned int sizeX_, unsigned int sizeY_); - virtual ~RenderBuffer() {}; + virtual ~RenderBuffer(){}; virtual void resize(unsigned int newX, unsigned int newY); @@ -283,7 +284,7 @@ class FrameBuffer { public: // abstract class: use the factory methods from the Engine class FrameBuffer(); - virtual ~FrameBuffer() {}; + virtual ~FrameBuffer(){}; virtual void bind() = 0; // Bind to this framebuffer so subsequent draw calls will go to it @@ -319,7 +320,7 @@ class FrameBuffer { // Query pixel virtual std::array readFloat4(int xPos, int yPos) = 0; virtual float readDepth(int xPos, int yPos) = 0; - virtual void blitTo(FrameBuffer* other) = 0; + virtual void blitTo(FrameBuffer* other, int targetPosX = 0, int targetPosY = 0) = 0; virtual std::vector readBuffer() = 0; virtual uint32_t getNativeBufferID() = 0; @@ -402,7 +403,7 @@ class ShaderProgram { public: ShaderProgram(DrawMode dm); - virtual ~ShaderProgram() {}; + virtual ~ShaderProgram(){}; // === Store data @@ -455,23 +456,30 @@ class ShaderProgram { bool withAlpha = true, bool useMipMap = false, bool repeat = false) = 0; virtual void setTextureFromColormap(std::string name, const std::string& colorMap, bool allowUpdate = false) = 0; // TODO make this one take a shared pointer and have the same semantics as the attribute version - virtual void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, ManagedBufferBase* source = nullptr) = 0; - // Bind an AttributeBuffer (VBO) as a buffer texture (samplerBuffer / GL_TEXTURE_BUFFER, ShaderTextureType::TextureBuffer). - // Note: the buffer is always exposed to shaders as a flattened 1-component scalar stream (GL_R32F / GL_R32I / GL_R32UI), - // even for vector/matrix types (e.g., fetch a vec3 at index i via texelFetch at 3*i + {0, 1, 2}). This is done because - // OpenGL 3.3 core does not support 3-component buffer texture formats (GL_RGB32F requires GL 4.0). + virtual void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, + ManagedBufferBase* source = nullptr) = 0; + // Bind an AttributeBuffer (VBO) as a buffer texture (samplerBuffer / GL_TEXTURE_BUFFER, + // ShaderTextureType::TextureBuffer). Note: the buffer is always exposed to shaders as a flattened 1-component scalar + // stream (GL_R32F / GL_R32I / GL_R32UI), even for vector/matrix types (e.g., fetch a vec3 at index i via texelFetch + // at 3*i + {0, 1, 2}). This is done because OpenGL 3.3 core does not support 3-component buffer texture formats + // (GL_RGB32F requires GL 4.0). virtual void setTextureFromAttributeBuffer(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source = nullptr) = 0; // Convenience overloads for ManagedBuffer — set the buffer AND record the source for lazy sync. // Defined in managed_buffer.h after ManagedBuffer is fully declared. - template void setAttribute(std::string name, ManagedBuffer& buf); + template + void setAttribute(std::string name, ManagedBuffer& buf); // Binds a texture-backed ManagedBuffer (DeviceBufferType::Texture1d/2d/3d) to a sampler1D/2D/3D. - template void setTextureFromBuffer(std::string name, ManagedBuffer& buf); - // Binds an attribute-backed ManagedBuffer (DeviceBufferType::Attribute) as a buffer texture (samplerBuffer / TextureBuffer). - template void setTextureFromAttributeBuffer(std::string name, ManagedBuffer& buf); - template void setIndex(ManagedBuffer& buf); + template + void setTextureFromBuffer(std::string name, ManagedBuffer& buf); + // Binds an attribute-backed ManagedBuffer (DeviceBufferType::Attribute) as a buffer texture (samplerBuffer / + // TextureBuffer). + template + void setTextureFromAttributeBuffer(std::string name, ManagedBuffer& buf); + template + void setIndex(ManagedBuffer& buf); // Indices virtual void setIndex(std::shared_ptr externalBuffer) = 0; @@ -545,8 +553,7 @@ class Engine { virtual void clearSceneBuffer(); virtual bool bindSceneBuffer(); - virtual void resizeScreenBuffers(); // applies to all buffers tied to display size - virtual void setScreenBufferViewports(); + virtual void resizeScreenBuffersAndSetViewports(); // applies to all buffers tied to display size virtual void applyLightingTransform(std::shared_ptr& texture); // tonemap and gamma correct, render to active buffer void updateMinDepthTexture(); @@ -650,18 +657,25 @@ class Engine { // === The frame buffers used in the rendering pipeline // The size of these buffers is always kept in sync with the screen size std::shared_ptr displayBuffer, displayBufferAlt; - std::shared_ptr sceneBuffer, sceneBufferFinal; + std::shared_ptr sceneBuffer, sceneBufferFinal; // TODO rename the 'final' one + std::vector> sceneBufferTargets; std::shared_ptr pickFramebuffer; - std::shared_ptr sceneDepthMinFrame; + std::shared_ptr sceneDepthMinFrame; // per-viewport; set by setActiveSceneTarget + std::vector> sceneDepthMinFrameTargets; FrameBuffer& getDisplayBuffer(); - // Main buffers for rendering - // sceneDepthMin is an optional texture copy of the depth buffe used for some effects - std::shared_ptr sceneColor, sceneColorFinal, sceneDepth, sceneDepthMin; + // Main buffers for rendering. + // sceneColor, sceneDepth, sceneDepthMin, and their corresponding framebuffers are per-viewport; + // the active viewport's versions are exposed as the non-vector members, set by setActiveSceneTarget. + // sceneColorFinal holds the composited result and remains a single texture. + std::shared_ptr sceneColorFinal; + std::shared_ptr sceneColor, sceneDepth, sceneDepthMin; + std::vector> sceneColorTargets, sceneDepthTargets, sceneDepthMinTargets; std::shared_ptr pickColorBuffer, pickDepthBuffer; TextureBuffer& getFinalSceneColorTexture(); // General-use programs used by the engine + // TODO some of these seem to be unused; remove them std::shared_ptr renderTexturePlain, renderTextureDot3, renderTextureMap3, renderTextureSphereBG; std::shared_ptr compositePeel, mapLight, copyDepth; @@ -676,6 +690,10 @@ class Engine { virtual void setFrontFaceCCW(bool newVal) = 0; // true if CCW triangles are considered front-facing; false otherwise bool getFrontFaceCCW(); + // A few viewport related helpers + void setActiveSceneTarget(int activeSceneTargets); + void ensureSceneTargetsAllocated(int sceneTargetsCount); + // == Options BackgroundView background = BackgroundView::None; diff --git a/include/polyscope/render/mock_opengl/mock_gl_engine.h b/include/polyscope/render/mock_opengl/mock_gl_engine.h index 58b545a4..a6458ac5 100644 --- a/include/polyscope/render/mock_opengl/mock_gl_engine.h +++ b/include/polyscope/render/mock_opengl/mock_gl_engine.h @@ -224,7 +224,7 @@ class GLFrameBuffer : public FrameBuffer { std::vector readBuffer() override; std::array readFloat4(int xPos, int yPos) override; float readDepth(int xPos, int yPos) override; - void blitTo(FrameBuffer* other) override; + void blitTo(FrameBuffer* other, int targetPosX = 0, int targetPosY = 0) override; // Getters uint32_t getNativeBufferID() override; @@ -244,7 +244,8 @@ struct GLShaderAttribute { RenderDataType type; int arrayCount; std::shared_ptr buff; // the buffer that we will actually use - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source }; struct GLShaderTexture { @@ -252,9 +253,11 @@ struct GLShaderTexture { ShaderTextureType type; uint32_t index; bool isSet; - GLTextureBuffer* textureBuffer; // NOTE: very confusing name, unrelated to the OpenGL "TextureBuffer" concept as used below + GLTextureBuffer* + textureBuffer; // NOTE: very confusing name, unrelated to the OpenGL "TextureBuffer" concept as used below std::shared_ptr textureBufferOwned; // might be empty, if texture isn't owned - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source // used only for ShaderTextureType::TextureBuffer std::shared_ptr attrBuffer; @@ -347,7 +350,8 @@ class GLShaderProgram : public ShaderProgram { void setTexture2D(std::string name, unsigned char* texData, unsigned int width, unsigned int height, bool withAlpha = true, bool useMipMap = false, bool repeat = false) override; void setTextureFromColormap(std::string name, const std::string& colorMap, bool allowUpdate = false) override; - void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, ManagedBufferBase* source = nullptr) override; + void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, + ManagedBufferBase* source = nullptr) override; void setTextureFromAttributeBuffer(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source = nullptr) override; diff --git a/include/polyscope/render/opengl/gl_engine.h b/include/polyscope/render/opengl/gl_engine.h index 2ac6b46d..f98d25ba 100644 --- a/include/polyscope/render/opengl/gl_engine.h +++ b/include/polyscope/render/opengl/gl_engine.h @@ -140,8 +140,8 @@ class GLAttributeBuffer : public AttributeBuffer { }; class GLTextureBuffer : public TextureBuffer { -// NOTE: very confusing name, this is unrelated to the openGL "TextureBuffer" concept as used in ShaderTextureType::TextureBuffer -// this is just a texture that happens to hold buffer data + // NOTE: very confusing name, this is unrelated to the openGL "TextureBuffer" concept as used in + // ShaderTextureType::TextureBuffer this is just a texture that happens to hold buffer data public: // create a 1D texture from data @@ -264,7 +264,7 @@ class GLFrameBuffer : public FrameBuffer { std::vector readBuffer() override; std::array readFloat4(int xPos, int yPos) override; float readDepth(int xPos, int yPos) override; - void blitTo(FrameBuffer* other) override; + void blitTo(FrameBuffer* other, int targetPosX = 0, int targetPosY = 0) override; // Getters FrameBufferHandle getHandle() const { return handle; } @@ -287,7 +287,8 @@ struct GLShaderAttribute { int arrayCount; AttributeLocation location; // -1 means "no location", usually because it was optimized out std::shared_ptr buff; // the buffer that we will actually use - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source }; struct GLShaderTexture { @@ -295,10 +296,12 @@ struct GLShaderTexture { ShaderTextureType type; uint32_t index; bool isSet; - GLTextureBuffer* textureBuffer; // NOTE: very confusing name, unrelated to the openGL "TextureBuffer" concept as used below + GLTextureBuffer* + textureBuffer; // NOTE: very confusing name, unrelated to the openGL "TextureBuffer" concept as used below std::shared_ptr textureBufferOwned; // might be empty, if texture isn't owned TextureLocation location; // -1 means "no location", usually because it was optimized out - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source // these are used only for ShaderTextureType::TextureBuffer std::shared_ptr attrBuffer; @@ -397,7 +400,8 @@ class GLShaderProgram : public ShaderProgram { void setTexture2D(std::string name, unsigned char* texData, unsigned int width, unsigned int height, bool withAlpha = true, bool useMipMap = false, bool repeat = false) override; void setTextureFromColormap(std::string name, const std::string& colorMap, bool allowUpdate = false) override; - void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, ManagedBufferBase* source = nullptr) override; + void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, + ManagedBufferBase* source = nullptr) override; void setTextureFromAttributeBuffer(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source = nullptr) override; diff --git a/include/polyscope/render/opengl/shaders/rules.h b/include/polyscope/render/opengl/shaders/rules.h index 78979786..c2c20506 100644 --- a/include/polyscope/render/opengl/shaders/rules.h +++ b/include/polyscope/render/opengl/shaders/rules.h @@ -40,8 +40,7 @@ extern const ShaderReplacementRule PROJ_AND_INV_PROJ_MAT; extern const ShaderReplacementRule COMPUTE_SHADE_NORMAL_FROM_POSITION; extern const ShaderReplacementRule PREMULTIPLY_LIT_COLOR; extern const ShaderReplacementRule CULL_POS_FROM_VIEW; -extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE; -extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC; +extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_DYNAMIC; ShaderReplacementRule generateSlicePlaneRule(std::string uniquePostfix); ShaderReplacementRule generateVolumeGridSlicePlaneRule(std::string uniquePostfix); diff --git a/include/polyscope/structure.h b/include/polyscope/structure.h index 475151a8..54ba12c4 100644 --- a/include/polyscope/structure.h +++ b/include/polyscope/structure.h @@ -133,6 +133,14 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer void addToGroup(std::string groupName); void addToGroup(Group& group); + // Viewport visibility + // If true, the structure (and any of its quantities) are visible on the i'th viewport + void setViewportVisibility(int32_t viewportInd, bool assigned); + void setViewportVisibilityAll(bool assigned); // set visibility true/false for all viewports + void setViewportVisibilityExclusive(int32_t viewportInd); // only visible in the i'th viewport + bool getViewportVisibility(int32_t viewportInd = -1); // test visibility for the i'th viewport, + // -1 means currently active viewport + // ==================================================================== // ==== Options ======================================================= // ==================================================================== @@ -264,7 +272,12 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer protected: // = State + PersistentValue enabled; + + // Used to implement viewport visibility + PersistentValue viewportVisibilityMask; + PersistentValue objectTransform; // rigid transform // 0 for transparent, 1 for opaque, only has effect if engine transparency is set diff --git a/include/polyscope/vector_quantity.ipp b/include/polyscope/vector_quantity.ipp index a9d3e939..6e97ec44 100644 --- a/include/polyscope/vector_quantity.ipp +++ b/include/polyscope/vector_quantity.ipp @@ -161,7 +161,7 @@ template void VectorQuantity::createProgram() { std::vector rules = - this->quantity.parent.addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + this->quantity.parent.addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (this->quantity.parent.wantsCullPosition()) { rules.push_back("VECTOR_CULLPOS_FROM_TAIL"); } @@ -241,8 +241,7 @@ TangentVectorQuantity::TangentVectorQuantity(QuantityT& quantity_, tangentVectors(&quantity_, quantity_.uniquePrefix() + "#values", std::vector(tangentVectors_)), tangentBasisX(&quantity_, quantity_.uniquePrefix() + "#basisX", std::vector(tangentBasisX_)), tangentBasisY(&quantity_, quantity_.uniquePrefix() + "#basisY", std::vector(tangentBasisY_)), - vectorRoots(vectorRoots_), - nSym(nSym_) { + vectorRoots(vectorRoots_), nSym(nSym_) { tangentVectors.checkInvalidValues(); tangentBasisX.checkInvalidValues(); tangentBasisY.checkInvalidValues(); @@ -287,7 +286,7 @@ template void TangentVectorQuantity::createProgram() { std::vector rules = - this->quantity.parent.addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + this->quantity.parent.addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (this->quantity.parent.wantsCullPosition()) { rules.push_back("VECTOR_CULLPOS_FROM_TAIL"); } diff --git a/include/polyscope/view.h b/include/polyscope/view.h index adbcda8c..9de889c6 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -8,6 +8,7 @@ #include "polyscope/camera_parameters.h" #include "polyscope/types.h" +#include "polyscope/view_parameters.h" // #include "polyscope/gl/gl_utils.h" #include "imgui.h" @@ -70,14 +71,16 @@ extern glm::vec3& flightInitialViewT; extern float& flightTargetFov; extern float& flightInitialFov; -// Default values +// Default values / limits extern const int defaultWindowWidth; extern const int defaultWindowHeight; extern const float defaultNearClipRatio; extern const float defaultFarClipRatio; extern const float defaultFov; +constexpr int maxNumViewports = 64; // bounded by 64-bit viewportVisibilityMask on Structure // Internal details +extern int& activeViewportIndex; extern bool overrideClipPlanes; // used for temporary state changes in render passes, internal use only! extern float overrideNearClipRelative; extern float overrideFarClipRelative; @@ -86,6 +89,9 @@ extern float overrideFarClipRelative; // == Get/Set the current camera view in the user's window +// If using viewports, whenever not specified, all functions apply to the current +// active viewport. + // Get various camera matrices and data for the current view CameraParameters getCameraParametersForCurrentView(); // contains all of this info // (these friendly helpers to get the same info as ^^^) @@ -136,6 +142,9 @@ void immediatelyEndFlight(); // == Properties of the view/window +// If using viewports, whenever not specified, all functions apply to the current +// active viewport. + // Set the size of the OS window // Set in logical pixels, which might be different from actual buffer pixels on // high-DPI screens @@ -163,23 +172,122 @@ bool getWindowResizable(); // == Utility functions related to the view -// Get world geometry corresponding to a screen pixel (e.g. from a mouse click) +// If using viewports, whenever not specified, all functions apply to the current +// active viewport. + +// Get world geometry corresponding to a screen pixel (e.g. from a mouse click). +// +// These take GLOBAL coordinates on the whole window, like the position of an ImGui click, find the viewport which +// contains them, and use the camera of that viewport. (See the coordinate note below for screenCoords vs bufferInds.) glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords); glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds); glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth); +// +// The viewport variants instead take coordinates LOCAL to the viewport viewportInd (the active viewport if -1), and +// use the camera of that viewport. +glm::vec3 viewportScreenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd = -1); +glm::vec3 viewportBufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd = -1); +glm::vec3 viewportScreenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, + int32_t viewportInd = -1); // Get and set camera from json string std::string getViewAsJson(); void setViewFromJson(std::string jsonData, bool flyTo); -std::string getCameraJson(); // DEPRACTED: old names for avove +std::string getCameraJson(); // DEPRECATED: old names for above void setCameraFromJson(std::string jsonData, bool flyTo); - -// Misc helpers -std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); -glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); -glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); +// TODO add functions to serialize all viewports at once + +// == Misc helpers + +// === Coordinate system conventions === +// +// There are two kinds of 2D pixel coordinates. They differ ONLY by a scale factor, never by origin or direction: +// +// Screen coords (glm::vec2, float) — logical pixels. Used by ImGui (io.MousePos), window/widget layout. +// +// Buffer indices (glm::ivec2, int) — pixels of the render buffers. On high-DPI (e.g. MacOS Retina) displays each +// 1.0 screen-coord unit spans multiple buffer pixels. +// +// BOTH have their origin at the TOP-LEFT, with y increasing DOWNWARD. This is the convention for everything in the +// Polyscope API: view/pick functions, PickResult, viewport locations like ViewParameters::viewportRelativePosY and +// viewportPosY, etc. +// +// When using viewports, coordinates are additionally expressed in one of two frames: +// +// Global — the origin is the top-left of the whole window. +// Local — the origin is the top-left of one particular viewport. +// +// Functions below state which frame they use for arguments and return values; unless a name says "Viewport" or an +// argument says "local", assume GLOBAL. A viewport covering the whole window has identical local and global coords. + +// Convert between buffer indices and screen coords (see definition above), in the GLOBAL frame of the whole window. +glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); // buffer → screen glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds); -std::string getCurrentProjectionModeRaycastRule(); +glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); // screen → buffer +std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); + +// The same conversions as above, but both the inputs and outputs are in the LOCAL frame of the given viewport. +// Pass viewportInd=-1 to use the current active viewport. (Local buffer indices are clamped to lie inside the +// viewport.) +glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd = -1); +glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd = -1); +glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); +std::tuple screenCoordsToBufferIndsViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); + +// Given GLOBAL screen coordinates / buffer inds, determine which viewport they lie in (the topmost one, if viewports +// overlap). +int32_t screenCoordsToViewportInd(glm::vec2 screenCoords); +int32_t bufferIndsToViewportInd(glm::ivec2 bufferInds); + +// Given GLOBAL screen coordinates / buffer inds, determine which viewport they lie in, and the LOCAL coordinates within +// that viewport. The return tuple is +std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoords); +std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds); + +// Given LOCAL screen coordinates / buffer inds within a viewport, return the corresponding GLOBAL coordinates. +// Pass viewportInd=-1 to use the current active viewport. +glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd = -1); +glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd = -1); + + +// == Viewport helpers + +// High-level helper to create a grid of viewports and arrange them in a grid +void createViewportGrid(int gridWidth, int gridHeight); + +// Manually create viewports and arrange them +void setNumViewports(int count); +void setActiveViewportRelativeLocation(float posX, float posY); // on [0,1], of the viewport's top-left corner (y down) +void setActiveViewportRelativeSize(float width, float height); // on [0,1] + +int getNumViewports(); + +// Set the active viewport +void activateViewport(int viewportInd); +int getActiveViewportIndex(); + +// Get info about the current active viewport +int getActiveViewportBufferWidth(); +int getActiveViewportBufferHeight(); + +// Returns {x, y, width, height} of a viewport in screen coordinates (see definition above). +// Pass viewportInd=-1 to use the active viewport. +glm::vec4 getViewportImGuiRect(int32_t viewportInd = -1); + +// Get a reference to the view parameters for a specific viewport, -1 means the active viewport. +const view::ViewParameters& getViewportParameters(int32_t viewportInd = -1); + +// If true, all viewports share the same camera and rotation/translation/zoom etc applies +// to all views simultaneously. If false, each viewport has its own independent camera and navigation state. +bool getViewportsShareNavigation(); +void setViewportsShareNavigation(bool shareNavigation); + +// viewport internal helpers +void createInitialViewport(); +void clearViewports(); +void validateViewports(); +void updateViewportDimensions(); +void propagateViewUpdatesToViewports(); // == Internal helpers. Should probably not be called in user code. diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h new file mode 100644 index 00000000..6ad44fb4 --- /dev/null +++ b/include/polyscope/view_parameters.h @@ -0,0 +1,65 @@ +// Copyright 2017-2023, Nicholas Sharp and the Polyscope contributors. https://polyscope.run + +#pragma once + +#include + +#include "polyscope/types.h" + +#include "glm/gtx/dual_quaternion.hpp" +#include "glm/gtx/norm.hpp" // necessary for dual_quaternion below +#include "glm/mat4x4.hpp" +#include "glm/vec3.hpp" + +namespace polyscope { +namespace view { + +struct ViewParameters { + + NavigateStyle style; + UpDir upDir; + FrontDir frontDir; + float moveScale; + ViewRelativeMode viewRelativeMode; + float nearClip; + float farClip; + std::array bgColor; + + // Current view camera parameters + // TODO deprecate these one day, and just use a CameraParameters member instead. But this would break existing code, + // so for now we leave these as-is and wrap inputs/outputs to a CameraParameters + glm::mat4x4 viewMat; + float fov; // in the y direction + glm::vec3 viewCenter; // center about which view transformations are performed + ProjectionMode projectionMode; + + // "Flying" view members + bool midflight; + float flightStartTime; + float flightEndTime; + glm::dualquat flightTargetViewR; + glm::dualquat flightInitialViewR; + glm::vec3 flightTargetViewT; + glm::vec3 flightInitialViewT; + float flightTargetFov; + float flightInitialFov; + + // Viewport position and size as fractions of the full window, in [0,1]. + // posX/posY is the top-left corner (y=0 at the top, like screen coords). + float viewportRelativePosX; + float viewportRelativePosY; + float viewportRelativeWidth; + float viewportRelativeHeight; + + // Computed viewport geometry derived from the relative values above. + // See note in view.h for the distinction of bufferIndices vs screenCoords. + int viewportPosX; // top-left corner of the viewport in buffer inds (integer pixel inds) + int viewportPosY; // (y=0 at the top, like buffer inds everywhere else. OpenGL calls flip this as needed) + int viewportBufferWidth; // viewport dimensions in buffer inds (integer buffer pixels) + int viewportBufferHeight; // viewport dimensions in buffer inds (integer buffer pixels) + float viewportWindowWidth; // viewport dimensions in screenCoords (floats, as in ImGui etc) + float viewportWindowHeight; // viewport dimensions in screenCoords (floats, as in ImGui etc) +}; + +} // namespace view +} // namespace polyscope diff --git a/src/camera_view.cpp b/src/camera_view.cpp index c86e066d..5809d9d7 100644 --- a/src/camera_view.cpp +++ b/src/camera_view.cpp @@ -154,16 +154,14 @@ void CameraView::drawPickDelayed() { void CameraView::prepare() { { - std::vector rules = - addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + std::vector rules = addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (wantsCullPosition()) rules.push_back("SPHERE_CULLPOS_FROM_CENTER"); rules = render::engine->addMaterialRules(material, rules); nodeProgram = render::engine->requestShader("RAYCAST_SPHERE", rules); } { - std::vector rules = - addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + std::vector rules = addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (wantsCullPosition()) rules.push_back("CYLINDER_CULLPOS_FROM_MID"); rules = render::engine->addMaterialRules(material, rules); edgeProgram = render::engine->requestShader("RAYCAST_CYLINDER", rules); diff --git a/src/curve_network.cpp b/src/curve_network.cpp index 10a9eff6..972eef52 100644 --- a/src/curve_network.cpp +++ b/src/curve_network.cpp @@ -226,7 +226,7 @@ void CurveNetwork::drawPickDelayed() { std::vector CurveNetwork::addCurveNetworkNodeRules(std::vector initRules) { initRules = addStructureRules(initRules); - initRules.push_back(view::getCurrentProjectionModeRaycastRule()); + initRules.push_back("BUILD_RAY_FOR_FRAGMENT_DYNAMIC"); if (nodeRadiusQuantityName != "" || edgeRadiusQuantityName != "") { initRules.push_back("SPHERE_VARIABLE_SIZE"); @@ -239,7 +239,7 @@ std::vector CurveNetwork::addCurveNetworkNodeRules(std::vector CurveNetwork::addCurveNetworkEdgeRules(std::vector initRules) { initRules = addStructureRules(initRules); - initRules.push_back(view::getCurrentProjectionModeRaycastRule()); + initRules.push_back("BUILD_RAY_FOR_FRAGMENT_DYNAMIC"); // use node radius to blend cylinder radius if (nodeRadiusQuantityName != "" || edgeRadiusQuantityName != "") { @@ -381,7 +381,8 @@ void CurveNetwork::fillEdgeGeometryBuffers(render::ShaderProgram& program) { } else if (haveNodeRadiusQuantity) { // have just node CurveNetworkNodeScalarQuantity& nodeRadQ = resolveNodeRadiusQuantity(); - program.setAttribute("a_tailRadius", nodeRadQ.values.getIndexedRenderAttributeBuffer(edgeTailInds), &nodeRadQ.values); + program.setAttribute("a_tailRadius", nodeRadQ.values.getIndexedRenderAttributeBuffer(edgeTailInds), + &nodeRadQ.values); program.setAttribute("a_tipRadius", nodeRadQ.values.getIndexedRenderAttributeBuffer(edgeTipInds), &nodeRadQ.values); } } diff --git a/src/internal.cpp b/src/internal.cpp index 28693204..2197bcd2 100644 --- a/src/internal.cpp +++ b/src/internal.cpp @@ -29,7 +29,6 @@ float rightWindowsWidth = -1.; namespace lazy { TransparencyMode transparencyMode = TransparencyMode::None; -ProjectionMode projectionMode = ProjectionMode::Perspective; int transparencyRenderPasses = 8; int ssaaFactor = 1; float uiScale = -1.; diff --git a/src/persistent_value.cpp b/src/persistent_value.cpp index 193ad803..1e16f053 100644 --- a/src/persistent_value.cpp +++ b/src/persistent_value.cpp @@ -9,6 +9,7 @@ namespace detail { // storage for persistent value global caches // clang-format off PersistentCache persistentCache_int32_t; +PersistentCache persistentCache_uint64_t; PersistentCache persistentCache_double; PersistentCache persistentCache_float; PersistentCache persistentCache_bool; diff --git a/src/pick.cpp b/src/pick.cpp index db1cfe6e..8057bd1c 100644 --- a/src/pick.cpp +++ b/src/pick.cpp @@ -10,13 +10,47 @@ namespace polyscope { +// The workhorse for all of the pick functions below. Takes buffer inds that are LOCAL to the currently ACTIVE viewport. +// (the public functions below take care of routing to the right viewport and converting coordinates) +static PickResult pickAtActiveViewportBufferInds(glm::ivec2 bufferInds); + PickResult pickAtScreenCoords(glm::vec2 screenCoords) { - int xInd, yInd; - glm::ivec2 bufferInds = view::screenCoordsToBufferIndsVec(screenCoords); - return pickAtBufferInds(bufferInds); + // screenCoords are global, find the viewport they lie in and the local coordinates there + glm::vec2 localScreenCoords; + int32_t viewportInd; + std::tie(localScreenCoords, viewportInd) = view::screenCoordsGlobalToViewport(screenCoords); + return pickViewportAtScreenCoords(localScreenCoords, viewportInd); } PickResult pickAtBufferInds(glm::ivec2 bufferInds) { + // bufferInds are global, find the viewport they lie in and the local indices there + glm::ivec2 localBufferInds; + int32_t viewportInd; + std::tie(localBufferInds, viewportInd) = view::bufferIndsGlobalToViewport(bufferInds); + return pickViewportAtBufferInds(localBufferInds, viewportInd); +} + +PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd) { + int32_t prevViewport = view::getActiveViewportIndex(); + if (viewportInd < 0) viewportInd = prevViewport; + if (viewportInd != prevViewport) view::activateViewport(viewportInd); + glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, viewportInd); + PickResult result = pickAtActiveViewportBufferInds(localBufferInds); + if (viewportInd != prevViewport) view::activateViewport(prevViewport); + return result; +} + +PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd) { + int32_t prevViewport = view::getActiveViewportIndex(); + if (viewportInd < 0) viewportInd = prevViewport; + if (viewportInd != prevViewport) view::activateViewport(viewportInd); + PickResult result = pickAtActiveViewportBufferInds(bufferInds); // already local to the viewport, no conversion + if (viewportInd != prevViewport) view::activateViewport(prevViewport); + return result; +} + +static PickResult pickAtActiveViewportBufferInds(glm::ivec2 bufferInds) { + // bufferInds are local to the active viewport PickResult result; // Query the pick buffer @@ -25,14 +59,23 @@ PickResult pickAtBufferInds(glm::ivec2 bufferInds) { // Query the depth buffer populated above render::FrameBuffer* pickFramebuffer = render::engine->pickFramebuffer.get(); - float clipDepth = pickFramebuffer->readDepth(bufferInds.x, view::bufferHeight - bufferInds.y); + int viewportW = view::getActiveViewportBufferWidth(); + int viewportH = view::getActiveViewportBufferHeight(); + float clipDepth = 1.0f; + if (bufferInds.x >= 0 && bufferInds.x < viewportW && bufferInds.y >= 0 && bufferInds.y < viewportH) { + clipDepth = pickFramebuffer->readDepth(bufferInds.x, viewportH - 1 - bufferInds.y); + } // Transcribe result into return tuple result.structure = std::get<0>(rawPickResult); result.quantity = std::get<1>(rawPickResult); - result.bufferInds = bufferInds; - result.screenCoords = view::bufferIndsToScreenCoords(bufferInds); - result.position = view::screenCoordsAndDepthToWorldPosition(result.screenCoords, clipDepth); + result.viewportInd = view::getActiveViewportIndex(); + result.viewportBufferInds = bufferInds; + result.viewportScreenCoords = view::bufferIndsToScreenCoordsViewport(bufferInds, result.viewportInd); + result.bufferInds = view::bufferIndsViewportToGlobal(bufferInds, result.viewportInd); + result.screenCoords = view::bufferIndsToScreenCoords(result.bufferInds); + result.position = + view::viewportScreenCoordsAndDepthToWorldPosition(result.viewportScreenCoords, clipDepth, result.viewportInd); result.depth = glm::length(result.position - view::getCameraWorldPosition()); @@ -204,20 +247,46 @@ uint64_t localIndexToGlobal(std::tuple localPic return 0; } -std::pair pickAtScreenCoords(glm::vec2 screenCoords) { - int xInd, yInd; - std::tie(xInd, yInd) = view::screenCoordsToBufferInds(screenCoords); - return pickAtBufferCoords(xInd, yInd); +// === The old, deprecated picking API === +// +// These predate viewports, so with a single viewport (all that older code could have) they must keep behaving exactly +// as they always have. When using multiple viewports, they follow the same convention as the other viewport-aware +// functions: the coordinates are LOCAL to the viewport `iView`, where iView < 0 means the active viewport. (Some +// internal code relies on this, to pick in whatever viewport it is currently rendering.) The non-deprecated +// polyscope::pickAtScreenCoords() and polyscope::pickAtBufferInds() take global coordinates and find the viewport. + +static std::tuple evaluatePickQueryFullInActiveViewport(int xPos, int yPos); + +std::pair pickAtScreenCoords(glm::vec2 screenCoords, int32_t iView) { + glm::ivec2 localInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, iView); + return evaluatePickQuery(localInds.x, localInds.y, iView); } -std::pair pickAtBufferCoords(int xPos, int yPos) { return evaluatePickQuery(xPos, yPos); } +std::pair pickAtBufferCoords(int xPos, int yPos, int32_t iView) { + return evaluatePickQuery(xPos, yPos, iView); +} -std::tuple evaluatePickQueryFull(int xPos, int yPos) { +std::tuple evaluatePickQueryFull(int xPos, int yPos, int32_t iView) { + // the pick is evaluated in the active viewport, so temporarily activate the requested viewport if needed + int32_t prevViewport = view::getActiveViewportIndex(); + if (iView < 0 || iView == prevViewport) { + return evaluatePickQueryFullInActiveViewport(xPos, yPos); + } + view::activateViewport(iView); + std::tuple result = evaluatePickQueryFullInActiveViewport(xPos, yPos); + view::activateViewport(prevViewport); + return result; +} + +static std::tuple evaluatePickQueryFullInActiveViewport(int xPos, int yPos) { // NOTE: hack used for debugging: if xPos == yPos == -1 we do a pick render but do not query the value. + int viewportW = view::getActiveViewportBufferWidth(); + int viewportH = view::getActiveViewportBufferHeight(); + // Be sure not to pick outside of buffer - if (xPos < -1 || xPos >= view::bufferWidth || yPos < -1 || yPos >= view::bufferHeight) { + if (xPos < -1 || xPos >= viewportW || yPos < -1 || yPos >= viewportH) { return {nullptr, nullptr, 0}; } @@ -226,20 +295,22 @@ std::tuple evaluatePickQueryFull(int xPos, int render::engine->setDepthMode(DepthMode::Less); render::engine->setBlendMode(BlendMode::Disable); - pickFramebuffer->resize(view::bufferWidth, view::bufferHeight); - pickFramebuffer->setViewport(0, 0, view::bufferWidth, view::bufferHeight); + pickFramebuffer->resize(viewportW, viewportH); + pickFramebuffer->setViewport(0, 0, viewportW, viewportH); pickFramebuffer->clearColor = glm::vec3{0., 0., 0.}; if (!pickFramebuffer->bindForRendering()) return {nullptr, nullptr, 0}; pickFramebuffer->clear(); // Render pick buffer for (auto& cat : state::structures) { - for (auto& x : cat.second) { - x.second->drawPick(); + for (auto& s : cat.second) { + if (!s.second->getViewportVisibility()) continue; + s.second->drawPick(); } } for (auto& catMap : state::structures) { for (auto& s : catMap.second) { + if (!s.second->getViewportVisibility()) continue; s.second->drawPickDelayed(); } } @@ -250,14 +321,14 @@ std::tuple evaluatePickQueryFull(int xPos, int } // Read from the pick buffer - std::array result = pickFramebuffer->readFloat4(xPos, view::bufferHeight - yPos); + std::array result = pickFramebuffer->readFloat4(xPos, viewportH - 1 - yPos); uint64_t globalInd = pick::vecToInd(glm::vec3{result[0], result[1], result[2]}); return pick::globalIndexToLocal(globalInd); } -std::pair evaluatePickQuery(int xPos, int yPos) { - std::tuple t = evaluatePickQueryFull(xPos, yPos); +std::pair evaluatePickQuery(int xPos, int yPos, int32_t iView) { + std::tuple t = evaluatePickQueryFull(xPos, yPos, iView); return std::pair(std::get<0>(t), std::get<2>(t)); } diff --git a/src/point_cloud.cpp b/src/point_cloud.cpp index f7dcf170..d0759fc7 100644 --- a/src/point_cloud.cpp +++ b/src/point_cloud.cpp @@ -248,7 +248,7 @@ std::vector PointCloud::addPointCloudRules(std::vector initRules = addStructureRules(initRules); if (withPointCloud) { - initRules.push_back(view::getCurrentProjectionModeRaycastRule()); + initRules.push_back("BUILD_RAY_FOR_FRAGMENT_DYNAMIC"); if (pointRadiusQuantityName != "") { initRules.push_back("SPHERE_VARIABLE_SIZE"); diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 3bf6cfb6..8411c511 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -39,7 +39,7 @@ namespace { struct ContextEntry { ImGuiContext* context; ImPlotContext* plotContext; - std ::function callback; + std::function callback; bool drawDefaultUI; }; std::vector contextStack; @@ -247,6 +247,7 @@ void init(std::string backend) { internal::contextStackSize++; view::invalidateView(); + view::createInitialViewport(); state::initialized = true; state::doDefaultMouseInteraction = true; @@ -422,6 +423,8 @@ void drawStructures() { for (auto& catMap : state::structures) { for (auto& s : catMap.second) { + if (!s.second->getViewportVisibility()) continue; + s.second->draw(); } } @@ -437,6 +440,8 @@ void drawStructuresDelayed() { // drawn for (auto& catMap : state::structures) { for (auto& s : catMap.second) { + if (!s.second->getViewportVisibility()) continue; + s.second->drawDelayed(); } } @@ -480,6 +485,14 @@ void processInputEvents() { // === Mouse inputs if (!io.WantCaptureMouse && !widgetCapturedMouse) { + // Activate the viewport under the mouse on click (affects widget placement etc, regardless of nav sharing) + if (ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1)) { + int clickedViewport = view::screenCoordsToViewportInd({io.MousePos.x, io.MousePos.y}); + if (clickedViewport != view::getActiveViewportIndex()) { + view::activateViewport(clickedViewport); + } + } + { // Process scroll via "mouse wheel" (which might be a touchpad) float xoffset = io.MouseWheelH; float yoffset = io.MouseWheel; @@ -494,12 +507,19 @@ void processInputEvents() { // which might involve intentionally holding shift) bool scrollClipPlane = io.KeyShift && !io.KeyCtrl; - if (scrollClipPlane && clipPlaneOffset != 0.0f) { - view::processClipPlaneShift(clipPlaneOffset); - requestRedraw(); - } - if (!scrollClipPlane && scrollOffset != 0.0f) { - view::processZoom(0.5 * scrollOffset); + bool doClipScroll = scrollClipPlane && clipPlaneOffset != 0.0f; + bool doZoomScroll = !scrollClipPlane && scrollOffset != 0.0f; + if (doClipScroll || doZoomScroll) { + int hoveredViewport = view::screenCoordsToViewportInd({io.MousePos.x, io.MousePos.y}); + if (hoveredViewport != view::getActiveViewportIndex()) { + view::activateViewport(hoveredViewport); + } + if (doClipScroll) { + view::processClipPlaneShift(clipPlaneOffset); + } + if (doZoomScroll) { + view::processZoom(0.5 * scrollOffset); + } requestRedraw(); } } @@ -510,6 +530,15 @@ void processInputEvents() { bool dragRight = !dragLeft && ImGui::IsMouseDragging(1); // left takes priority, so only one can be true if (dragLeft || dragRight) { + // Activate the viewport under the initial click + { + ImVec2 clickPos = dragLeft ? io.MouseClickedPos[0] : io.MouseClickedPos[1]; + int clickedViewport = view::screenCoordsToViewportInd({clickPos.x, clickPos.y}); + if (clickedViewport != view::getActiveViewportIndex()) { + view::activateViewport(clickedViewport); + } + } + glm::vec2 dragDelta{io.MouseDelta.x / view::windowWidth, -io.MouseDelta.y / view::windowHeight}; dragDistSinceLastRelease += std::abs(dragDelta.x); dragDistSinceLastRelease += std::abs(dragDelta.y); @@ -523,11 +552,16 @@ void processInputEvents() { view::processZoom(dragDelta.y * 5); } if (isRotate) { - glm::vec2 currPos{io.MousePos.x / view::windowWidth, - (view::windowHeight - io.MousePos.y) / view::windowHeight}; - currPos = (currPos * 2.0f) - glm::vec2{1.0, 1.0}; - if (std::abs(currPos.x) <= 1.0 && std::abs(currPos.y) <= 1.0) { - view::processRotate(currPos - 2.0f * dragDelta, currPos); + // Normalize current and previous mouse positions relative to the active viewport for arc-based rotation. + glm::vec4 svRect = view::getViewportImGuiRect(); + if (svRect.z > 0.0f && svRect.w > 0.0f) { + glm::vec2 currPos{(io.MousePos.x - svRect.x) / svRect.z, + (svRect.w - (io.MousePos.y - svRect.y)) / svRect.w}; + currPos = (currPos * 2.0f) - glm::vec2{1.0f, 1.0f}; + glm::vec2 prevPos{((io.MousePos.x - io.MouseDelta.x) - svRect.x) / svRect.z, + (svRect.w - ((io.MousePos.y - io.MouseDelta.y) - svRect.y)) / svRect.w}; + prevPos = (prevPos * 2.0f) - glm::vec2{1.0f, 1.0f}; + view::processRotate(prevPos, currPos); } } if (isTranslate) { @@ -612,88 +646,146 @@ void renderScene() { render::engine->applyTransparencySettings(); - render::engine->sceneBuffer->clearColor = {0., 0., 0.}; - render::engine->sceneBuffer->clearAlpha = 0.; - render::engine->sceneBuffer->clear(); - - if (!render::engine->bindSceneBuffer()) return; + if (!options::renderScene) return; - // If a view has never been set, this will set it to the home view - view::ensureViewValid(); + if (view::getNumViewports() == 0) { + error("there are no viewports"); + } - if (!options::renderScene) return; + // We internally change the active viewport to render; save it here so we can restore at the end + int savedActiveViewport = view::getActiveViewportIndex(); if (render::engine->getTransparencyMode() == TransparencyMode::Pretty) { // Special depth peeling case: multiple render passes // We will perform several "peeled" rounds of rendering in to the usual scene buffer. After each, we will manually // composite in to the final scene buffer. - // Clear the final buffer explicitly since we will gradually composite in to it rather than just blitting directly // as in normal rendering. render::engine->sceneBufferFinal->clearColor = glm::vec3{0., 0., 0.}; render::engine->sceneBufferFinal->clearAlpha = 0; render::engine->sceneBufferFinal->clear(); - render::engine->setDepthMode(DepthMode::Less); // we need depth to be enabled for the clear below to do anything - render::engine->sceneDepthMinFrame->clear(); + for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { + view::activateViewport(viewportInd); + view::ensureViewValid(); + view::updateFlight(); + render::engine->setActiveSceneTarget(viewportInd); + view::ViewParameters vp = view::getViewportParameters(viewportInd); + int ssaa = render::engine->getSSAAFactor(); - for (int iPass = 0; iPass < options::transparencyRenderPasses; iPass++) { - bool isRedraw = iPass > 0; - internal::renderPassIsRedraw = isRedraw; + render::engine->setDepthMode(DepthMode::Less); // we need depth to be enabled for the clear below to do anything + render::engine->sceneDepthMinFrame->clear(); - render::engine->bindSceneBuffer(); - render::engine->clearSceneBuffer(); + for (int iPass = 0; iPass < options::transparencyRenderPasses; iPass++) { + bool isRedraw = iPass > 0; + internal::renderPassIsRedraw = isRedraw; - render::engine->applyTransparencySettings(); - drawStructures(); + if (!render::engine->bindSceneBuffer()) { + // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw + break; + } + render::engine->clearSceneBuffer(); - // Draw ground plane, slicers, etc - render::engine->groundPlane.draw(isRedraw); - if (!isRedraw) { - // Only on first pass (kinda weird, but works out, and doesn't really matter) - renderSlicePlanes(); - } + render::engine->applyTransparencySettings(); + drawStructures(); - render::engine->applyTransparencySettings(); - drawStructuresDelayed(); + // Draw ground plane, slicers, etc + render::engine->groundPlane.draw(isRedraw); + if (!isRedraw) { + // Only on first pass (kinda weird, but works out, and doesn't really matter) + renderSlicePlanes(); + } - // Composite the result of this pass in to the result buffer - render::engine->sceneBufferFinal->bind(); - render::engine->setDepthMode(DepthMode::Disable); - render::engine->setBlendMode(BlendMode::AlphaUnder); - render::engine->compositePeel->draw(); + render::engine->applyTransparencySettings(); + drawStructuresDelayed(); + + // Composite the result of this pass in to the result buffer. + // Set the viewport to the viewport's region in sceneBufferFinal so the fullscreen quad composites + // only into the correct portion of the final buffer. + // (viewportPosY is y-from-top like everywhere else, but OpenGL viewports have y=0 at the bottom, so flip it) + int viewportPosYFromBottom = view::bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + render::engine->sceneBufferFinal->setViewport(ssaa * vp.viewportPosX, ssaa * viewportPosYFromBottom, + ssaa * vp.viewportBufferWidth, ssaa * vp.viewportBufferHeight); + render::engine->sceneBufferFinal->bindForRendering(); + render::engine->setDepthMode(DepthMode::Disable); + render::engine->setBlendMode(BlendMode::AlphaUnder); + render::engine->compositePeel->setTextureFromBuffer("t_image", render::engine->sceneColor.get()); + render::engine->compositePeel->draw(); + + // Update the minimum depth texture + render::engine->updateMinDepthTexture(); + } - // Update the minimum depth texture - render::engine->updateMinDepthTexture(); + internal::renderPassIsRedraw = false; // reset to usual value } - internal::renderPassIsRedraw = false; // reset to usual value + // Restore sceneBufferFinal viewport to cover the full buffer + int ssaaFactor = render::engine->getSSAAFactor(); + render::engine->sceneBufferFinal->setViewport(0, 0, ssaaFactor * view::bufferWidth, + ssaaFactor * view::bufferHeight); } else { // Normal case: single render pass + + internal::renderPassIsRedraw = false; - render::engine->applyTransparencySettings(); - drawStructures(); + for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { + view::activateViewport(viewportInd); + view::ensureViewValid(); + view::updateFlight(); + render::engine->setActiveSceneTarget(viewportInd); // sets sceneBuffer (etc) to the current target viewport buffer + + render::engine->sceneBuffer->clearColor = {0., 0., 0.}; + render::engine->sceneBuffer->clearAlpha = 0.; + render::engine->sceneBuffer->clear(); + if (!render::engine->bindSceneBuffer()) { + // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw + continue; + } + + render::engine->applyTransparencySettings(); + drawStructures(); - render::engine->groundPlane.draw(); - renderSlicePlanes(); + render::engine->groundPlane.draw(); + renderSlicePlanes(); - render::engine->applyTransparencySettings(); - drawStructuresDelayed(); + render::engine->applyTransparencySettings(); + drawStructuresDelayed(); - render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get()); + view::ViewParameters vp = view::getViewportParameters(viewportInd); + int ssaaFactor = render::engine->getSSAAFactor(); + // (viewportPosY is y-from-top like everywhere else, but OpenGL has y=0 at the bottom, so flip it) + int viewportPosYFromBottom = view::bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), ssaaFactor * vp.viewportPosX, + ssaaFactor * viewportPosYFromBottom); + } } + + // restore the active viewport as it was before the render call + view::activateViewport(savedActiveViewport); + render::engine->setActiveSceneTarget(savedActiveViewport); } void renderSceneToScreen() { render::engine->bindDisplay(); if (options::debugDrawPickBuffer) { - // special debug draw - pick::evaluatePickQuery(-1, -1); // populate the buffer - render::engine->pickFramebuffer->blitTo(render::engine->displayBuffer.get()); + // special debug draw: render and blit each viewport's pick buffer into its region of displayBuffer + render::engine->displayBuffer->clearColor = {0., 0., 0.}; + render::engine->displayBuffer->clearAlpha = 1.; + render::engine->displayBuffer->clear(); + int savedActiveViewport = view::getActiveViewportIndex(); + for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { + view::activateViewport(viewportInd); + pick::evaluatePickQuery(-1, -1); // populate the buffer for this viewport + view::ViewParameters vp = view::getViewportParameters(viewportInd); + int viewportPosYFromBottom = view::bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + render::engine->pickFramebuffer->blitTo(render::engine->displayBuffer.get(), vp.viewportPosX, + viewportPosYFromBottom); + } + view::activateViewport(savedActiveViewport); } else { render::engine->applyLightingTransform(render::engine->sceneColorFinal); } @@ -893,13 +985,20 @@ void buildPolyscopeGui() { if (ImGui::Button("Force refresh")) { refresh(); } + + ImGui::Text("Active viewport: %d / %d", view::getActiveViewportIndex(), view::getNumViewports()); + ImGui::Checkbox("Show pick buffer", &options::debugDrawPickBuffer); ImGui::Checkbox("Always redraw", &options::alwaysRedraw); static bool showDebugTextures = false; ImGui::Checkbox("Show debug textures", &showDebugTextures); if (showDebugTextures) { - render::engine->showTextureInImGuiWindow("Scene", render::engine->sceneColor.get()); + for (int32_t i = 0; i < view::getNumViewports(); i++) { + render::engine->showTextureInImGuiWindow("Viewport " + std::to_string(i), + render::engine->sceneColorTargets[i].get()); + } + render::engine->showTextureInImGuiWindow("Scene Final", render::engine->sceneColorFinal.get()); } ImGui::TreePop(); @@ -997,6 +1096,10 @@ void buildPickGui() { ImGui::Text("screen coordinates: (%.2f,%.2f) depth: %g", selection.screenCoords.x, selection.screenCoords.y, selection.depth); + if (view::getNumViewports() > 1) { + ImGui::Text("viewport: %d local coordinates: (%.2f,%.2f)", selection.viewportInd, + selection.viewportScreenCoords.x, selection.viewportScreenCoords.y); + } ImGui::Text("world position: <%g, %g, %g>", selection.position.x, selection.position.y, selection.position.z); ImGui::NewLine(); @@ -1068,7 +1171,6 @@ void draw(bool withUI, bool withContextCallback) { render::engine->ImGuiNewFrame(); processInputEvents(); - view::updateFlight(); showDelayedWarnings(); } @@ -1109,8 +1211,8 @@ void draw(bool withUI, bool withContextCallback) { // Draw structures in the scene if (redrawNextFrame || options::alwaysRedraw) { - renderScene(); redrawNextFrame = false; + renderScene(); } renderSceneToScreen(); @@ -1154,6 +1256,7 @@ void mainLoopIteration() { void show(size_t forFrames) { checkInitialized(); + view::validateViewports(); if (isHeadless() && forFrames == 0) { info("You called show() while in headless mode. In headless mode there is no display to create windows on. By " @@ -1238,6 +1341,7 @@ void shutdown(bool allowMidFrameShutdown) { } removeEverything(); + view::clearViewports(); // Shut down the render engine render::engine->shutdown(); @@ -1495,12 +1599,6 @@ void processLazyProperties() { // There is a second function processLazyPropertiesOutsideOfImGui() which handles a few more that can only be set // at limited times when an ImGui frame is not active. - // projection mode - if (internal::lazy::projectionMode != view::projectionMode) { - internal::lazy::projectionMode = view::projectionMode; - view::setProjectionMode(view::projectionMode); - } - // transparency mode if (internal::lazy::transparencyMode != options::transparencyMode) { internal::lazy::transparencyMode = options::transparencyMode; diff --git a/src/render/engine.cpp b/src/render/engine.cpp index 79ff0ac8..55da0104 100644 --- a/src/render/engine.cpp +++ b/src/render/engine.cpp @@ -134,7 +134,7 @@ int renderDataTypeCountCompatbility(const RenderDataType r1, const RenderDataTyp if (r1 == RenderDataType::Vector2Float && r2 == RenderDataType::Float) return 2; if (r1 == RenderDataType::Vector3Float && r2 == RenderDataType::Float) return 3; if (r1 == RenderDataType::Vector4Float && r2 == RenderDataType::Float) return 4; - + if (r1 == RenderDataType::Vector2Int && r2 == RenderDataType::Int) return 2; if (r1 == RenderDataType::Vector3Int && r2 == RenderDataType::Int) return 3; if (r1 == RenderDataType::Vector4Int && r2 == RenderDataType::Int) return 4; @@ -489,27 +489,28 @@ void Engine::clearDisplay() { void Engine::clearSceneBuffer() { sceneBuffer->clear(); } -void Engine::resizeScreenBuffers() { +void Engine::resizeScreenBuffersAndSetViewports() { + view::updateViewportDimensions(); unsigned int width = view::bufferWidth; unsigned int height = view::bufferHeight; displayBuffer->resize(width, height); displayBufferAlt->resize(width, height); - sceneBuffer->resize(ssaaFactor * width, ssaaFactor * height); sceneBufferFinal->resize(ssaaFactor * width, ssaaFactor * height); - sceneDepthMinFrame->resize(ssaaFactor * width, ssaaFactor * height); -} -void Engine::setScreenBufferViewports() { - unsigned int xStart = 0; - unsigned int yStart = 0; - unsigned int sizeX = view::bufferWidth; - unsigned int sizeY = view::bufferHeight; - - displayBuffer->setViewport(xStart, yStart, sizeX, sizeY); - displayBufferAlt->setViewport(xStart, yStart, sizeX, sizeY); - sceneBuffer->setViewport(ssaaFactor * xStart, ssaaFactor * yStart, ssaaFactor * sizeX, ssaaFactor * sizeY); - sceneBufferFinal->setViewport(ssaaFactor * xStart, ssaaFactor * yStart, ssaaFactor * sizeX, ssaaFactor * sizeY); - sceneDepthMinFrame->setViewport(ssaaFactor * xStart, ssaaFactor * yStart, ssaaFactor * sizeX, ssaaFactor * sizeY); + displayBuffer->setViewport(0, 0, width, height); + displayBufferAlt->setViewport(0, 0, width, height); + sceneBufferFinal->setViewport(0, 0, ssaaFactor * width, ssaaFactor * height); + + for (size_t i = 0; i < sceneBufferTargets.size(); i++) { + view::ViewParameters vp = view::getViewportParameters(i); + + sceneBufferTargets[i]->resize(ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); + sceneDepthMinFrameTargets[i]->resize(ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); + + sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); + sceneDepthMinFrameTargets[i]->setViewport(0, 0, ssaaFactor * vp.viewportBufferWidth, + ssaaFactor * vp.viewportBufferHeight); + } } bool Engine::bindSceneBuffer() { @@ -517,6 +518,56 @@ bool Engine::bindSceneBuffer() { return sceneBuffer->bindForRendering(); } +void Engine::setActiveSceneTarget(int i) { + if (i >= (int)sceneBufferTargets.size()) exception("invalid scene target index"); + sceneBuffer = sceneBufferTargets[i]; + sceneColor = sceneColorTargets[i]; + sceneDepth = sceneDepthTargets[i]; + sceneDepthMin = sceneDepthMinTargets[i]; + sceneDepthMinFrame = sceneDepthMinFrameTargets[i]; +} + +void Engine::ensureSceneTargetsAllocated(int count) { + int currentCount = (int)sceneColorTargets.size(); + if (currentCount == count) return; + + sceneColorTargets.resize(count); + sceneDepthTargets.resize(count); + sceneBufferTargets.resize(count); + sceneDepthMinTargets.resize(count); + sceneDepthMinFrameTargets.resize(count); + + // initialize any new targets/buffers + for (int i = currentCount; i < count; i++) { + + // we always initialize at the arbitray size of 128x128, then resize below to avoid duplicating logic + unsigned int w = 128; + unsigned int h = 128; + + std::shared_ptr color = generateTextureBuffer(TextureFormat::RGBA16F, w, h); + std::shared_ptr depth = generateTextureBuffer(TextureFormat::DEPTH24, w, h); + std::shared_ptr fb = generateFrameBuffer(w, h); + fb->addColorBuffer(color); + fb->addDepthBuffer(depth); + fb->setDrawBuffers(); + fb->clearColor = glm::vec3{1., 1., 1.}; + fb->clearAlpha = 0.0; + + std::shared_ptr depthMin = generateTextureBuffer(TextureFormat::DEPTH24, w, h); + std::shared_ptr depthMinFrame = generateFrameBuffer(w, h); + depthMinFrame->addDepthBuffer(depthMin); + depthMinFrame->clearDepth = 0.0; + + sceneColorTargets[i] = color; + sceneDepthTargets[i] = depth; + sceneBufferTargets[i] = fb; + sceneDepthMinTargets[i] = depthMin; + sceneDepthMinFrameTargets[i] = depthMinFrame; + } + + resizeScreenBuffersAndSetViewports(); +} + void Engine::applyLightingTransform(std::shared_ptr& texture) { glm::vec4 currV = getCurrentViewport(); @@ -690,30 +741,6 @@ void Engine::allocateGlobalBuffersAndPrograms() { // Note: The display frame buffer should be manually wrapped by child classes - { // Scene buffer - - // Note that this is basically duplicated in ground_plane.cpp, changes here should probably be reflected there - sceneColor = generateTextureBuffer(TextureFormat::RGBA16F, view::bufferWidth, view::bufferHeight); - // sceneDepth = generateRenderBuffer(RenderBufferType::Depth, view::bufferWidth, view::bufferHeight); - sceneDepth = generateTextureBuffer(TextureFormat::DEPTH24, view::bufferWidth, view::bufferHeight); - - sceneBuffer = generateFrameBuffer(view::bufferWidth, view::bufferHeight); - sceneBuffer->addColorBuffer(sceneColor); - sceneBuffer->addDepthBuffer(sceneDepth); - sceneBuffer->setDrawBuffers(); - - sceneBuffer->clearColor = glm::vec3{1., 1., 1.}; - sceneBuffer->clearAlpha = 0.0; - } - - { // Alternate depth texture used for some effects - sceneDepthMin = generateTextureBuffer(TextureFormat::DEPTH24, view::bufferWidth, view::bufferHeight); - - sceneDepthMinFrame = generateFrameBuffer(view::bufferWidth, view::bufferHeight); - sceneDepthMinFrame->addDepthBuffer(sceneDepthMin); - sceneDepthMinFrame->clearDepth = 0.0; - } - { // "Final" scene buffer (after resolving) sceneColorFinal = generateTextureBuffer(TextureFormat::RGBA16F, view::bufferWidth, view::bufferHeight); @@ -773,12 +800,10 @@ void Engine::allocateGlobalBuffersAndPrograms() { compositePeel = render::engine->requestShader("COMPOSITE_PEEL", {}, render::ShaderReplacementDefaults::Process); compositePeel->setAttribute("a_position", screenTrianglesCoords()); compositePeel->setDrawCount(screenTrianglesCoords().size()); - compositePeel->setTextureFromBuffer("t_image", sceneColor.get()); copyDepth = render::engine->requestShader("DEPTH_COPY", {}, render::ShaderReplacementDefaults::Process); copyDepth->setAttribute("a_position", screenTrianglesCoords()); copyDepth->setDrawCount(screenTrianglesCoords().size()); - copyDepth->setTextureFromBuffer("t_depth", sceneDepth.get()); // clang-format on } @@ -909,8 +934,9 @@ std::vector Engine::distantCubeCoords() { } void Engine::updateMinDepthTexture() { + sceneDepthMinFrame->bindForRendering(); setDepthMode(DepthMode::Greater); - sceneDepthMinFrame->bind(); + copyDepth->setTextureFromBuffer("t_depth", sceneDepth.get()); copyDepth->draw(); } @@ -919,13 +945,18 @@ void Engine::freeAllOwnedResources() { displayBuffer.reset(); displayBufferAlt.reset(); sceneBuffer.reset(); + sceneBufferTargets.clear(); sceneBufferFinal.reset(); pickFramebuffer.reset(); sceneDepthMinFrame.reset(); + sceneDepthMinFrameTargets.clear(); sceneColor.reset(); sceneColorFinal.reset(); sceneDepth.reset(); sceneDepthMin.reset(); + sceneColorTargets.clear(); + sceneDepthTargets.clear(); + sceneDepthMinTargets.clear(); pickColorBuffer.reset(); pickDepthBuffer.reset(); renderTexturePlain.reset(); diff --git a/src/render/ground_plane.cpp b/src/render/ground_plane.cpp index 391eeb5d..9a5ad613 100644 --- a/src/render/ground_plane.cpp +++ b/src/render/ground_plane.cpp @@ -62,7 +62,7 @@ void GroundPlane::populateGroundPlaneGeometry() { // clang-format on groundPlaneProgram->setAttribute("a_position", positions); - groundPlaneProgram->setDrawCount(4*3); + groundPlaneProgram->setDrawCount(4 * 3); groundPlaneViewCached = view::upDir; } @@ -410,6 +410,9 @@ void GroundPlane::draw(bool isRedraw) { // Render the ground plane render::engine->applyTransparencySettings(); setUniforms(); + if (options::transparencyMode == TransparencyMode::Pretty) { + groundPlaneProgram->setTextureFromBuffer("t_minDepth", render::engine->sceneDepthMin.get()); + } groundPlaneProgram->draw(); } diff --git a/src/render/mock_opengl/mock_gl_engine.cpp b/src/render/mock_opengl/mock_gl_engine.cpp index 2be064b8..b9924707 100644 --- a/src/render/mock_opengl/mock_gl_engine.cpp +++ b/src/render/mock_opengl/mock_gl_engine.cpp @@ -412,7 +412,9 @@ void GLTextureBuffer::resize(unsigned int newX, unsigned int newY, unsigned int checkGLError(); } -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); } +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +} void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { @@ -508,17 +510,39 @@ void GLTextureBuffer::setData(const std::vector& data, size_t offset, si checkGLError(); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; void GLTextureBuffer::setFilterMode(FilterMode newMode) { @@ -730,7 +754,7 @@ std::vector GLFrameBuffer::readBuffer() { return buff; } -void GLFrameBuffer::blitTo(FrameBuffer* targetIn) { +void GLFrameBuffer::blitTo(FrameBuffer* targetIn, int targetPosX, int targetPosY) { // it _better_ be a GL buffer GLFrameBuffer* target = dynamic_cast(targetIn); @@ -800,7 +824,8 @@ void GLCompiledProgram::addUniqueAttribute(ShaderSpecAttribute newAttribute) { return; } } - attributes.push_back(GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, nullptr, nullptr}); + attributes.push_back( + GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, nullptr, nullptr}); } void GLCompiledProgram::addUniqueUniform(ShaderSpecUniform newUniform) { @@ -821,8 +846,7 @@ void GLCompiledProgram::addUniqueTexture(ShaderSpecTexture newTexture) { if (t.name == newTexture.name) { // if it occurs twice, confirm that the occurences match - if (t.type != newTexture.type) - exception("texture " + t.name + " appears twice in program with different types"); + if (t.type != newTexture.type) exception("texture " + t.name + " appears twice in program with different types"); return; } @@ -859,7 +883,8 @@ void GLShaderProgram::createBuffers() { } } -void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source) { +void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, + ManagedBufferBase* source) { bindVAO(); checkGLError(); @@ -1495,7 +1520,8 @@ void GLShaderProgram::setTextureFromBuffer(std::string name, TextureBuffer* text (bufDim == 3 && t.type == ShaderTextureType::Texture3D); if (!typeMatches) { throw std::invalid_argument("Tried to use texture " + name + " with mismatched type " + - shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + "D texture buffer"); + shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + + "D texture buffer"); } t.textureBuffer = dynamic_cast(textureBuffer); @@ -1674,8 +1700,9 @@ void GLShaderProgram::validateData() { for (GLShaderAttribute a : attributes) { int compatCount = renderDataTypeCountCompatbility(a.type, a.buff->getType()); if (a.buff->getBufferSize() / static_cast(compatCount) < static_cast(drawCount)) - throw std::invalid_argument("Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + - ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); + throw std::invalid_argument( + "Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + + ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); } } @@ -1907,7 +1934,7 @@ void MockGLEngine::updateWindowSize(bool force) { newWindowHeight != view::windowHeight || newWindowWidth != view::windowWidth) { // Basically a resize callback requestRedraw(); - + // prevent any division by zero for e.g. aspect ratio calcs if (newBufferHeight == 0) newBufferHeight = 1; if (newWindowHeight == 0) newWindowHeight = 1; @@ -1916,9 +1943,7 @@ void MockGLEngine::updateWindowSize(bool force) { view::bufferHeight = newBufferHeight; view::windowWidth = newWindowWidth; view::windowHeight = newWindowHeight; - - render::engine->resizeScreenBuffers(); - render::engine->setScreenBufferViewports(); + render::engine->resizeScreenBuffersAndSetViewports(); } } @@ -2242,8 +2267,7 @@ void MockGLEngine::populateDefaultShadersAndRules() { registerShaderRule("PREMULTIPLY_LIT_COLOR", PREMULTIPLY_LIT_COLOR); registerShaderRule("CULL_POS_FROM_VIEW", CULL_POS_FROM_VIEW); registerShaderRule("PROJ_AND_INV_PROJ_MAT", PROJ_AND_INV_PROJ_MAT); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC); + registerShaderRule("BUILD_RAY_FOR_FRAGMENT_DYNAMIC", BUILD_RAY_FOR_FRAGMENT_DYNAMIC); // Lighting and shading things registerShaderRule("LIGHT_MATCAP", LIGHT_MATCAP); diff --git a/src/render/opengl/gl_engine.cpp b/src/render/opengl/gl_engine.cpp index 7438766b..29aa6b62 100644 --- a/src/render/opengl/gl_engine.cpp +++ b/src/render/opengl/gl_engine.cpp @@ -3,8 +3,8 @@ #include "polyscope/render/engine.h" #ifdef POLYSCOPE_BACKEND_OPENGL3_ENABLED -#include "polyscope/render/opengl/gl_engine.h" #include "polyscope/render/managed_buffer.h" +#include "polyscope/render/opengl/gl_engine.h" #include "polyscope/messages.h" #include "polyscope/options.h" @@ -519,7 +519,8 @@ void checkTextureSize1D(unsigned int sizeX) { void checkTextureSize2D(unsigned int sizeX, unsigned int sizeY) { GLint maxTexSize = 0; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize); - if (maxTexSize > 0 && (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize))) { + if (maxTexSize > 0 && + (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize))) { exception("OpenGL error: 2D texture size (" + std::to_string(sizeX) + " x " + std::to_string(sizeY) + ") exceeds GL_MAX_TEXTURE_SIZE (" + std::to_string(maxTexSize) + ")."); } @@ -527,8 +528,9 @@ void checkTextureSize2D(unsigned int sizeX, unsigned int sizeY) { void checkTextureSize3D(unsigned int sizeX, unsigned int sizeY, unsigned int sizeZ) { GLint maxTexSize = 0; glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &maxTexSize); - if (maxTexSize > 0 && (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize) || - sizeZ > static_cast(maxTexSize))) { + if (maxTexSize > 0 && + (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize) || + sizeZ > static_cast(maxTexSize))) { exception("OpenGL error: 3D texture size (" + std::to_string(sizeX) + " x " + std::to_string(sizeY) + " x " + std::to_string(sizeZ) + ") exceeds GL_MAX_3D_TEXTURE_SIZE (" + std::to_string(maxTexSize) + ")."); } @@ -661,7 +663,9 @@ void GLTextureBuffer::resize(unsigned int newX, unsigned int newY, unsigned int checkGLError(); } -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { size_t n = std::min(count, data.size()); @@ -785,17 +789,39 @@ void GLTextureBuffer::setData(const std::vector& data, size_t offset, si checkGLError(); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; void GLTextureBuffer::setFilterMode(FilterMode newMode) { @@ -1115,7 +1141,7 @@ std::vector GLFrameBuffer::readBuffer() { return buff; } -void GLFrameBuffer::blitTo(FrameBuffer* targetIn) { +void GLFrameBuffer::blitTo(FrameBuffer* targetIn, int targetPosX, int targetPosY) { // it _better_ be a GL buffer GLFrameBuffer* target = dynamic_cast(targetIn); @@ -1125,8 +1151,8 @@ void GLFrameBuffer::blitTo(FrameBuffer* targetIn) { bindForRendering(); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target->getHandle()); - glBlitFramebuffer(0, 0, getSizeX(), getSizeY(), 0, 0, target->getSizeX(), target->getSizeY(), GL_COLOR_BUFFER_BIT, - GL_LINEAR); + glBlitFramebuffer(0, 0, getSizeX(), getSizeY(), targetPosX, targetPosY, targetPosX + getSizeX(), + targetPosY + getSizeY(), GL_COLOR_BUFFER_BIT, GL_LINEAR); checkGLError(); } @@ -1288,7 +1314,8 @@ void GLCompiledProgram::addUniqueAttribute(ShaderSpecAttribute newAttribute) { return; } } - attributes.push_back(GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, -1, nullptr, nullptr}); + attributes.push_back( + GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, -1, nullptr, nullptr}); } void GLCompiledProgram::addUniqueUniform(ShaderSpecUniform newUniform) { @@ -1309,8 +1336,7 @@ void GLCompiledProgram::addUniqueTexture(ShaderSpecTexture newTexture) { if (t.name == newTexture.name) { // if it occurs twice, confirm that the occurences match - if (t.type != newTexture.type) - exception("texture " + t.name + " appears twice in program with different types"); + if (t.type != newTexture.type) exception("texture " + t.name + " appears twice in program with different types"); return; } @@ -1367,7 +1393,8 @@ void GLShaderProgram::createBuffers() { checkGLError(); } -void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source) { +void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, + ManagedBufferBase* source) { bindVAO(); checkGLError(); @@ -2103,7 +2130,8 @@ void GLShaderProgram::setTextureFromBuffer(std::string name, TextureBuffer* text (bufDim == 3 && t.type == ShaderTextureType::Texture3D); if (!typeMatches) { throw std::invalid_argument("Tried to use texture " + name + " with mismatched type " + - shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + "D texture buffer"); + shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + + "D texture buffer"); } t.textureBuffer = dynamic_cast(textureBuffer); @@ -2316,7 +2344,7 @@ void GLShaderProgram::validateData() { // Validate drawCount. if (drawCount == INVALID_IND_32) { - throw std::invalid_argument( "drawCount has not been set; call setDrawCount() before drawing"); + throw std::invalid_argument("drawCount has not been set; call setDrawCount() before drawing"); } if (useIndex) { if (indexBuffer->getBufferSize() < static_cast(drawCount)) @@ -2327,11 +2355,12 @@ void GLShaderProgram::validateData() { if (a.location == -1) continue; int compatCount = renderDataTypeCountCompatbility(a.type, a.buff->getType()); if (a.buff->getBufferSize() / static_cast(compatCount) < static_cast(drawCount)) - throw std::invalid_argument("Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + - ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); + throw std::invalid_argument( + "Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + + ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); } } - + // Check instanced (if applicable) if (drawMode == DrawMode::TrianglesInstanced || drawMode == DrawMode::TriangleStripInstanced) { if (instanceCount == INVALID_IND_32) { @@ -2834,8 +2863,7 @@ void GLEngine::populateDefaultShadersAndRules() { registerShaderRule("PREMULTIPLY_LIT_COLOR", PREMULTIPLY_LIT_COLOR); registerShaderRule("CULL_POS_FROM_VIEW", CULL_POS_FROM_VIEW); registerShaderRule("PROJ_AND_INV_PROJ_MAT", PROJ_AND_INV_PROJ_MAT); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC); + registerShaderRule("BUILD_RAY_FOR_FRAGMENT_DYNAMIC", BUILD_RAY_FOR_FRAGMENT_DYNAMIC); // Lighting and shading things registerShaderRule("LIGHT_MATCAP", LIGHT_MATCAP); diff --git a/src/render/opengl/gl_engine_egl.cpp b/src/render/opengl/gl_engine_egl.cpp index ad8dece6..3a4aea5d 100644 --- a/src/render/opengl/gl_engine_egl.cpp +++ b/src/render/opengl/gl_engine_egl.cpp @@ -254,8 +254,7 @@ void GLEngineEGL::initialize() { { std::stringstream ss; - ss << "Backend: openGL3_egl -- " - << "Loaded openGL version: " << glGetString(GL_VERSION) << " -- " + ss << "Backend: openGL3_egl -- " << "Loaded openGL version: " << glGetString(GL_VERSION) << " -- " << "EGL version: " << majorVer << "." << minorVer; info(0, ss.str()); } @@ -588,9 +587,7 @@ void GLEngineEGL::updateWindowSize(bool force) { void GLEngineEGL::applyWindowSize() { view::bufferWidth = view::windowWidth; view::bufferHeight = view::windowHeight; - - render::engine->resizeScreenBuffers(); - render::engine->setScreenBufferViewports(); + render::engine->resizeScreenBuffersAndSetViewports(); } diff --git a/src/render/opengl/gl_engine_glfw.cpp b/src/render/opengl/gl_engine_glfw.cpp index dceb0148..6ae8f220 100644 --- a/src/render/opengl/gl_engine_glfw.cpp +++ b/src/render/opengl/gl_engine_glfw.cpp @@ -108,8 +108,7 @@ void GLEngineGLFW::initialize() { { std::stringstream ss; - ss << "Backend: openGL3_glfw -- " - << "Loaded openGL version: " << glGetString(GL_VERSION); + ss << "Backend: openGL3_glfw -- " << "Loaded openGL version: " << glGetString(GL_VERSION); info(0, ss.str()); } @@ -329,9 +328,7 @@ void GLEngineGLFW::updateWindowSize(bool force) { view::bufferHeight = newBufferHeight; view::windowWidth = newWindowWidth; view::windowHeight = newWindowHeight; - - render::engine->resizeScreenBuffers(); - render::engine->setScreenBufferViewports(); + render::engine->resizeScreenBuffersAndSetViewports(); } } diff --git a/src/render/opengl/shaders/rules.cpp b/src/render/opengl/shaders/rules.cpp index 5bc7fcbd..b5b0ab04 100644 --- a/src/render/opengl/shaders/rules.cpp +++ b/src/render/opengl/shaders/rules.cpp @@ -465,38 +465,31 @@ const ShaderReplacementRule CULL_POS_FROM_VIEW ( /* textures */ {} ); -const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE( - /* rule name */ "BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", +// A combined rule that uses a uniform u_isPerspective to select between perspective and orthographic ray building at +// runtime. +const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_DYNAMIC( + /* rule name */ "BUILD_RAY_FOR_FRAGMENT_DYNAMIC", { /* replacement sources */ {"FRAG_DECLARATIONS", R"( + uniform int u_isPerspective; void buildRayForFragmentPerspective(vec4 viewport, vec2 depthRange, mat4 projMat, mat4 invProjMat, vec4 fragCoord, out vec3 rayStart, out vec3 rayDir); - )"}, - {"BUILD_RAY_FOR_FRAGMENT", R"( - buildRayForFragmentPerspective(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); - )"}, - {"GEOM_CONSTRUCT_VECTOR_TO_CAMERA_IN_VIEW_SPACE", R"( - vec3 dirToCam = normalize(-gl_in[0].gl_Position.xyz); - )"} - }, - /* uniforms */ {}, - /* attributes */ {}, - /* textures */ {} -); - -const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC( - /* rule name */ "BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", - { /* replacement sources */ - {"FRAG_DECLARATIONS", R"( void buildRayForFragmentOrthographic(vec4 viewport, vec2 depthRange, mat4 projMat, mat4 invProjMat, vec4 fragCoord, out vec3 rayStart, out vec3 rayDir); )"}, {"BUILD_RAY_FOR_FRAGMENT", R"( - buildRayForFragmentOrthographic(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); + if (u_isPerspective != 0) { + buildRayForFragmentPerspective(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); + } else { + buildRayForFragmentOrthographic(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); + } + )"}, + {"GEOM_DECLARATIONS", R"( + uniform int u_isPerspective; )"}, {"GEOM_CONSTRUCT_VECTOR_TO_CAMERA_IN_VIEW_SPACE", R"( - vec3 dirToCam = vec3(0.0, 0.0, 1.0); + vec3 dirToCam = (u_isPerspective != 0) ? normalize(-gl_in[0].gl_Position.xyz) : vec3(0.0, 0.0, 1.0); )"} }, - /* uniforms */ {}, + /* uniforms */ {{"u_isPerspective", RenderDataType::Int}}, /* attributes */ {}, /* textures */ {} ); diff --git a/src/sparse_volume_grid.cpp b/src/sparse_volume_grid.cpp index 27c86a3e..6106baac 100644 --- a/src/sparse_volume_grid.cpp +++ b/src/sparse_volume_grid.cpp @@ -440,9 +440,9 @@ void SparseVolumeGrid::ensureWireframeProgramsPrepared() { { // clang-format off wireframeNodeProgram = render::engine->requestShader("RAYCAST_SPHERE", - render::engine->addMaterialRules(material.get(), + render::engine->addMaterialRules(material.get(), addStructureRules( - { view::getCurrentProjectionModeRaycastRule(), + { "BUILD_RAY_FOR_FRAGMENT_DYNAMIC", wantsCullPosition() ? "SPHERE_CULLPOS_FROM_CENTER" : "", "SHADE_BASECOLOR" } @@ -459,9 +459,9 @@ void SparseVolumeGrid::ensureWireframeProgramsPrepared() { { // clang-format off wireframeEdgeProgram = render::engine->requestShader("RAYCAST_CYLINDER", - render::engine->addMaterialRules(material.get(), + render::engine->addMaterialRules(material.get(), addStructureRules( - { view::getCurrentProjectionModeRaycastRule(), + { "BUILD_RAY_FOR_FRAGMENT_DYNAMIC", wantsCullPosition() ? "CYLINDER_CULLPOS_FROM_MID" : "", "SHADE_BASECOLOR" } diff --git a/src/structure.cpp b/src/structure.cpp index 9e6c3ee2..6d5f17b5 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -14,6 +14,7 @@ namespace polyscope { Structure::Structure(std::string name_, std::string subtypeName_) : name(name_), subtypeName(subtypeName_), enabled(subtypeName + "#" + name + "#enabled", true), + viewportVisibilityMask(subtypeName + "#" + name + "#viewportVisibilityMask", ~uint64_t(0)), objectTransform(subtypeName + "#" + name + "#object_transform", glm::mat4(1.0)), transparency(subtypeName + "#" + name + "#transparency", 1.0), transformGizmo(subtypeName + "#" + name + "#transform_gizmo", &objectTransform.get(), &objectTransform), @@ -25,7 +26,7 @@ Structure::Structure(std::string name_, std::string subtypeName_) validateName(name); } -Structure::~Structure() {}; +Structure::~Structure(){}; Structure* Structure::setEnabled(bool newEnabled) { if (newEnabled == isEnabled()) return this; @@ -53,6 +54,42 @@ void Structure::addToGroup(std::string groupName) { addToGroup(*getGroup(groupNa void Structure::addToGroup(Group& group) { group.addChildStructure(*this); } +void Structure::setViewportVisibility(int32_t viewportInd, bool visible) { + if (viewportInd < 0 || viewportInd >= view::maxNumViewports) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } + uint64_t mask = viewportVisibilityMask.get(); + if (visible) { + mask |= (uint64_t(1) << viewportInd); + } else { + mask &= ~(uint64_t(1) << viewportInd); + } + viewportVisibilityMask = mask; + requestRedraw(); +} + +void Structure::setViewportVisibilityAll(bool visible) { + viewportVisibilityMask = visible ? ~uint64_t(0) : uint64_t(0); + requestRedraw(); +} + +void Structure::setViewportVisibilityExclusive(int32_t viewportInd) { + if (viewportInd < 0 || viewportInd >= view::maxNumViewports) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } + viewportVisibilityMask = uint64_t(1) << viewportInd; + requestRedraw(); +} + +bool Structure::getViewportVisibility(int32_t viewportInd) { + if (viewportInd < 0) viewportInd = view::getActiveViewportIndex(); + if (viewportInd < 0 || viewportInd >= view::maxNumViewports) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } + return (viewportVisibilityMask.get() >> viewportInd) & uint64_t(1); +} + + void Structure::buildUI() { ImGui::PushID(name.c_str()); // ensure there are no conflicts with // identically-named labels @@ -131,6 +168,19 @@ void Structure::buildUI() { ImGui::EndMenu(); } + // Viewport visibility (only shown when multiple viewports exist) + int nViewports = view::getNumViewports(); + if (nViewports > 1 && ImGui::BeginMenu("Viewport Visibility")) { + if (ImGui::MenuItem("Show in all")) setViewportVisibilityAll(true); + if (ImGui::MenuItem("Hide in all")) setViewportVisibilityAll(false); + ImGui::Separator(); + for (int i = 0; i < nViewports; i++) { + bool vis = getViewportVisibility(i); + if (ImGui::MenuItem(("Viewport " + std::to_string(i)).c_str(), NULL, vis)) setViewportVisibility(i, !vis); + } + ImGui::EndMenu(); + } + buildStructureOptionsUI(); // Do any structure-specific stuff here @@ -275,6 +325,11 @@ void Structure::setStructureUniforms(render::ShaderProgram& p) { p.setUniform("u_projMatrix", glm::value_ptr(projMat)); } + if (p.hasUniform("u_isPerspective")) { + int isPerspective = (view::projectionMode == ProjectionMode::Perspective) ? 1 : 0; + p.setUniform("u_isPerspective", isPerspective); + } + if (render::engine->transparencyEnabled()) { if (p.hasUniform("u_transparency")) { p.setUniform("u_transparency", transparency.get()); @@ -286,10 +341,8 @@ void Structure::setStructureUniforms(render::ShaderProgram& p) { p.setUniform("u_viewportDim", viewportDim); } - // Attach the min depth texture, if needed - // (note that this design is somewhat lazy wrt to the name of the function: it sets a texture, not a uniform, and - // only actually does anything once on initialization) - if (render::engine->transparencyEnabled() && p.hasTexture("t_minDepth") && !p.textureIsSet("t_minDepth")) { + // Attach the min depth texture, if needed (rebind each draw since sceneDepthMin changes per-viewport) + if (render::engine->transparencyEnabled() && p.hasTexture("t_minDepth")) { p.setTextureFromBuffer("t_minDepth", render::engine->sceneDepthMin.get()); } } diff --git a/src/transformation_gizmo.cpp b/src/transformation_gizmo.cpp index 6d6e2ddd..5ce2f6e6 100644 --- a/src/transformation_gizmo.cpp +++ b/src/transformation_gizmo.cpp @@ -42,11 +42,17 @@ void TransformationGizmo::draw() { ImGuizmo::PushID(uniquePrefix().c_str()); - ImGuiIO& io = ImGui::GetIO(); - ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y); - - // styling options - ImGuizmo::SetGizmoSizeClipSpace(gizmoSize.get() * 0.08f * options::uiScale); + glm::vec4 svRect = view::getViewportImGuiRect(); + ImGuizmo::SetRect(svRect.x, svRect.y, svRect.z, svRect.w); + + // Scale up to compensate for the viewport being smaller than the full window. + // ImGuizmo maps clip-space size independently by viewport width and height, so a single scalar + // can't match both axes when the viewport aspect ratio differs from the full window. The geometric + // mean minimizes the asymmetry between X and Y. + float fullArea = (float)view::windowWidth * (float)view::windowHeight; + float svArea = svRect.z * svRect.w; + float sizeScale = std::sqrt(fullArea / svArea); + ImGuizmo::SetGizmoSizeClipSpace(gizmoSize.get() * 0.08f * options::uiScale * sizeScale); ImGuizmo::Style& style = ImGuizmo::GetStyle(); style.HatchedAxisLineThickness = 0.; // disable the hatching affect along the negative axis diff --git a/src/view.cpp b/src/view.cpp index 1baed9d3..2b337d14 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -43,6 +43,7 @@ glm::vec3& flightTargetViewT = state::globalContext.flightTargetViewT; glm::vec3& flightInitialViewT = state::globalContext.flightInitialViewT; float& flightTargetFov = state::globalContext.flightTargetFov; float& flightInitialFov = state::globalContext.flightInitialFov; +int& activeViewportIndex = state::globalContext.activeViewportIndex; // Default values @@ -64,6 +65,7 @@ float overrideFarClipRelative = defaultFarClipRatio; namespace { // anonymous helpers + // A default pairing of directions to fall back on when something goes wrong. const std::vector> defaultUpFrontPairs{ {UpDir::NegXUp, FrontDir::NegYFront}, {UpDir::XUp, FrontDir::YFront}, {UpDir::NegYUp, FrontDir::NegZFront}, @@ -113,20 +115,94 @@ glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds) { return bufferIndsToScreenCoords(bufferInds.x, bufferInds.y); } -std::string getCurrentProjectionModeRaycastRule() { - // This is related to the render engine, it returns the name of the - // shader rule which constructs rays for raycasting-based rendering. - // See rules.h +// NOTE: All of the helpers here follow the conventions in the big note in view.h: screen coords and buffer inds both +// have y=0 at the TOP, and differ only by the DPI scale factor. "Global" coordinates have their origin at the top-left +// of the whole window, "local" (viewport) coordinates have their origin at the top-left of a particular viewport. + +namespace { +// The top-left corner of a viewport, in global buffer inds (y-from-top) +glm::ivec2 viewportOriginBufferInds(const ViewParameters& vp) { return glm::ivec2(vp.viewportPosX, vp.viewportPosY); } +}; // namespace + +// local screen coords --> local buffer inds +std::tuple screenCoordsToBufferIndsViewport(glm::vec2 screenCoords, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(viewportInd); + + int xPos = (screenCoords.x * view::bufferWidth) / view::windowWidth; + int yPos = (screenCoords.y * view::bufferHeight) / view::windowHeight; + + // clamp to lie in the viewport + xPos = std::max(std::min(xPos, vp.viewportBufferWidth - 1), 0); + yPos = std::max(std::min(yPos, vp.viewportBufferHeight - 1), 0); + + return std::tuple(xPos, yPos); +} + +glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd) { + glm::ivec2 out; + std::tie(out.x, out.y) = screenCoordsToBufferIndsViewport(screenCoords, viewportInd); + return out; +} + +// local buffer inds --> local screen coords +glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd) { + // (only a change of scale, so the viewport is not actually needed here, but we keep the argument to mirror the + // function above) + return bufferIndsToScreenCoords(xPos, yPos); +} - switch (view::projectionMode) { - case ProjectionMode::Perspective: - return "BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE"; - case ProjectionMode::Orthographic: - return "BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC"; +glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd) { + return bufferIndsToScreenCoordsViewport(bufferInds.x, bufferInds.y, viewportInd); +} + +std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoords) { + int32_t viewportInd = screenCoordsToViewportInd(screenCoords); + glm::vec4 rect = getViewportImGuiRect(viewportInd); // {x, y, width, height} in global screen coords + glm::vec2 localCoords{std::max(std::min(screenCoords.x - rect.x, rect.z), 0.f), + std::max(std::min(screenCoords.y - rect.y, rect.w), 0.f)}; + return {localCoords, viewportInd}; +} + +std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds) { + int32_t viewportInd = bufferIndsToViewportInd(bufferInds); + const ViewParameters& vp = getViewportParameters(viewportInd); + glm::ivec2 localInds = bufferInds - viewportOriginBufferInds(vp); + localInds.x = std::max(std::min(localInds.x, vp.viewportBufferWidth - 1), 0); + localInds.y = std::max(std::min(localInds.y, vp.viewportBufferHeight - 1), 0); + return {localInds, viewportInd}; +} + +glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd) { + glm::vec4 rect = getViewportImGuiRect(viewportInd); // {x, y, width, height} in global screen coords + return glm::vec2{rect.x + screenCoords.x, rect.y + screenCoords.y}; +} + +glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(viewportInd); + return viewportOriginBufferInds(vp) + bufferInds; +} + +int32_t bufferIndsToViewportInd(glm::ivec2 bufferInds) { + for (int32_t i = getNumViewports() - 1; i >= 0; i--) { + // go back-to-front, so we report the topmost matching viewport + const ViewParameters& vp = getViewportParameters(i); + glm::ivec2 origin = viewportOriginBufferInds(vp); // (y-from-top, like the input) + if (bufferInds.x >= origin.x && bufferInds.x < origin.x + vp.viewportBufferWidth && bufferInds.y >= origin.y && + bufferInds.y < origin.y + vp.viewportBufferHeight) { + return i; + } } - return ""; + + return 0; // returning 0 is the least evil option if we miss somehow due to cracks or invalid input +} + +int32_t screenCoordsToViewportInd(glm::vec2 screenCoords) { + return bufferIndsToViewportInd(screenCoordsToBufferIndsVec(screenCoords)); } + void processRotate(glm::vec2 startP, glm::vec2 endP) { if (startP == endP) { @@ -256,8 +332,9 @@ void processRotate(glm::vec2 startP, glm::vec2 endP) { } } - requestRedraw(); immediatelyEndFlight(); + propagateViewUpdatesToViewports(); + requestRedraw(); } void processTranslate(glm::vec2 delta) { @@ -285,14 +362,16 @@ void processTranslate(glm::vec2 delta) { projectCenterToBeValidForView(); - requestRedraw(); immediatelyEndFlight(); + propagateViewUpdatesToViewports(); + requestRedraw(); } void processClipPlaneShift(float amount) { if (amount == 0.0) return; // Adjust the near clipping plane nearClip += .03 * amount * nearClip; + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -332,6 +411,7 @@ void processZoom(float amount) { immediatelyEndFlight(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -381,6 +461,7 @@ void processKeyboardNavigation(ImGuiIO& io) { if (hasMovement) { immediatelyEndFlight(); + propagateViewUpdatesToViewports(); requestRedraw(); } } @@ -536,6 +617,8 @@ void updateViewAndChangeNavigationStyle(NavigateStyle newStyle, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToViewports(); } void updateViewAndChangeUpDir(UpDir newUpDir, bool flyTo) { @@ -571,6 +654,8 @@ void updateViewAndChangeUpDir(UpDir newUpDir, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToViewports(); } void updateViewAndChangeFrontDir(FrontDir newFrontDir, bool flyTo) { @@ -595,6 +680,8 @@ void updateViewAndChangeFrontDir(FrontDir newFrontDir, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToViewports(); } void setViewCenterAndLookAt(glm::vec3 newCenter, bool flyTo) { @@ -631,6 +718,8 @@ void setViewCenterAndLookAt(glm::vec3 newCenter, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToViewports(); } void setViewCenterAndProject(glm::vec3 newCenter) { @@ -667,10 +756,12 @@ void lookAt(glm::vec3 cameraLocation, glm::vec3 target, glm::vec3 upDir, bool fl if (flyTo) { + propagateViewUpdatesToViewports(); startFlightTo(targetView, fov); } else { viewMat = targetView; projectCenterToBeValidForView(); + propagateViewUpdatesToViewports(); requestRedraw(); } } @@ -693,12 +784,14 @@ void setViewToCamera(const CameraParameters& p) { // aspectRatio = p.focalLengths.x / p.focalLengths.y; // TODO should be // flipped? projectCenterToBeValidForView(); + propagateViewUpdatesToViewports(); + requestRedraw(); } CameraParameters getCameraParametersForCurrentView() { ensureViewValid(); - float aspectRatio = (float)bufferWidth / bufferHeight; + float aspectRatio = getAspectRatioWidthOverHeight(); return CameraParameters(CameraIntrinsics::fromFoVDegVerticalAndAspect(fov, aspectRatio), CameraExtrinsics::fromMatrix(viewMat)); } @@ -706,6 +799,7 @@ CameraParameters getCameraParametersForCurrentView() { void setCameraViewMatrix(glm::mat4 mat) { viewMat = mat; projectCenterToBeValidForView(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -713,6 +807,7 @@ glm::mat4 getCameraViewMatrix() { return viewMat; } void setVerticalFieldOfViewDegrees(float newVal) { view::fov = newVal; + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -720,8 +815,7 @@ ProjectionMode getProjectionMode() { return projectionMode; } void setProjectionMode(ProjectionMode newMode) { projectionMode = newMode; - internal::lazy::projectionMode = newMode; // update the lazy property right now, so we don't pay for a refresh twice - refresh(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -729,18 +823,23 @@ void setProjectionMode(ProjectionMode newMode) { ViewRelativeMode getViewRelativeMode() { return viewRelativeMode; } void setViewRelativeMode(ViewRelativeMode newMode) { viewRelativeMode = newMode; + propagateViewUpdatesToViewports(); requestRedraw(); } void setClipPlanes(float newNearClip, float newFarClip) { nearClip = newNearClip; farClip = newFarClip; + propagateViewUpdatesToViewports(); requestRedraw(); } std::tuple getClipPlanes() { return std::tuple(nearClip, farClip); } float getVerticalFieldOfViewDegrees() { return view::fov; } -float getAspectRatioWidthOverHeight() { return (float)bufferWidth / bufferHeight; } +float getAspectRatioWidthOverHeight() { + int h = getActiveViewportBufferHeight(); + return (h > 0) ? (float)getActiveViewportBufferWidth() / h : 1.0f; +} glm::mat4 getCameraPerspectiveMatrix() { @@ -754,7 +853,7 @@ glm::mat4 getCameraPerspectiveMatrix() { } float fovRad = glm::radians(fov); - float aspectRatio = (float)bufferWidth / bufferHeight; + float aspectRatio = getAspectRatioWidthOverHeight(); switch (projectionMode) { case ProjectionMode::Perspective: { return glm::perspective(fovRad, aspectRatio, absNearClip, absFarClip); @@ -770,7 +869,6 @@ glm::mat4 getCameraPerspectiveMatrix() { return glm::mat4(1.0f); // unreachable } - glm::vec3 getCameraWorldPosition() { // This will work no matter how the view matrix is constructed... glm::mat4 invViewMat = inverse(getCameraViewMatrix()); @@ -803,34 +901,87 @@ glm::vec3 getLookVec() { return Rt * glm::vec3(0.0, 0.0, -1.0); } -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords) { +// NOTE: There are two flavors of the ray/position helpers below, see the note in view.h: +// - the plain versions (like screenCoordsToWorldRay()) take GLOBAL coordinates on the whole window, find the viewport +// that contains them, and call the viewport version. +// - the viewport versions (like viewportScreenCoordsToWorldRay()) take coordinates LOCAL to a viewport, and use the +// camera of that viewport, which might not be the active one. + +namespace { +// Find the viewport that contains some global screen coords, and the coords in that viewport's local frame. +// Unlike screenCoordsGlobalToViewport(), the local coords are NOT clamped to the viewport. The plain ray functions +// don't clamp, so points outside the window still give a ray, like they always did when using a single viewport. +std::tuple globalScreenCoordsToLocalUnclamped(glm::vec2 screenCoords) { + int32_t viewportInd = screenCoordsToViewportInd(screenCoords); + glm::vec4 rect = getViewportImGuiRect(viewportInd); // {x, y, width, height} in global screen coords + return std::tuple(glm::vec2(screenCoords.x - rect.x, screenCoords.y - rect.y), viewportInd); +} + +// Same, for buffer coords +std::tuple globalBufferCoordsToLocalUnclamped(glm::vec2 bufferCoords) { + int32_t viewportInd = bufferIndsToViewportInd(glm::ivec2(bufferCoords)); + glm::ivec2 origin = viewportOriginBufferInds(getViewportParameters(viewportInd)); + return std::tuple(bufferCoords - glm::vec2(origin), viewportInd); +} + +// The workhorse for rays from buffer coords +glm::vec3 localBufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t viewportInd) { + int32_t prevViewport = getActiveViewportIndex(); + bool switched = (viewportInd >= 0 && viewportInd != prevViewport); + if (switched) activateViewport(viewportInd); + const ViewParameters& vp = getViewportParameters(); glm::mat4 view = getCameraViewMatrix(); glm::mat4 proj = getCameraPerspectiveMatrix(); - glm::vec4 viewport = {0., 0., view::windowWidth, view::windowHeight}; + glm::vec4 viewport = {0., 0., vp.viewportBufferWidth, vp.viewportBufferHeight}; - glm::vec3 screenPos3{screenCoords.x, view::windowHeight - screenCoords.y, 0.}; + glm::vec3 screenPos3{bufferCoords.x, vp.viewportBufferHeight - bufferCoords.y, 0.}; glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); - glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); + glm::vec3 worldRayDir = glm::normalize(worldPos - getCameraWorldPosition()); + if (switched) activateViewport(prevViewport); return worldRayDir; } +}; // namespace -glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds) { return bufferCoordsToWorldRay(bufferInds); } - -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords) { +glm::vec3 viewportScreenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd) { + int32_t prevViewport = getActiveViewportIndex(); + bool switched = (viewportInd >= 0 && viewportInd != prevViewport); + if (switched) activateViewport(viewportInd); + const ViewParameters& vp = getViewportParameters(); glm::mat4 view = getCameraViewMatrix(); glm::mat4 proj = getCameraPerspectiveMatrix(); - glm::vec4 viewport = {0., 0., view::bufferWidth, view::bufferHeight}; + glm::vec4 viewport = {0., 0., vp.viewportWindowWidth, vp.viewportWindowHeight}; - glm::vec3 screenPos3{bufferCoords.x, view::bufferHeight - bufferCoords.y, 0.}; + glm::vec3 screenPos3{screenCoords.x, vp.viewportWindowHeight - screenCoords.y, 0.}; glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); - glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); + glm::vec3 worldRayDir = glm::normalize(worldPos - getCameraWorldPosition()); + if (switched) activateViewport(prevViewport); return worldRayDir; } +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords) { + glm::vec2 localScreenCoords; + int32_t viewportInd; + std::tie(localScreenCoords, viewportInd) = globalScreenCoordsToLocalUnclamped(screenCoords); + return viewportScreenCoordsToWorldRay(localScreenCoords, viewportInd); +} + +glm::vec3 viewportBufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd) { + return localBufferCoordsToWorldRay(glm::vec2(bufferInds), viewportInd); +} + +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds) { return bufferCoordsToWorldRay(glm::vec2(bufferInds)); } + +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords) { + glm::vec2 localBufferCoords; + int32_t viewportInd; + std::tie(localBufferCoords, viewportInd) = globalBufferCoordsToLocalUnclamped(bufferCoords); + return localBufferCoordsToWorldRay(localBufferCoords, viewportInd); +} + std::tuple computeClipPlanes() { float s = computeRelativeMotionScale(); float absFarClip = farClip * s; @@ -846,6 +997,13 @@ std::tuple computeClipPlanes() { } glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth) { + glm::vec2 localScreenCoords; + int32_t viewportInd; + std::tie(localScreenCoords, viewportInd) = globalScreenCoordsToLocalUnclamped(screenCoords); + return viewportScreenCoordsAndDepthToWorldPosition(localScreenCoords, clipDepth, viewportInd); +} + +glm::vec3 viewportScreenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t viewportInd) { if (clipDepth == 1.) { // if we didn't hit anything in the depth buffer, just return infinity @@ -853,16 +1011,18 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip return glm::vec3{inf, inf, inf}; } + int32_t prevViewport = getActiveViewportIndex(); + bool switched = (viewportInd >= 0 && viewportInd != prevViewport); + if (switched) activateViewport(viewportInd); - glm::mat4 view = getCameraViewMatrix(); - glm::mat4 viewInv = glm::inverse(view); + const ViewParameters& vp = getViewportParameters(); + glm::mat4 viewInv = glm::inverse(getCameraViewMatrix()); glm::mat4 proj = getCameraPerspectiveMatrix(); glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently - // convert depth to world units - glm::vec2 screenPos{screenCoords.x / static_cast(view::windowWidth), - 1.f - screenCoords.y / static_cast(view::windowHeight)}; + // Normalize the local screen coords (y-from-top) to [0,1], with y flipped to be y-from-bottom as in clip space + glm::vec2 screenPos{screenCoords.x / vp.viewportWindowWidth, 1.f - screenCoords.y / vp.viewportWindowHeight}; float z = clipDepth * 2.0f - 1.0f; glm::vec4 clipPos = glm::vec4(screenPos * 2.0f - 1.0f, z, 1.0f); glm::vec4 viewPos = projInv * clipPos; @@ -871,6 +1031,7 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip glm::vec4 worldPos = viewInv * viewPos; worldPos /= worldPos.w; + if (switched) activateViewport(prevViewport); return glm::vec3(worldPos); } @@ -904,9 +1065,16 @@ void startFlightTo(const glm::mat4& T, float targetFov, float flightLengthInSeco flightTargetFov = targetFov; midflight = true; + + propagateViewUpdatesToViewports(); + requestRedraw(); } -void immediatelyEndFlight() { midflight = false; } +void immediatelyEndFlight() { + midflight = false; + propagateViewUpdatesToViewports(); + requestRedraw(); +} void updateFlight() { @@ -1096,8 +1264,11 @@ void setViewFromJson(std::string jsonData, bool flyTo) { } } + propagateViewUpdatesToViewports(); + } catch (...) { // If anything goes wrong parsing, just give up + propagateViewUpdatesToViewports(); return; } } @@ -1317,6 +1488,7 @@ void buildViewGui() { float fovF = fov; if (ImGui::SliderFloat(" Field of View", &fovF, minFov, maxFov, "%.2f deg")) { fov = fovF; + propagateViewUpdatesToViewports(); requestRedraw(); }; @@ -1338,10 +1510,12 @@ void buildViewGui() { if (ImGui::TreeNode("Clip Planes")) { if (ImGui::SliderFloat("Near", &nearClip, 0., 10., "%.5f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat)) { + propagateViewUpdatesToViewports(); requestRedraw(); } if (ImGui::SliderFloat("Far", &farClip, 1., 10000., "%.2f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat)) { + propagateViewUpdatesToViewports(); requestRedraw(); } float absNearClip, absFarClip; @@ -1463,5 +1637,282 @@ void setWindowResizable(bool isResizable) { bool getWindowResizable() { return windowResizable; } +// == Viewport helpers + +namespace { +void packCurrentViewportParametersToIndex(int idx) { + if (idx < 0) return; + + ViewParameters& vp = state::globalContext.viewportParameters[idx]; + vp.style = style; + vp.upDir = upDir; + vp.frontDir = frontDir; + vp.moveScale = moveScale; + vp.viewRelativeMode = viewRelativeMode; + vp.nearClip = nearClip; + vp.farClip = farClip; + vp.bgColor = bgColor; + vp.viewMat = viewMat; + vp.fov = fov; + vp.viewCenter = viewCenter; + vp.projectionMode = projectionMode; + vp.midflight = midflight; + vp.flightStartTime = flightStartTime; + vp.flightEndTime = flightEndTime; + vp.flightTargetViewR = flightTargetViewR; + vp.flightInitialViewR = flightInitialViewR; + vp.flightTargetViewT = flightTargetViewT; + vp.flightInitialViewT = flightInitialViewT; + vp.flightTargetFov = flightTargetFov; + vp.flightInitialFov = flightInitialFov; +} + +void unpackCurrentViewportParametersFromActive() { + if (activeViewportIndex < 0) return; + + const ViewParameters& vp = state::globalContext.viewportParameters[activeViewportIndex]; + style = vp.style; + upDir = vp.upDir; + frontDir = vp.frontDir; + moveScale = vp.moveScale; + viewRelativeMode = vp.viewRelativeMode; + nearClip = vp.nearClip; + farClip = vp.farClip; + bgColor = vp.bgColor; + viewMat = vp.viewMat; + fov = vp.fov; + viewCenter = vp.viewCenter; + projectionMode = vp.projectionMode; + midflight = vp.midflight; + flightStartTime = vp.flightStartTime; + flightEndTime = vp.flightEndTime; + flightTargetViewR = vp.flightTargetViewR; + flightInitialViewR = vp.flightInitialViewR; + flightTargetViewT = vp.flightTargetViewT; + flightInitialViewT = vp.flightInitialViewT; + flightTargetFov = vp.flightTargetFov; + flightInitialFov = vp.flightInitialFov; +} + +} // namespace + + +int getActiveViewportIndex() { return activeViewportIndex; } + +int getActiveViewportBufferWidth() { + return state::globalContext.viewportParameters[activeViewportIndex].viewportBufferWidth; +} + +int getActiveViewportBufferHeight() { + return state::globalContext.viewportParameters[activeViewportIndex].viewportBufferHeight; +} + +glm::vec4 getViewportImGuiRect(int32_t viewportInd) { + if (viewportInd < 0) viewportInd = activeViewportIndex; + const ViewParameters& vp = getViewportParameters(viewportInd); + glm::vec2 origin = bufferIndsToScreenCoords(vp.viewportPosX, vp.viewportPosY); + return glm::vec4(origin.x, origin.y, vp.viewportWindowWidth, vp.viewportWindowHeight); +} + +void activateViewport(int viewportInd) { + if (viewportInd < 0 || viewportInd >= getNumViewports()) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } + packCurrentViewportParametersToIndex(activeViewportIndex); + activeViewportIndex = viewportInd; + unpackCurrentViewportParametersFromActive(); +} + +int getNumViewports() { return state::globalContext.viewportParameters.size(); } + +void setNumViewports(int count) { + checkInitialized(); + if (count <= 0) error("Invalid viewport count " + std::to_string(count)); + if (count > maxNumViewports) error("At most " + std::to_string(maxNumViewports) + " viewports are supported."); + + + // save current parameters + if (getNumViewports() > 0) { + packCurrentViewportParametersToIndex(activeViewportIndex); + } + + int oldCount = getNumViewports(); + state::globalContext.viewportParameters.resize(count); + + // Copy the current active view parameters into all new views to initialize them. + // Newly added viewports start at zero size until positioned via setActiveViewportRelativeSize() + // so allocating many small viewports never transiently allocates full-window buffers for each. + for (int i = oldCount; i < count; i++) { + packCurrentViewportParametersToIndex(i); + state::globalContext.viewportParameters[i].viewportRelativePosX = 0.0f; + state::globalContext.viewportParameters[i].viewportRelativePosY = 0.0f; + state::globalContext.viewportParameters[i].viewportRelativeWidth = 0.0f; + state::globalContext.viewportParameters[i].viewportRelativeHeight = 0.0f; + } + + // Clamp active index to valid range after shrinking, and unpack BEFORE resizing buffers + // (which packs the active viewport). + if (activeViewportIndex >= count) { + activeViewportIndex = count - 1; + unpackCurrentViewportParametersFromActive(); + } + + render::engine->ensureSceneTargetsAllocated(count); + render::engine->setActiveSceneTarget(activeViewportIndex); + + requestRedraw(); +} + +void setActiveViewportRelativeLocation(float posX, float posY) { + checkInitialized(); + if (posX < 0 || posX > 1 || posY < 0 || posY > 1) { + error("Invalid viewport location " + std::to_string(posX) + " x " + std::to_string(posY)); + } + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativePosX = posX; + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativePosY = posY; + render::engine->resizeScreenBuffersAndSetViewports(); + requestRedraw(); +} + +void setActiveViewportRelativeSize(float width, float height) { + checkInitialized(); + if (width < 0 || width > 1 || height < 0 || height > 1) { + error("Invalid viewport size " + std::to_string(width) + " x " + std::to_string(height)); + } + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativeWidth = width; + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativeHeight = height; + render::engine->resizeScreenBuffersAndSetViewports(); + requestRedraw(); +} + +bool getViewportsShareNavigation() { return state::globalContext.viewportsShareNavigation; } + +void setViewportsShareNavigation(bool shareNavigation) { + state::globalContext.viewportsShareNavigation = shareNavigation; + propagateViewUpdatesToViewports(); + requestRedraw(); +} + +void createViewportGrid(int gridWidth, int gridHeight) { + // make sure the dimensions are reasonable + if (gridWidth <= 0 || gridHeight <= 0) { + error("Invalid viewport grid dimensions " + std::to_string(gridWidth) + " x " + std::to_string(gridHeight)); + } + + setNumViewports(gridWidth * gridHeight); + + // initialize all viewports to the same parameters as the current active view, so they start in a known state + for (int i = 0; i < getNumViewports(); i++) { + packCurrentViewportParametersToIndex(i); + } + + float cellW = 1.0f / gridWidth; + float cellH = 1.0f / gridHeight; + for (int i = 0; i < gridHeight; i++) { + for (int j = 0; j < gridWidth; j++) { + int ind = i * gridWidth + j; + ViewParameters& vp = state::globalContext.viewportParameters[ind]; + // note: this intentionally puts the first grid viewport in the upper-left, matching convention from other + // software + vp.viewportRelativePosX = static_cast(j) / gridWidth; + vp.viewportRelativePosY = static_cast(i) / gridHeight; + vp.viewportRelativeWidth = cellW; + vp.viewportRelativeHeight = cellH; + } + } + + activateViewport(0); + render::engine->resizeScreenBuffersAndSetViewports(); + requestRedraw(); +} + +void createInitialViewport() { + state::globalContext.viewportParameters.resize(1); + packCurrentViewportParametersToIndex(0); + activeViewportIndex = 0; + state::globalContext.viewportParameters[0].viewportRelativePosX = 0.0; + state::globalContext.viewportParameters[0].viewportRelativePosY = 0.0; + state::globalContext.viewportParameters[0].viewportRelativeWidth = 1.0; + state::globalContext.viewportParameters[0].viewportRelativeHeight = 1.0; + if (!render::engine) error("Render engine not initialized. You called an internal function at the wrong time."); + render::engine->ensureSceneTargetsAllocated(1); + render::engine->setActiveSceneTarget(0); +} + +void clearViewports() { + state::globalContext.viewportParameters.clear(); + activeViewportIndex = -1; +} + +void validateViewports() { + if (getNumViewports() == 0) + error( + "No viewports of the scene exist. Either viewports were configured wrong, program flow has been called in the " + "wrong order."); +} + +void updateViewportDimensions() { + packCurrentViewportParametersToIndex(activeViewportIndex); // active values are duplicated + for (int32_t iV = 0; iV < getNumViewports(); iV++) { + ViewParameters& vp = state::globalContext.viewportParameters[iV]; + + // Compute pos and size by rounding both edges independently in buffer space, so that adjacent viewports sharing + // a boundary always snap to the same integer pixel (no cracks or overlaps), and derive screen-coord dimensions + // by the DPI scale factor so screen-coord and buffer-ind frames agree exactly. + vp.viewportPosX = (int)std::round(view::bufferWidth * vp.viewportRelativePosX); + vp.viewportPosY = (int)std::round(view::bufferHeight * vp.viewportRelativePosY); + vp.viewportBufferWidth = + (int)std::round(view::bufferWidth * (vp.viewportRelativePosX + vp.viewportRelativeWidth)) - vp.viewportPosX; + vp.viewportBufferHeight = + (int)std::round(view::bufferHeight * (vp.viewportRelativePosY + vp.viewportRelativeHeight)) - vp.viewportPosY; + float scaleX = (view::bufferWidth > 0) ? static_cast(view::windowWidth) / view::bufferWidth : 1.0f; + float scaleY = (view::bufferHeight > 0) ? static_cast(view::windowHeight) / view::bufferHeight : 1.0f; + vp.viewportWindowWidth = vp.viewportBufferWidth * scaleX; + vp.viewportWindowHeight = vp.viewportBufferHeight * scaleY; + } + unpackCurrentViewportParametersFromActive(); +} + +void propagateViewUpdatesToViewports() { + if (!getViewportsShareNavigation()) return; + + for (int32_t iV = 0; iV < getNumViewports(); iV++) { + ViewParameters& vp = state::globalContext.viewportParameters[iV]; + vp.style = style; + vp.upDir = upDir; + vp.frontDir = frontDir; + vp.moveScale = moveScale; + vp.viewRelativeMode = viewRelativeMode; + vp.nearClip = nearClip; + vp.farClip = farClip; + vp.bgColor = bgColor; + vp.viewMat = viewMat; + vp.fov = fov; + vp.viewCenter = viewCenter; + vp.projectionMode = projectionMode; + vp.midflight = midflight; + vp.flightStartTime = flightStartTime; + vp.flightEndTime = flightEndTime; + vp.flightTargetViewR = flightTargetViewR; + vp.flightInitialViewR = flightInitialViewR; + vp.flightTargetViewT = flightTargetViewT; + vp.flightInitialViewT = flightInitialViewT; + vp.flightTargetFov = flightTargetFov; + vp.flightInitialFov = flightInitialFov; + } +} + +const ViewParameters& getViewportParameters(int32_t viewportInd) { + if (viewportInd < 0) viewportInd = activeViewportIndex; + if (viewportInd < 0 || viewportInd >= getNumViewports()) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } + if (viewportInd == activeViewportIndex) { + // write them to the structure in case they have been changed since it was activated + packCurrentViewportParametersToIndex(activeViewportIndex); + } + return state::globalContext.viewportParameters[viewportInd]; +} + } // namespace view } // namespace polyscope diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index 2d9aebf9..e31b11fc 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -237,6 +237,333 @@ TEST_F(PolyscopeTest, NavigationMode) { polyscope::view::setNavigateStyle(polyscope::NavigateStyle::Turntable); // set back to usual default } +TEST_F(PolyscopeTest, ViewportManagement) { + auto psMesh = registerTriangleMesh(); + + // 2x1 grid + polyscope::view::createViewportGrid(2, 1); + EXPECT_EQ(polyscope::view::getNumViewports(), 2); + polyscope::show(3); + + // activateViewport / getActiveViewportIndex + polyscope::view::activateViewport(1); + EXPECT_EQ(polyscope::view::getActiveViewportIndex(), 1); + polyscope::view::activateViewport(0); + EXPECT_EQ(polyscope::view::getActiveViewportIndex(), 0); + + // shared navigation + polyscope::view::setViewportsShareNavigation(true); + EXPECT_TRUE(polyscope::view::getViewportsShareNavigation()); + polyscope::show(3); + + polyscope::view::setViewportsShareNavigation(false); + EXPECT_FALSE(polyscope::view::getViewportsShareNavigation()); + polyscope::show(3); + + // 2x2 grid + polyscope::view::createViewportGrid(2, 2); + EXPECT_EQ(polyscope::view::getNumViewports(), 4); + polyscope::show(3); + + // back to single viewport + polyscope::view::createViewportGrid(1, 1); + EXPECT_EQ(polyscope::view::getNumViewports(), 1); + polyscope::show(3); + + polyscope::view::setViewportsShareNavigation(true); // restore default + polyscope::removeAllStructures(); +} + +TEST_F(PolyscopeTest, ViewportVisibility) { + auto psMesh = registerTriangleMesh(); + + polyscope::view::createViewportGrid(2, 2); // 4 viewports + + // default: visible in all viewports + for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getViewportVisibility(i)); + + // hide in one viewport + psMesh->setViewportVisibility(2, false); + EXPECT_TRUE(psMesh->getViewportVisibility(0)); + EXPECT_TRUE(psMesh->getViewportVisibility(1)); + EXPECT_FALSE(psMesh->getViewportVisibility(2)); + EXPECT_TRUE(psMesh->getViewportVisibility(3)); + + // hide all + psMesh->setViewportVisibilityAll(false); + for (int i = 0; i < 4; i++) EXPECT_FALSE(psMesh->getViewportVisibility(i)); + + // show all + psMesh->setViewportVisibilityAll(true); + for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getViewportVisibility(i)); + + // exclusive: only visible in viewport 1 + psMesh->setViewportVisibilityExclusive(1); + EXPECT_FALSE(psMesh->getViewportVisibility(0)); + EXPECT_TRUE(psMesh->getViewportVisibility(1)); + EXPECT_FALSE(psMesh->getViewportVisibility(2)); + EXPECT_FALSE(psMesh->getViewportVisibility(3)); + + // getViewportVisibility(-1) uses active viewport + polyscope::view::activateViewport(1); + EXPECT_TRUE(psMesh->getViewportVisibility(-1)); + polyscope::view::activateViewport(0); + EXPECT_FALSE(psMesh->getViewportVisibility(-1)); + + polyscope::show(3); + + polyscope::view::createViewportGrid(1, 1); // restore + polyscope::removeAllStructures(); +} + +TEST_F(PolyscopeTest, ViewportProjectionMode) { + auto psMesh = registerTriangleMesh(); + auto psCloud = polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); + + polyscope::view::createViewportGrid(2, 1); // 2 viewports + polyscope::view::setViewportsShareNavigation(false); // allow independent projection modes + + // default: all viewports start with same projection mode (Perspective) + polyscope::view::activateViewport(0); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); + polyscope::view::activateViewport(1); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); + + // set viewport 1 to orthographic (stateful: set on the active viewport) + polyscope::view::activateViewport(1); + polyscope::view::setProjectionMode(polyscope::ProjectionMode::Orthographic); + polyscope::view::activateViewport(0); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); + polyscope::view::activateViewport(1); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Orthographic); + + // render with mixed projection modes + polyscope::show(3); + + // restore + polyscope::view::setViewportsShareNavigation(true); + polyscope::view::setProjectionMode(polyscope::ProjectionMode::Perspective); + polyscope::view::createViewportGrid(1, 1); + polyscope::removeAllStructures(); +} + +TEST_F(PolyscopeTest, ViewportCoordinates) { + polyscope::view::setWindowSize(800, 600); + polyscope::show(3); // ensure buffer is sized + + polyscope::view::createViewportGrid(2, 1); // left/right halves + polyscope::show(3); + + int bufW = polyscope::view::bufferWidth; + int bufH = polyscope::view::bufferHeight; + + // --- bufferIndsToScreenCoords / screenCoordsToBufferInds are inverses --- + glm::ivec2 bi{bufW / 4, bufH / 4}; + glm::vec2 sc = polyscope::view::bufferIndsToScreenCoords(bi); + auto [rx, ry] = polyscope::view::screenCoordsToBufferInds(sc); + EXPECT_EQ(rx, bi.x); + EXPECT_EQ(ry, bi.y); + + // --- viewport-local round-trip: buffer inds → screen coords → buffer inds --- + glm::ivec2 localBi{10, 20}; + glm::vec2 localSc = polyscope::view::bufferIndsToScreenCoordsViewport(localBi, 0); + auto [lx, ly] = polyscope::view::screenCoordsToBufferIndsViewport(localSc, 0); + EXPECT_EQ(lx, localBi.x); + EXPECT_EQ(ly, localBi.y); + + // --- globalToViewport / viewportToGlobal are inverses (screen coords) --- + glm::vec2 globalSc = polyscope::view::bufferIndsToScreenCoords(bi); + auto [localSc2, viewportInd] = polyscope::view::screenCoordsGlobalToViewport(globalSc); + glm::vec2 recoveredSc = polyscope::view::screenCoordsViewportToGlobal(localSc2, viewportInd); + EXPECT_NEAR(recoveredSc.x, globalSc.x, 1e-4f); + EXPECT_NEAR(recoveredSc.y, globalSc.y, 1e-4f); + + // --- globalToViewport / viewportToGlobal are inverses (buffer inds) --- + auto [localBi2, viewportInd2] = polyscope::view::bufferIndsGlobalToViewport(bi); + glm::ivec2 recoveredBi = polyscope::view::bufferIndsViewportToGlobal(localBi2, viewportInd2); + EXPECT_EQ(recoveredBi.x, bi.x); + EXPECT_EQ(recoveredBi.y, bi.y); + + // --- screenCoordsToViewportInd and bufferIndsToViewportInd agree --- + glm::vec2 testSc = polyscope::view::bufferIndsToScreenCoords(bi); + int32_t indFromSc = polyscope::view::screenCoordsToViewportInd(testSc); + int32_t indFromBi = polyscope::view::bufferIndsToViewportInd(bi); + EXPECT_EQ(indFromSc, indFromBi); + + // --- point in left half should be viewport 0, right half viewport 1 --- + glm::ivec2 leftBi{bufW / 4, bufH / 2}; + glm::ivec2 rightBi{3 * bufW / 4, bufH / 2}; + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(leftBi), 0); + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(rightBi), 1); + + polyscope::view::createViewportGrid(1, 1); // restore +} + +// A full-window viewport 0, with a small inset viewport 1 in the lower-right corner. Leaves viewport 0 active. +static void createInsetViewports() { + polyscope::view::setNumViewports(2); + polyscope::view::activateViewport(0); + polyscope::view::setActiveViewportRelativeLocation(0.f, 0.f); + polyscope::view::setActiveViewportRelativeSize(1.f, 1.f); + polyscope::view::activateViewport(1); + polyscope::view::setActiveViewportRelativeLocation(0.7f, 0.7f); + polyscope::view::setActiveViewportRelativeSize(0.3f, 0.3f); + polyscope::view::activateViewport(0); +} + +// Unlike the 2x1 split above, an inset is not symmetric in y, so this catches y-from-top vs y-from-bottom mixups. +TEST_F(PolyscopeTest, ViewportCoordinatesInset) { + polyscope::view::setWindowSize(800, 600); + createInsetViewports(); + polyscope::show(3); + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + glm::vec2 insetSc{0.85f * winW, 0.85f * winH}; // in the inset, at the lower-right + glm::vec2 upperRightSc{0.85f * winW, 0.15f * winH}; // not in the inset + + // finding the viewport agrees for screen coords and buffer inds + EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(insetSc), 1); + EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(upperRightSc), 0); + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(polyscope::view::screenCoordsToBufferIndsVec(insetSc)), 1); + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(polyscope::view::screenCoordsToBufferIndsVec(upperRightSc)), 0); + + // global <--> local round trips. The center of the inset is 0.15 of the window from its top-left corner. + auto [localSc, indSc] = polyscope::view::screenCoordsGlobalToViewport(insetSc); + EXPECT_EQ(indSc, 1); + EXPECT_NEAR(localSc.x, 0.15f * winW, 1e-3f); + EXPECT_NEAR(localSc.y, 0.15f * winH, 1e-3f); + EXPECT_NEAR(polyscope::view::screenCoordsViewportToGlobal(localSc, indSc).y, insetSc.y, 1e-3f); + + glm::ivec2 insetBi = polyscope::view::screenCoordsToBufferIndsVec(insetSc); + auto [localBi, indBi] = polyscope::view::bufferIndsGlobalToViewport(insetBi); + EXPECT_EQ(indBi, 1); + EXPECT_EQ(polyscope::view::bufferIndsViewportToGlobal(localBi, indBi), insetBi); + + polyscope::view::createViewportGrid(1, 1); // restore +} + +// The viewport ray helpers take local coordinates and use that viewport's camera (even if it isn't the active one), and +// the plain ones take global coordinates and find the viewport. +TEST_F(PolyscopeTest, ViewportRays) { + polyscope::view::setWindowSize(800, 600); + createInsetViewports(); + polyscope::view::setViewportsShareNavigation(false); + polyscope::show(3); + + // cameras looking down different axes + polyscope::view::activateViewport(1); + polyscope::view::lookAt(glm::vec3{0.f, 0.f, 5.f}, glm::vec3{0.f, 0.f, 0.f}); // looks along -z + polyscope::view::activateViewport(0); + polyscope::view::lookAt(glm::vec3{5.f, 0.f, 0.f}, glm::vec3{0.f, 0.f, 0.f}); // looks along -x + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + + // the center of each viewport has a ray along that viewport's look direction (the active viewport is the default) + EXPECT_NEAR(polyscope::view::viewportScreenCoordsToWorldRay(glm::vec2{0.15f * winW, 0.15f * winH}, 1).z, -1.f, 1e-3f); + EXPECT_NEAR(polyscope::view::viewportScreenCoordsToWorldRay(glm::vec2{0.5f * winW, 0.5f * winH}).x, -1.f, 1e-3f); + + // the same with global coordinates + EXPECT_NEAR(polyscope::view::screenCoordsToWorldRay(glm::vec2{0.85f * winW, 0.85f * winH}).z, -1.f, 1e-3f); + EXPECT_NEAR(polyscope::view::screenCoordsToWorldRay(glm::vec2{0.5f * winW, 0.5f * winH}).x, -1.f, 1e-3f); + + polyscope::view::setViewportsShareNavigation(true); + polyscope::view::createViewportGrid(1, 1); // restore +} + +// With a single viewport, as in all code from before viewports, the plain ray function takes window coordinates and +// does not clamp them to the window. +TEST_F(PolyscopeTest, RayHelpersSingleViewport) { + polyscope::view::setWindowSize(800, 600); + polyscope::view::createViewportGrid(1, 1); + polyscope::show(3); + + glm::vec2 outside{-300.f, 900.f}; + EXPECT_EQ(polyscope::view::screenCoordsToWorldRay(outside), + polyscope::view::viewportScreenCoordsToWorldRay(outside, 0)); + EXPECT_GT(glm::length(polyscope::view::screenCoordsToWorldRay(outside) - + polyscope::view::screenCoordsToWorldRay(glm::vec2{0.f, 599.f})), + 1e-2f); +} + +// The mock backend can't return real hits, so this tests that picks are routed to the right viewport, with the right +// coordinates. (See the next test for real hits.) +TEST_F(PolyscopeTest, ViewportPickRouting) { + polyscope::view::setWindowSize(800, 600); + polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); + createInsetViewports(); + polyscope::show(3); + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + const polyscope::view::ViewParameters& inset = polyscope::view::getViewportParameters(1); + + // a global point in the inset: the plain coordinates are global, the viewport ones are at the center of the inset + glm::vec2 insetSc{0.85f * winW, 0.85f * winH}; + polyscope::PickResult pick = polyscope::pickAtScreenCoords(insetSc); + EXPECT_EQ(pick.viewportInd, 1); + EXPECT_NEAR(pick.screenCoords.x, insetSc.x, 1); + EXPECT_NEAR(pick.screenCoords.y, insetSc.y, 1); + EXPECT_NEAR(pick.viewportScreenCoords.x, 0.15f * winW, 1); + EXPECT_NEAR(pick.viewportScreenCoords.y, 0.15f * winH, 1); + EXPECT_NEAR(pick.viewportBufferInds.x, inset.viewportBufferWidth / 2, 1); + EXPECT_NEAR(pick.viewportBufferInds.y, inset.viewportBufferHeight / 2, 1); + + // global buffer inds route the same way, and a pick can be reproduced from its local coordinates and viewport + EXPECT_EQ(polyscope::pickAtBufferInds(pick.bufferInds).viewportInd, 1); + EXPECT_EQ(polyscope::pickViewportAtBufferInds(pick.viewportBufferInds, pick.viewportInd).bufferInds, pick.bufferInds); + + // a point outside the inset is in viewport 0, and picking does not change which viewport is active + EXPECT_EQ(polyscope::pickAtScreenCoords(glm::vec2{0.3f * winW, 0.3f * winH}).viewportInd, 0); + EXPECT_EQ(polyscope::view::getActiveViewportIndex(), 0); + + polyscope::view::createViewportGrid(1, 1); // restore + polyscope::removeAllStructures(); +} + +// Pick which structure is really hit, with overlapping viewports. Needs real rendering, so it is skipped with the mock +// backend. +TEST_F(PolyscopeTest, ViewportPickHitsStructure) { + if (testBackend == "openGL_mock") GTEST_SKIP() << "needs a real rendering backend to get real pick hits"; + + polyscope::view::setWindowSize(800, 600); + createInsetViewports(); + + // Two big squares facing the camera: "A" at z=0 shown only in viewport 0, and "B" at z=1 shown only in the inset + auto makeSquare = [](float z) { + return std::vector{{-10, -10, z}, {10, -10, z}, {10, 10, z}, {-10, 10, z}}; + }; + std::vector> faces{{0, 1, 2}, {0, 2, 3}}; + polyscope::registerSurfaceMesh("A", makeSquare(0.f), faces)->setViewportVisibilityExclusive(0); + polyscope::registerSurfaceMesh("B", makeSquare(1.f), faces)->setViewportVisibilityExclusive(1); + polyscope::view::lookAt(glm::vec3{0.f, 0.f, 5.f}, glm::vec3{0.f, 0.f, 0.f}); + polyscope::show(3); + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + glm::vec2 insetSc{0.85f * winW, 0.85f * winH}; + + // a global point in the inset hits "B", at its depth + polyscope::PickResult insetPick = polyscope::pickAtScreenCoords(insetSc); + EXPECT_EQ(insetPick.structureName, "B"); + EXPECT_EQ(insetPick.viewportInd, 1); + EXPECT_NEAR(insetPick.position.z, 1.f, 0.05f); + + // a global point outside the inset hits "A" + EXPECT_EQ(polyscope::pickAtScreenCoords(glm::vec2{0.3f * winW, 0.3f * winH}).structureName, "A"); + + // asking for viewport 0 at the same point as the inset hits "A", the structure underneath the inset + EXPECT_EQ(polyscope::pickViewportAtScreenCoords(insetSc, 0).structureName, "A"); + + // top-row pick (y=0) must not read out-of-bounds + polyscope::PickResult topRowPick = polyscope::pickViewportAtBufferInds(glm::ivec2{10, 0}, 0); + EXPECT_EQ(topRowPick.structureName, "A"); + + polyscope::view::createViewportGrid(1, 1); // restore + polyscope::removeAllStructures(); +} + TEST_F(PolyscopeTest, UIScale) { // this should trigger a reload of the font atlas @@ -280,5 +607,10 @@ TEST_F(PolyscopeTest, GroundPlaneTest) { polyscope::options::groundPlaneHeightMode = polyscope::GroundPlaneHeightMode::Automatic; polyscope::show(3); + // render with viewports + polyscope::view::createViewportGrid(2, 1); + polyscope::show(3); + polyscope::view::createViewportGrid(1, 1); + polyscope::removeAllStructures(); } diff --git a/test/src/combo_test.cpp b/test/src/combo_test.cpp index e49fa117..ec33e369 100644 --- a/test/src/combo_test.cpp +++ b/test/src/combo_test.cpp @@ -144,6 +144,21 @@ TEST_F(PolyscopeTest, SlicePlaneTest) { polyscope::removeAllStructures(); } +TEST_F(PolyscopeTest, SlicePlaneViewportTest) { + auto psMesh = registerTriangleMesh(); + + polyscope::addSlicePlane(); + + polyscope::view::createViewportGrid(2, 1); + polyscope::show(3); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 0); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 1); + polyscope::view::createViewportGrid(1, 1); + + polyscope::removeAllSlicePlanes(); + polyscope::removeAllStructures(); +} + // Register a handful of quantities / structures, then call refresh TEST_F(PolyscopeTest, OrthoViewTest) { diff --git a/test/src/floating_test.cpp b/test/src/floating_test.cpp index b9e8eb48..010a783e 100644 --- a/test/src/floating_test.cpp +++ b/test/src/floating_test.cpp @@ -252,6 +252,16 @@ TEST_F(PolyscopeTest, FloatingRenderImageTest) { polyscope::removeFloatingQuantity("render im depth", true); polyscope::show(3); + // render and pick with viewports + polyscope::view::createViewportGrid(2, 1); + polyscope::show(3); + polyscope::pickViewportAtScreenCoords(glm::vec2(0.3, 0.8), 0); + polyscope::pickViewportAtScreenCoords(glm::vec2(0.3, 0.8), 1); + polyscope::options::transparencyMode = polyscope::TransparencyMode::Pretty; + polyscope::show(3); + polyscope::options::transparencyMode = polyscope::TransparencyMode::None; + polyscope::view::createViewportGrid(1, 1); + polyscope::removeAllStructures(); } diff --git a/test/src/point_cloud_test.cpp b/test/src/point_cloud_test.cpp index 8e06aa32..54a1f25f 100644 --- a/test/src/point_cloud_test.cpp +++ b/test/src/point_cloud_test.cpp @@ -30,6 +30,12 @@ TEST_F(PolyscopeTest, ShowPointCloud) { polyscope::show(3); EXPECT_TRUE(polyscope::hasPointCloud("test1")); EXPECT_FALSE(polyscope::hasPointCloud("test2")); + + // render with viewports + polyscope::view::createViewportGrid(2, 1); + polyscope::show(3); + polyscope::view::createViewportGrid(1, 1); + polyscope::removeAllStructures(); EXPECT_FALSE(polyscope::hasPointCloud("test1")); } @@ -91,6 +97,13 @@ TEST_F(PolyscopeTest, PointCloudPick) { polyscope::pickAtBufferInds(glm::ivec2(77, 88)); polyscope::view::setProjectionMode(polyscope::ProjectionMode::Perspective); + // pick with viewports + polyscope::view::createViewportGrid(2, 1); + polyscope::show(3); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 0); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 1); + polyscope::view::createViewportGrid(1, 1); + polyscope::removeAllStructures(); } @@ -267,5 +280,12 @@ TEST_F(PolyscopeTest, PointCloudScalarTransparency) { polyscope::options::transparencyMode = polyscope::TransparencyMode::None; polyscope::show(3); + // render transparency with viewports + polyscope::view::createViewportGrid(2, 1); + polyscope::options::transparencyMode = polyscope::TransparencyMode::Pretty; + polyscope::show(3); + polyscope::options::transparencyMode = polyscope::TransparencyMode::None; + polyscope::view::createViewportGrid(1, 1); + polyscope::removeAllStructures(); } diff --git a/test/src/surface_mesh_test.cpp b/test/src/surface_mesh_test.cpp index 7a2fd2ef..36dbfa51 100644 --- a/test/src/surface_mesh_test.cpp +++ b/test/src/surface_mesh_test.cpp @@ -15,6 +15,12 @@ TEST_F(PolyscopeTest, ShowSurfaceMesh) { polyscope::show(3); EXPECT_TRUE(polyscope::hasSurfaceMesh("test1")); EXPECT_FALSE(polyscope::hasSurfaceMesh("test2")); + + // render with viewports + polyscope::view::createViewportGrid(2, 1); + polyscope::show(3); + polyscope::view::createViewportGrid(1, 1); + polyscope::removeAllStructures(); EXPECT_FALSE(polyscope::hasSurfaceMesh("test1")); } @@ -740,15 +746,14 @@ TEST_F(PolyscopeTest, SimpleTriangleMeshUpdateFunctions) { polyscope::show(3); // updateMesh: shrink - psMesh->updateMesh(std::vector{{0,0,0},{1,0,0},{0,1,0}}, - std::vector{{0,1,2}}); + psMesh->updateMesh(std::vector{{0, 0, 0}, {1, 0, 0}, {0, 1, 0}}, std::vector{{0, 1, 2}}); EXPECT_EQ(psMesh->nVertices(), 3u); EXPECT_EQ(psMesh->nFaces(), 1u); polyscope::show(3); // updateMesh: grow beyond original size - std::vector bigVerts = {{0,0,0},{1,0,0},{0,1,0},{0,0,1},{1,1,0}}; - std::vector bigFaces = {{0,1,2},{1,3,4},{2,3,0}}; + std::vector bigVerts = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}}; + std::vector bigFaces = {{0, 1, 2}, {1, 3, 4}, {2, 3, 0}}; psMesh->updateMesh(bigVerts, bigFaces); EXPECT_EQ(psMesh->nVertices(), 5u); EXPECT_EQ(psMesh->nFaces(), 3u); @@ -763,21 +768,21 @@ TEST_F(PolyscopeTest, SimpleTriangleMeshQuantityUpdateAfterResize) { // Add quantities at original size and enable them auto qVS = psMesh->addVertexScalarQuantity("vScalar", std::vector(psMesh->nVertices(), 1.f)); auto qFS = psMesh->addFaceScalarQuantity("fScalar", std::vector(psMesh->nFaces(), 2.f)); - auto qVC = psMesh->addVertexColorQuantity("vColor", std::vector(psMesh->nVertices(), glm::vec3{1,0,0})); - auto qFC = psMesh->addFaceColorQuantity("fColor", std::vector(psMesh->nFaces(), glm::vec3{0,1,0})); + auto qVC = psMesh->addVertexColorQuantity("vColor", std::vector(psMesh->nVertices(), glm::vec3{1, 0, 0})); + auto qFC = psMesh->addFaceColorQuantity("fColor", std::vector(psMesh->nFaces(), glm::vec3{0, 1, 0})); qVS->setEnabled(true); polyscope::show(3); // Resize the mesh - std::vector newVerts = {{0,0,0},{1,0,0},{0,1,0},{0,0,1},{1,1,0}}; - std::vector newFaces = {{0,1,2},{1,3,4},{2,3,0}}; + std::vector newVerts = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}}; + std::vector newFaces = {{0, 1, 2}, {1, 3, 4}, {2, 3, 0}}; psMesh->updateMesh(newVerts, newFaces); // Update all quantities to match new counts qVS->updateData(std::vector(psMesh->nVertices(), 3.f)); qFS->updateData(std::vector(psMesh->nFaces(), 4.f)); - qVC->updateData(std::vector(psMesh->nVertices(), glm::vec3{0,0,1})); - qFC->updateData(std::vector(psMesh->nFaces(), glm::vec3{1,1,0})); + qVC->updateData(std::vector(psMesh->nVertices(), glm::vec3{0, 0, 1})); + qFC->updateData(std::vector(psMesh->nFaces(), glm::vec3{1, 1, 0})); EXPECT_EQ(qVS->values.size(), psMesh->nVertices()); EXPECT_EQ(qFS->values.size(), psMesh->nFaces()); @@ -792,8 +797,9 @@ TEST_F(PolyscopeTest, SimpleTriangleMeshQuantityUpdateAfterResize) { TEST_F(PolyscopeTest, SimpleTriangleMeshLargeFaceQuantities) { - // This primarily serves to test the GL Texture Buffers and using attributes to set texture buffers within the ManagedBuffer and Engine classes. - // Currently, SimpleTriangleMesh face quantities are the only users of this, and there's a fair bit of special-purpose code just to support that. + // This primarily serves to test the GL Texture Buffers and using attributes to set texture buffers within the + // ManagedBuffer and Engine classes. Currently, SimpleTriangleMesh face quantities are the only users of this, and + // there's a fair bit of special-purpose code just to support that. // Exceeds typical 16k/32k GL_MAX_TEXTURE_SIZE for 1D textures; verifies TBO-backed face quantities // render the expected data at high gl_PrimitiveID across initial upload, updateData(), and growth via updateMesh().