/*
 * SPDX-FileName: CameraGroup.cxx
 * SPDX-FileCopyrightText: Copyright (C) 2008  Tim Moore
 * SPDX-FileContributor: Copyright (C) 2011  Mathias Froehlich
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "CameraGroup.hxx"

#include <Main/fg_props.hxx>
#include <Main/globals.hxx>
#include "renderer.hxx"
#include "FGEventHandler.hxx"
#include "WindowBuilder.hxx"
#include "WindowSystemAdapter.hxx"
#include "splash.hxx"
#include "sview.hxx"
#include "VRManager.hxx"

#include <simgear/math/SGRect.hxx>
#include <simgear/props/props.hxx>
#include <simgear/props/props_io.hxx> // for copyProperties
#include <simgear/structure/exception.hxx>
#include <simgear/scene/material/EffectCullVisitor.hxx>
#include <simgear/scene/util/ProjectionMatrix.hxx>
#include <simgear/scene/util/RenderConstants.hxx>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>
#include <simgear/scene/util/OsgUtils.hxx>
#include <simgear/scene/viewer/Compositor.hxx>
#include <simgear/scene/viewer/CompositorUtil.hxx>

#include <algorithm>
#include <cstring>
#include <string>

#include <osg/Camera>
#include <osg/Geometry>
#include <osg/GraphicsContext>
#include <osg/io_utils>
#include <osg/Math>
#include <osg/Matrix>
#include <osg/Notify>
#include <osg/Program>
#include <osg/Quat>
#include <osg/TexMat>
#include <osg/Vec3d>
#include <osg/Viewport>

#include <osgUtil/IntersectionVisitor>

#include <osgViewer/Viewer>
#include <osgViewer/GraphicsWindow>
#include <osgViewer/Renderer>

using namespace osg;

namespace {

osg::Matrix
invert(const osg::Matrix& matrix)
{
    return osg::Matrix::inverse(matrix);
}

/// Returns the zoom factor of the master camera.
/// The reference fov is the historic 55 deg
double
zoomFactor()
{
    double fov = fgGetDouble("/sim/current-view/field-of-view", 55);
    if (fov < 1)
        fov = 1;
    return tan(55*0.5*SG_DEGREES_TO_RADIANS)/tan(fov*0.5*SG_DEGREES_TO_RADIANS);
}

osg::Vec2d
preMult(const osg::Vec2d& v, const osg::Matrix& m)
{
    osg::Vec3d tmp = m.preMult(osg::Vec3(v, 0));
    return osg::Vec2d(tmp[0], tmp[1]);
}

osg::Matrix
relativeProjection(const osg::Matrix& P0, const osg::Matrix& R, const osg::Vec2d ref[2],
                   const osg::Matrix& pP, const osg::Matrix& pR, const osg::Vec2d pRef[2])
{
    // Track the way from one projection space to the other:
    // We want
    //  P = T*S*P0
    // where P0 is the projection template sensible for the given window size,
    // T is a translation matrix and S a scale matrix.
    // We need to determine T and S so that the reference points in the parents
    // projection space match the two reference points in this cameras projection space.

    // Starting from the parents camera projection space, we get into this cameras
    // projection space by the transform matrix:
    //  P*R*inv(pP*pR) = T*S*P0*R*inv(pP*pR)
    // So, at first compute that matrix without T*S and determine S and T from that

    // Ok, now osg uses the inverse matrix multiplication order, thus:
    osg::Matrix PtoPwithoutTS = invert(pR*pP)*R*P0;
    // Compute the parents reference points in the current projection space
    // without the yet unknown T and S
    osg::Vec2d pRefInThis[2] = {
        preMult(pRef[0], PtoPwithoutTS),
        preMult(pRef[1], PtoPwithoutTS)
    };

    // To get the same zoom, rescale to match the parents size
    double s = (ref[0] - ref[1]).length()/(pRefInThis[0] - pRefInThis[1]).length();
    osg::Matrix S = osg::Matrix::scale(s, s, 1);

    // For the translation offset, incorporate the now known scale
    // and recompute the position of the first reference point in the
    // currents projection space without the yet unknown T.
    pRefInThis[0] = preMult(pRef[0], PtoPwithoutTS*S);
    // The translation is then the difference of the reference points
    osg::Matrix T = osg::Matrix::translate(osg::Vec3d(ref[0] - pRefInThis[0], 0));

    // Compose and return the desired final projection matrix
    return P0*S*T;
}

} // anonymous namespace

namespace flightgear
{
using namespace simgear;
using namespace compositor;

class CameraGroupListener : public SGPropertyChangeListener {
public:
    CameraGroupListener(CameraGroup* cg, SGPropertyNode* gnode) :
        _groupNode(gnode),
        _cameraGroup(cg) {
        listenToNode("znear", 0.1f);
        listenToNode("zfar", 1000000.0f);
    }

    virtual ~CameraGroupListener() {
        unlisten("znear");
        unlisten("zfar");
    }

    virtual void valueChanged(SGPropertyNode* prop) {
        if (prop->getNameString() == "znear") {
            _cameraGroup->_zNear = prop->getFloatValue();
        } else if (prop->getNameString() == "zfar") {
            _cameraGroup->_zFar = prop->getFloatValue();
        }
    }
private:
    void listenToNode(const std::string& name, double val) {
        SGPropertyNode* n = _groupNode->getChild(name);
        if (!n) {
            n = _groupNode->getChild(name, 0 /* index */, true);
            n->setDoubleValue(val);
        }
        n->addChangeListener(this);
        valueChanged(n); // propagate initial state through
    }

    void unlisten(const std::string& name) {
        _groupNode->getChild(name)->removeChangeListener(this);
    }

    SGPropertyNode_ptr _groupNode;
    CameraGroup* _cameraGroup; // non-owning reference
};

typedef std::vector<SGPropertyNode_ptr> SGPropertyNodeVec;

osg::ref_ptr<CameraGroup> CameraGroup::_defaultGroup;

CameraGroup::CameraGroup(osgViewer::View* view) :
    _viewer(view)
{
}

void CameraGroup::update(const osg::Vec3d& position,
                         const osg::Quat& orientation)
{
    const osg::Matrix masterView(osg::Matrix::translate(-position)
                                 * osg::Matrix::rotate(orientation.inverse()));
    _viewer->getCamera()->setViewMatrix(masterView);
    const osg::Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
    double masterZoomFactor = zoomFactor();

    for (const auto &info : _cameras) {
        osg::Matrix view_matrix;
        if (info->flags & (CameraInfo::SPLASH | CameraInfo::GUI))
            view_matrix = osg::Matrix::identity();
        else if ((info->flags & CameraInfo::VIEW_ABSOLUTE) != 0)
            view_matrix = info->viewOffset;
        else
            view_matrix = masterView * info->viewOffset;

        osg::Matrix proj_matrix;
        if (info->flags & (CameraInfo::SPLASH | CameraInfo::GUI)) {
            const osg::GraphicsContext::Traits *traits =
                info->compositor->getGraphicsContext()->getTraits();
            proj_matrix = osg::Matrix::ortho2D(0, traits->width, 0, traits->height);
        } else if ((info->flags & CameraInfo::PROJECTION_ABSOLUTE) != 0) {
            if (info->flags & CameraInfo::ENABLE_MASTER_ZOOM) {
                if (info->relativeCameraParent) {
                    // template projection and view matrices of the current camera
                    osg::Matrix P0 = info->projOffset;
                    osg::Matrix R = view_matrix;

                    // The already known projection and view matrix of the parent camera
                    osg::Matrix pP = info->relativeCameraParent->projMatrix;
                    osg::Matrix pR = info->relativeCameraParent->viewMatrix;

                    // And the projection matrix derived from P0 so that the
                    // reference points match
                    proj_matrix = relativeProjection(P0, R,  info->thisReference,
                                                     pP, pR, info->parentReference);
                } else {
                    // We want to zoom, so take the original matrix and apply the
                    // zoom to it
                    proj_matrix = info->projOffset;
                    proj_matrix.postMultScale(osg::Vec3d(masterZoomFactor,
                                                         masterZoomFactor,
                                                         1));
                }
            } else {
                proj_matrix = info->projOffset;
            }
        } else {
            proj_matrix = masterProj * info->projOffset;
        }

        osg::Matrix new_proj_matrix = proj_matrix;
        if ((info->flags & CameraInfo::SPLASH) == 0 &&
            (info->flags & CameraInfo::GUI) == 0 &&
            (info->flags & CameraInfo::FIXED_NEAR_FAR) == 0) {
            ProjectionMatrix::clampNearFarPlanes(proj_matrix, _zNear, _zFar,
                                                 new_proj_matrix);
        }

        info->viewMatrix = view_matrix;
        info->projMatrix = new_proj_matrix;
        info->compositor->update(view_matrix, new_proj_matrix);
    }
}

void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
{
    if (vfov != 0.0f && aspectRatio != 0.0f) {
        osg::Matrixd m;
        ProjectionMatrix::makePerspective(m, vfov, 1.0 / aspectRatio,
                                          _zNear, _zFar, ProjectionMatrix::STANDARD);
        _viewer->getCamera()->setProjectionMatrix(m);
    }
}

double CameraGroup::getMasterAspectRatio() const
{
    if (_cameras.empty())
        return 0.0;

    // The master camera is the first one added
    const CameraInfo *info = _cameras.front();
    if (!info)
        return 0.0;
    const osg::GraphicsContext::Traits *traits =
        info->compositor->getGraphicsContext()->getTraits();

    return static_cast<double>(traits->height) / traits->width;
}

CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
{
    WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
    const SGPropertyNode* windowNode = cameraNode->getNode("window");
    GraphicsWindow* window = 0;
    int cameraFlags = CameraInfo::DO_INTERSECTION_TEST;
    if (windowNode) {
        // New style window declaration / definition
        window = wBuild->buildWindow(windowNode);
    } else {
        // Old style: suck window params out of camera block
        window = wBuild->buildWindow(cameraNode);
    }
    if (!window) {
        return nullptr;
    }

    // Set the projection matrix near/far behaviour
    ProjectionMatrix::Type proj_type = ProjectionMatrix::STANDARD;

    // Set vr-mirror flag so camera switches to VR mirror when appropriate.
    if (cameraNode->getBoolValue("vr-mirror", false))
        cameraFlags |= CameraInfo::VR_MIRROR;

    osg::Matrix vOff;
    const SGPropertyNode* viewNode = cameraNode->getNode("view");
    if (viewNode) {
        double heading = viewNode->getDoubleValue("heading-deg", 0.0);
        double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
        double roll = viewNode->getDoubleValue("roll-deg", 0.0);
        double x = viewNode->getDoubleValue("x", 0.0);
        double y = viewNode->getDoubleValue("y", 0.0);
        double z = viewNode->getDoubleValue("z", 0.0);
        // Build a view matrix, which is the inverse of a model
        // orientation matrix.
        vOff = (Matrix::translate(-x, -y, -z)
                * Matrix::rotate(-DegreesToRadians(heading),
                                 Vec3d(0.0, 1.0, 0.0),
                                 -DegreesToRadians(pitch),
                                 Vec3d(1.0, 0.0, 0.0),
                                 -DegreesToRadians(roll),
                                 Vec3d(0.0, 0.0, 1.0)));
        if (viewNode->getBoolValue("absolute", false))
            cameraFlags |= CameraInfo::VIEW_ABSOLUTE;
    } else {
        // Old heading parameter, works in the opposite direction
        double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
        vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
    }
    // Configuring the physical dimensions of a monitor
    SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
    double physicalWidth = viewportNode->getDoubleValue("width", 1024);
    double physicalHeight = viewportNode->getDoubleValue("height", 768);
    double bezelHeightTop = 0;
    double bezelHeightBottom = 0;
    double bezelWidthLeft = 0;
    double bezelWidthRight = 0;
    const SGPropertyNode* physicalDimensionsNode = 0;
    if ((physicalDimensionsNode = cameraNode->getNode("physical-dimensions")) != 0) {
        physicalWidth = physicalDimensionsNode->getDoubleValue("width", physicalWidth);
        physicalHeight = physicalDimensionsNode->getDoubleValue("height", physicalHeight);
        const SGPropertyNode* bezelNode = 0;
        if ((bezelNode = physicalDimensionsNode->getNode("bezel")) != 0) {
            bezelHeightTop = bezelNode->getDoubleValue("top", bezelHeightTop);
            bezelHeightBottom = bezelNode->getDoubleValue("bottom", bezelHeightBottom);
            bezelWidthLeft = bezelNode->getDoubleValue("left", bezelWidthLeft);
            bezelWidthRight = bezelNode->getDoubleValue("right", bezelWidthRight);
        }
    }
    osg::Matrix pOff;
    CameraInfo *parentInfo = nullptr;
    osg::Vec2d parentReference[2];
    osg::Vec2d thisReference[2];
    SGPropertyNode* projectionNode = 0;
    if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
        double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
        double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
                                                            1.0);
        double zNear = projectionNode->getDoubleValue("near", 0.0);
        double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
        double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
        double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
        double tan_fovy = tan(DegreesToRadians(fovy*0.5));
        double right = tan_fovy * aspectRatio * zNear + offsetX;
        double left = -tan_fovy * aspectRatio * zNear + offsetX;
        double top = tan_fovy * zNear + offsetY;
        double bottom = -tan_fovy * zNear + offsetY;
        ProjectionMatrix::makeFrustum(pOff,
                                      left, right,
                                      bottom, top,
                                      zNear, zFar,
                                      proj_type);
        cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE;
        if (projectionNode->getBoolValue("fixed-near-far", true))
            cameraFlags |= CameraInfo::FIXED_NEAR_FAR;
    } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
               || (projectionNode = cameraNode->getNode("ortho")) != 0) {
        double top = projectionNode->getDoubleValue("top", 0.0);
        double bottom = projectionNode->getDoubleValue("bottom", 0.0);
        double left = projectionNode->getDoubleValue("left", 0.0);
        double right = projectionNode->getDoubleValue("right", 0.0);
        double zNear = projectionNode->getDoubleValue("near", 0.0);
        double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
        if (cameraNode->getNode("frustum")) {
            ProjectionMatrix::makeFrustum(pOff,
                                          left, right,
                                          bottom, top,
                                          zNear, zFar,
                                          proj_type);
            cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE;
        } else {
            ProjectionMatrix::makeOrtho(pOff,
                                        left, right,
                                        bottom, top,
                                        zNear, zFar,
                                        proj_type);
            cameraFlags |= (CameraInfo::PROJECTION_ABSOLUTE | CameraInfo::ORTHO);
        }
        if (projectionNode->getBoolValue("fixed-near-far", true))
            cameraFlags |= CameraInfo::FIXED_NEAR_FAR;
    } else if ((projectionNode = cameraNode->getNode("master-perspective")) != 0) {
        double zNear = projectionNode->getDoubleValue("eye-distance", 0.4*physicalWidth);
        double xoff = projectionNode->getDoubleValue("x-offset", 0);
        double yoff = projectionNode->getDoubleValue("y-offset", 0);
        double left = -0.5*physicalWidth - xoff;
        double right = 0.5*physicalWidth - xoff;
        double bottom = -0.5*physicalHeight - yoff;
        double top = 0.5*physicalHeight - yoff;
        ProjectionMatrix::makeFrustum(pOff,
                                      left, right,
                                      bottom, top,
                                      zNear, zNear + 20000.0,
                                      proj_type);
        cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE | CameraInfo::ENABLE_MASTER_ZOOM;
    } else if ((projectionNode = cameraNode->getNode("right-of-perspective"))
               || (projectionNode = cameraNode->getNode("left-of-perspective"))
               || (projectionNode = cameraNode->getNode("above-perspective"))
               || (projectionNode = cameraNode->getNode("below-perspective"))
               || (projectionNode = cameraNode->getNode("reference-points-perspective"))) {
        std::string name = projectionNode->getStringValue("parent-camera");
        auto it = std::find_if(_cameras.begin(), _cameras.end(),
                               [&name](const auto &c) { return c->name == name; });
        if (it == _cameras.end()) {
            SG_LOG(SG_VIEW, SG_ALERT, "CameraGroup::buildCamera: "
                   "failed to find parent camera for relative camera!");
            return nullptr;
        }
        parentInfo = (*it);
        if (projectionNode->getNameString() == "right-of-perspective") {
            double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthRight)/parentInfo->physicalWidth;
            parentReference[0] = osg::Vec2d(tmp, -1);
            parentReference[1] = osg::Vec2d(tmp, 1);
            tmp = (physicalWidth + 2*bezelWidthLeft)/physicalWidth;
            thisReference[0] = osg::Vec2d(-tmp, -1);
            thisReference[1] = osg::Vec2d(-tmp, 1);
        } else if (projectionNode->getNameString() == "left-of-perspective") {
            double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthLeft)/parentInfo->physicalWidth;
            parentReference[0] = osg::Vec2d(-tmp, -1);
            parentReference[1] = osg::Vec2d(-tmp, 1);
            tmp = (physicalWidth + 2*bezelWidthRight)/physicalWidth;
            thisReference[0] = osg::Vec2d(tmp, -1);
            thisReference[1] = osg::Vec2d(tmp, 1);
        } else if (projectionNode->getNameString() == "above-perspective") {
            double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightTop)/parentInfo->physicalHeight;
            parentReference[0] = osg::Vec2d(-1, tmp);
            parentReference[1] = osg::Vec2d(1, tmp);
            tmp = (physicalHeight + 2*bezelHeightBottom)/physicalHeight;
            thisReference[0] = osg::Vec2d(-1, -tmp);
            thisReference[1] = osg::Vec2d(1, -tmp);
        } else if (projectionNode->getNameString() == "below-perspective") {
            double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightBottom)/parentInfo->physicalHeight;
            parentReference[0] = osg::Vec2d(-1, -tmp);
            parentReference[1] = osg::Vec2d(1, -tmp);
            tmp = (physicalHeight + 2*bezelHeightTop)/physicalHeight;
            thisReference[0] = osg::Vec2d(-1, tmp);
            thisReference[1] = osg::Vec2d(1, tmp);
        } else if (projectionNode->getNameString() == "reference-points-perspective") {
            SGPropertyNode* parentNode = projectionNode->getNode("parent", true);
            SGPropertyNode* thisNode = projectionNode->getNode("this", true);
            SGPropertyNode* pointNode;

            pointNode = parentNode->getNode("point", 0, true);
            parentReference[0][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
            parentReference[0][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
            pointNode = parentNode->getNode("point", 1, true);
            parentReference[1][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
            parentReference[1][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;

            pointNode = thisNode->getNode("point", 0, true);
            thisReference[0][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
            thisReference[0][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
            pointNode = thisNode->getNode("point", 1, true);
            thisReference[1][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
            thisReference[1][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
        }

        ProjectionMatrix::makePerspective(pOff, 45, physicalWidth/physicalHeight,
                                          1, 20000, proj_type);
        cameraFlags |= CameraInfo::PROJECTION_ABSOLUTE | CameraInfo::ENABLE_MASTER_ZOOM;
    } else {
        // old style shear parameters
        double shearx = cameraNode->getDoubleValue("shear-x", 0);
        double sheary = cameraNode->getDoubleValue("shear-y", 0);
        pOff.makeTranslate(-shearx, -sheary, 0);
    }

    CameraInfo *info = new CameraInfo(cameraFlags);
    _cameras.push_back(info);
    info->name = cameraNode->getStringValue("name");
    info->physicalWidth = physicalWidth;
    info->physicalHeight = physicalHeight;
    info->bezelHeightTop = bezelHeightTop;
    info->bezelHeightBottom = bezelHeightBottom;
    info->bezelWidthLeft = bezelWidthLeft;
    info->bezelWidthRight = bezelWidthRight;
    info->relativeCameraParent = parentInfo;
    info->parentReference[0] = parentReference[0];
    info->parentReference[1] = parentReference[1];
    info->thisReference[0] = thisReference[0];
    info->thisReference[1] = thisReference[1];
    info->viewOffset = vOff;
    info->projOffset = pOff;
    info->mvr.views = cameraNode->getIntValue("mvr-views", 1);
    info->mvr.viewIdGlobalStr = cameraNode->getStringValue("mvr-view-id-global", "");
    info->mvr.viewIdStr[0] = cameraNode->getStringValue("mvr-view-id-vert", "0");
    info->mvr.viewIdStr[1] = cameraNode->getStringValue("mvr-view-id-geom", "0");
    info->mvr.viewIdStr[2] = cameraNode->getStringValue("mvr-view-id-frag", "0");
    info->mvr.cells = cameraNode->getIntValue("mvr-cells", 1);

    osg::Viewport *viewport = new osg::Viewport(
        viewportNode->getDoubleValue("x"),
        viewportNode->getDoubleValue("y"),
        // If no width or height has been specified, fill the entire window
        viewportNode->getDoubleValue("width", window->gc->getTraits()->width),
        viewportNode->getDoubleValue("height",window->gc->getTraits()->height));

    std::string compositor_path = cameraNode->getStringValue("compositor", "");
    if (compositor_path.empty()) {
        compositor_path = fgGetString("/sim/rendering/default-compositor",
                                      "Compositor/default");
    } else {
        // Store the custom path in case we need to reload later
        info->compositor_path = compositor_path;
    }

    osg::ref_ptr<SGReaderWriterOptions> options =
        SGReaderWriterOptions::fromPath(globals->get_fg_root());
    options->setPropertyNode(globals->get_props());

    SViewSetCompositorParams(options, compositor_path);

    Compositor *compositor = nullptr;
    if (info->flags & CameraInfo::VR_MIRROR)
        compositor = buildVRMirrorCompositor(window->gc, viewport);
    if (!compositor)
        compositor = Compositor::create(_viewer,
                                        window->gc,
                                        viewport,
                                        compositor_path,
                                        options,
                                        &info->mvr);

    if (compositor) {
        info->compositor.reset(compositor);
    } else {
        throw sg_exception(std::string("Failed to create Compositor in path '") +
                           compositor_path + "'");
    }

    return info;
}

void CameraGroup::removeCamera(CameraInfo *info)
{
    for (auto it = _cameras.begin(); it != _cameras.end(); ++it) {
        if (*it == info) {
            _cameras.erase(it);
            return;
        }
    }
}

void CameraGroup::buildSplashCamera(SGPropertyNode* cameraNode,
                                    GraphicsWindow* window)
{
    WindowBuilder* wBuild = WindowBuilder::getWindowBuilder();
    const SGPropertyNode* windowNode = (cameraNode
                                            ? cameraNode->getNode("window")
                                            : 0);
    if (!window && windowNode) {
        // New style window declaration / definition
        window = wBuild->buildWindow(windowNode);
    }

    if (!window) { // buildWindow can fail
        SG_LOG(SG_VIEW, SG_WARN, "CameraGroup::buildSplashCamera: failed to build a window");
        return;
    }

    Camera* camera = new Camera;
    camera->setName("SplashCamera");
    camera->setAllowEventFocus(false);
    camera->setGraphicsContext(window->gc.get());
    // If a viewport isn't set on the camera, then it's hard to dig it
    // out of the SceneView objects in the viewer, and the coordinates
    // of mouse events are somewhat bizarre.
    osg::Viewport* viewport = new osg::Viewport(
        0, 0, window->gc->getTraits()->width, window->gc->getTraits()->height);
    camera->setViewport(viewport);
    camera->setClearMask(0);
    camera->setInheritanceMask(CullSettings::ALL_VARIABLES
                               & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
                                   | CullSettings::CULLING_MODE
                                   | CullSettings::CLEAR_MASK
                                   ));
    camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
    camera->setCullingMode(osg::CullSettings::NO_CULLING);
    camera->setProjectionResizePolicy(osg::Camera::FIXED);

    // The camera group will always update the camera
    camera->setReferenceFrame(Transform::ABSOLUTE_RF);

    // XXX Camera needs to be drawn just before GUI; eventually the render order
    // should be assigned by a camera manager.
    camera->setRenderOrder(osg::Camera::POST_RENDER, 9999);

    // Add splash screen!
    camera->addChild(globals->get_renderer()->getSplash());

    Pass* pass = new Pass;
    pass->camera = camera;
    pass->useMastersSceneData = false;

    // For now we just build a simple Compositor directly from C++ space that
    // encapsulates a single osg::Camera. This could be improved by letting
    // users change the Compositor config in XML space, for example to be able
    // to add post-processing to a HUD.
    // However, since many other parts of FG require direct access to the GUI
    // osg::Camera object, this is fine for now.
    Compositor* compositor = new Compositor(_viewer, window->gc, viewport);
    compositor->addPass(pass);

    const int cameraFlags = CameraInfo::SPLASH;
    CameraInfo* info = new CameraInfo(cameraFlags);
    info->name = "Splash camera";
    info->viewOffset = osg::Matrix::identity();
    info->projOffset = osg::Matrix::identity();
    info->compositor.reset(compositor);
    _cameras.push_back(info);

    // Disable statistics for the splash camera.
    camera->setStats(0);
}

void CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
                                 GraphicsWindow* window)
{
    WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
    const SGPropertyNode* windowNode = (cameraNode
                                        ? cameraNode->getNode("window")
                                        : 0);
    if (!window && windowNode) {
        // New style window declaration / definition
        window = wBuild->buildWindow(windowNode);
    }

    if (!window) { // buildWindow can fail
        SG_LOG(SG_VIEW, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
        return;
    }

    // Create the Compositor using XML configuration.
    osg::ref_ptr<SGReaderWriterOptions> options =
        SGReaderWriterOptions::fromPath(globals->get_fg_root());
    osg::ref_ptr<osg::Viewport> viewport = new osg::Viewport(
        0, 0, window->gc->getTraits()->width, window->gc->getTraits()->height);
    Compositor* compositor = Compositor::create(_viewer,
                                                window->gc,
                                                viewport.get(),
                                                "Compositor/gui",
                                                options);
    if (!compositor)
        return;

    // Many other parts of FG require direct access to the GUI osg::Camera
    // object, the GUI pass must exist.
    const auto& passes = compositor->getPassList();
    auto match = std::find_if(passes.begin(), passes.end(),
                              [](const Pass* pass) { return pass->type == "gui"; });
    if (match == passes.end()) {
        SG_LOG(SG_VIEW, SG_POPUP, "CameraGroup::buildGUICamera: GUI compositor must contain a pass of type \"gui\"");
        delete compositor;
        return;
    }
    int guiPass = match - passes.begin();

    // Mark the window as containing the GUI
    window->flags |= GraphicsWindow::GUI;

    const int cameraFlags = CameraInfo::GUI | CameraInfo::DO_INTERSECTION_TEST;
    CameraInfo* info = new CameraInfo(cameraFlags);
    info->name = "GUI camera";
    info->viewOffset = osg::Matrix::identity();
    info->projOffset = osg::Matrix::identity();
    info->compositor.reset(compositor);
    info->guiPass = guiPass;
    _cameras.push_back(info);
}

Compositor *CameraGroup::buildVRMirrorCompositor(osg::GraphicsContext* gc,
                                                 osg::Viewport *viewport)
{
#ifdef ENABLE_OSGXR
    if (VRManager::instance()->getUseMirror()) {
        Camera* camera = new Camera;
        camera->setName("VRMirror");
        camera->setAllowEventFocus(false);
        camera->setGraphicsContext(gc);
        camera->setViewport(viewport);
        camera->setClearMask(0);
        camera->setInheritanceMask(CullSettings::ALL_VARIABLES
                                   & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
                                       | CullSettings::CULLING_MODE
                                       | CullSettings::CLEAR_MASK
                                       ));
        camera->setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
        camera->setCullingMode(CullSettings::NO_CULLING);
        camera->setProjectionResizePolicy(Camera::FIXED);

        // OSG is buggy and treats draw buffer target as separate from FBO
        // state. Be explicit about drawing to back buffer to reduce chance of
        // inheriting a GL_NONE, which is particularly likely with single target
        // CSM passes and stereo.
        camera->setDrawBuffer(GL_BACK);
        camera->setReadBuffer(GL_BACK);

        // The camera group will always update the camera
        camera->setReferenceFrame(Transform::ABSOLUTE_RF);

        // Mirror camera needs to be drawn after VR cameras and before GUI
        camera->setRenderOrder(Camera::POST_RENDER, 9000);

        // Let osgXR do the mirror camera setup
        VRManager::instance()->setupMirrorCamera(camera);

        Pass *pass = new Pass;
        pass->camera = camera;
        pass->useMastersSceneData = false;

        // We just build a simple Compositor directly from C++ space that
        // encapsulates a single osg::Camera.
        Compositor *compositor = new Compositor(_viewer, gc, viewport);
        compositor->addPass(pass);

        return compositor;
    }
#endif
    return nullptr;
}

CameraGroup* CameraGroup::buildCameraGroup(osgViewer::View* view,
                                           SGPropertyNode* gnode)
{
    CameraGroup* cgroup = new CameraGroup(view);
    cgroup->_listener.reset(new CameraGroupListener(cgroup, gnode));

    for (int i = 0; i < gnode->nChildren(); ++i) {
        SGPropertyNode* pNode = gnode->getChild(i);
        std::string name = pNode->getNameString();
        if (name == "camera") {
            cgroup->buildCamera(pNode);
        } else if (name == "window") {
            WindowBuilder::getWindowBuilder()->buildWindow(pNode);
        } else if (name == "splash") {
            cgroup->buildSplashCamera(pNode);
        } else if (name == "gui") {
            cgroup->buildGUICamera(pNode);
        }
    }

    return cgroup;
}

void CameraGroup::setCameraCullMasks(osg::Node::NodeMask nm)
{
    for (auto& info : _cameras) {
        if (info->flags & CameraInfo::GUI)
            continue;
        info->compositor->setCullMask(nm);
    }
}

void CameraGroup::setLODScale(float scale)
{
    for (auto& info : _cameras) {
        if (info->flags & CameraInfo::GUI)
            continue;
        info->compositor->setLODScale(scale);
    }
}

void CameraGroup::resized()
{
    for (const auto &info : _cameras)
        info->compositor->resized();
}

CameraInfo* CameraGroup::getGUICamera() const
{
    auto result = std::find_if(_cameras.begin(), _cameras.end(),
                               [](const osg::ref_ptr<CameraInfo> &i) {
                                   return (i->flags & CameraInfo::GUI) != 0;
                               });
    if (result == _cameras.end())
        return 0;
    return (*result);
}

osg::Camera* getGUICamera(CameraGroup* cgroup)
{
    CameraInfo* camInfo = cgroup->getGUICamera();
    if (!camInfo)
        return nullptr;
    return camInfo->compositor->getPass(camInfo->guiPass)->camera;
}

const CameraGroup::CameraList& CameraGroup::getCameras()
{
    return _cameras;
}

static bool
computeSceneIntersection(const CameraGroup* cgroup,
                         const osg::Vec3d& start,
                         const osg::Vec3d& end,
                         osgUtil::LineSegmentIntersector::Intersections& intersections)
{
    osg::ref_ptr<osgUtil::LineSegmentIntersector> picker =
        new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL,
                                            start, end);
    osgUtil::IntersectionVisitor iv(picker);
    iv.setTraversalMask(simgear::PICK_BIT);

    const_cast<CameraGroup*>(cgroup)->getView()->getSceneData()->accept(iv);
    if (picker->containsIntersections()) {
        intersections = picker->getIntersections();
        return true;
    }

    return false;
}

static bool
computeSceneIntersection(const CameraGroup* cgroup,
                         const std::vector<osg::Vec3d>& lineStrip,
                         osgUtil::LineSegmentIntersector::Intersections& intersections)
{
    osg::ref_ptr<osgUtil::IntersectorGroup> group = new osgUtil::IntersectorGroup();
    for (unsigned int i = 1; i < lineStrip.size(); ++i)
        group->addIntersector(new osgUtil::LineSegmentIntersector(
            osgUtil::Intersector::MODEL,
            lineStrip[i - 1], lineStrip[i]));
    osgUtil::IntersectionVisitor iv(group);
    iv.setTraversalMask(simgear::PICK_BIT);

    const_cast<CameraGroup*>(cgroup)->getView()->getSceneData()->accept(iv);
    if (group->containsIntersections()) {
        // Append each segment's intersections to the list
        intersections.clear();
        for (auto& intersector : group->getIntersectors())
            if (intersector->containsIntersections()) {
                auto* lineIntersector = static_cast<osgUtil::LineSegmentIntersector*>(intersector.get());
                auto& someIntersections = lineIntersector->getIntersections();
                intersections.insert(std::begin(someIntersections),
                                     std::end(someIntersections));
            }
        return true;
    }

    return false;
}

static bool
computeCameraIntersection(const CameraGroup *cgroup,
                          const CameraInfo *cinfo,
                          const osg::Vec2d &windowPos,
                          osgUtil::LineSegmentIntersector::Intersections &intersections)
{
    if (!(cinfo->flags & CameraInfo::DO_INTERSECTION_TEST))
        return false;

    const osg::Viewport *viewport = cinfo->compositor->getViewport();
    SGRect<double> viewportRect(viewport->x(), viewport->y(),
                                viewport->width(), viewport->height());
    double epsilon = 0.5;
    if (!viewportRect.contains(windowPos.x(), windowPos.y(), epsilon))
        return false;

    osg::Vec4d start(windowPos.x(), windowPos.y(), 0.0, 1.0);
    osg::Vec4d end(windowPos.x(), windowPos.y(), 1.0, 1.0);
    osg::Matrix windowMat = viewport->computeWindowMatrix();
    osg::Matrix invViewMat = osg::Matrix::inverse(cinfo->viewMatrix);
    osg::Matrix invProjMat = osg::Matrix::inverse(cinfo->projMatrix * windowMat);
    start = start * invProjMat;
    end = end * invProjMat;
    start /= start.w();
    end /= end.w();
    start = start * invViewMat;
    end = end * invViewMat;

    return computeSceneIntersection(cgroup,
                                    osg::Vec3d(start.x(), start.y(), start.z()),
                                    osg::Vec3d(end.x(), end.y(), end.z()),
                                    intersections);
}

bool computeIntersections(const CameraGroup* cgroup,
                          const osg::Vec2d& windowPos,
                          osgUtil::LineSegmentIntersector::Intersections& intersections)
{
    // Find camera that contains event
    for (const auto &cinfo : cgroup->_cameras) {
        // Skip the splash and GUI cameras
        if (cinfo->flags & (CameraInfo::SPLASH | CameraInfo::GUI))
            continue;

        if (computeCameraIntersection(cgroup, cinfo, windowPos, intersections))
            return true;
    }

    intersections.clear();
    return false;
}

bool computeSceneIntersections(const CameraGroup* cgroup,
                               const std::vector<osg::Vec3d>& lineStrip,
                               osgUtil::LineSegmentIntersector::Intersections& intersections)
{
    if (lineStrip.size() > 2) {
        if (computeSceneIntersection(cgroup, lineStrip, intersections))
            return true;
    } else if (lineStrip.size() == 2) {
        if (computeSceneIntersection(cgroup, lineStrip[0], lineStrip[1], intersections))
            return true;
    }

    intersections.clear();
    return false;
}

void warpGUIPointer(CameraGroup* cgroup, int x, int y)
{
    using osgViewer::GraphicsWindow;
    osg::Camera* guiCamera = getGUICamera(cgroup);
    if (!guiCamera)
        return;
    osg::Viewport* vport = guiCamera->getViewport();
    GraphicsWindow* gw
        = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
    if (!gw)
        return;
    globals->get_renderer()->getEventHandler()->setMouseWarped();
    // Translate the warp request into the viewport of the GUI camera,
    // send the request to the window, then transform the coordinates
    // for the Viewer's event queue.
    double wx = x + vport->x();
    double wyUp = vport->height() + vport->y() - y;
    double wy;
    const osg::GraphicsContext::Traits* traits = gw->getTraits();
    if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
        == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
        wy = traits->height - wyUp;
    } else {
        wy = wyUp;
    }
    gw->getEventQueue()->mouseWarped(wx, wy);
    gw->requestWarpPointer(wx, wy);
    osgGA::GUIEventAdapter* eventState
        = cgroup->getView()->getEventQueue()->getCurrentEventState();
    double viewerX
        = (eventState->getXmin()
           + ((wx / double(traits->width))
              * (eventState->getXmax() - eventState->getXmin())));
    double viewerY
        = (eventState->getYmin()
           + ((wyUp / double(traits->height))
              * (eventState->getYmax() - eventState->getYmin())));
    cgroup->getView()->getEventQueue()->mouseWarped(viewerX, viewerY);
}

void reloadCompositors(CameraGroup *cgroup)
{
    auto viewer_base = globals->get_renderer()->getViewerBase();
    bool should_restart_threading = viewer_base->areThreadsRunning();
    if (should_restart_threading) {
        viewer_base->stopThreading();
    }

    // Prevent the camera render orders increasing indefinitely with each reload
    Compositor::resetOrderOffset();

    for (auto &info : cgroup->_cameras) {
        // Ignore the splash & GUI camera
        if (info->flags & (CameraInfo::SPLASH | CameraInfo::GUI))
            continue;
        // Get the viewport and the graphics context from the old Compositor
        osg::ref_ptr<osg::Viewport> viewport = info->compositor->getViewport();
        osg::ref_ptr<osg::GraphicsContext> gc =
            info->compositor->getGraphicsContext();
        osg::ref_ptr<SGReaderWriterOptions> options =
            SGReaderWriterOptions::fromPath(globals->get_fg_root());
        options->setPropertyNode(globals->get_props());

        if (info->reloadCompositorCallback.valid())
            info->reloadCompositorCallback->preReloadCompositor(cgroup, info);

        // Force deletion
        info->compositor.reset(nullptr);
        // Then replace it with a new instance
        std::string compositor_path = info->compositor_path.empty() ?
            fgGetString("/sim/rendering/default-compositor", "Compositor/default") :
            info->compositor_path;
        Compositor *compositor = nullptr;
        if (info->flags & CameraInfo::VR_MIRROR)
            compositor = cgroup->buildVRMirrorCompositor(gc, viewport);
        if (!compositor)
            compositor = Compositor::create(cgroup->_viewer,
                                            gc,
                                            viewport,
                                            compositor_path,
                                            options,
                                            &info->mvr);
        info->compositor.reset(compositor);

        if (info->reloadCompositorCallback.valid())
            info->reloadCompositorCallback->postReloadCompositor(cgroup, info);
    }

    if (should_restart_threading) {
        viewer_base->startThreading();
    }
    fgSetBool("/sim/rendering/compositor-reload-required", false);
    fgSetBool("/sim/signals/compositor-reload", true);
}

void CameraGroup::buildDefaultGroup(osgViewer::View* viewer)
{
    // Look for windows, camera groups, and the old syntax of
    // top-level cameras
    SGPropertyNode* renderingNode = fgGetNode("/sim/rendering");
    SGPropertyNode* cgroupNode = renderingNode->getNode("camera-group", true);
    bool oldSyntax = !cgroupNode->hasChild("camera");
    if (oldSyntax) {
        for (int i = 0; i < renderingNode->nChildren(); ++i) {
            SGPropertyNode* propNode = renderingNode->getChild(i);
            const std::string propName = propNode->getNameString();
            if (propName == "window" || propName == "camera") {
                SGPropertyNode* copiedNode
                    = cgroupNode->getNode(propName, propNode->getIndex(), true);
                copyProperties(propNode, copiedNode);
            }
        }

        SGPropertyNodeVec cameras(cgroupNode->getChildren("camera"));
        SGPropertyNode* masterCamera = 0;
        SGPropertyNodeVec::const_iterator it;
        for (it = cameras.begin(); it != cameras.end(); ++it) {
            if ((*it)->getDoubleValue("shear-x", 0.0) == 0.0
                && (*it)->getDoubleValue("shear-y", 0.0) == 0.0) {
                masterCamera = it->ptr();
                break;
            }
        }
        if (!masterCamera) {
            masterCamera = cgroupNode->getChild("camera", cameras.size(), true);
            setValue(masterCamera->getNode("window/name", true),
                     flightgear::DEFAULT_WINDOW_NAME);
            // Use VR mirror compositor when VR is enabled.
            setValue(masterCamera->getNode("vr-mirror", true), true);
        }
        SGPropertyNode* nameNode = masterCamera->getNode("window/name");
        if (nameNode)
            setValue(cgroupNode->getNode("gui/window/name", true),
                     nameNode->getStringValue());
    }

    SGPropertyNode* splashWindowNameNode = cgroupNode->getNode("splash/window/name");
    if (!splashWindowNameNode) {
        // Find the first camera with a window name
        SGPropertyNodeVec cameras(cgroupNode->getChildren("camera"));
        for (auto it = cameras.begin(); it != cameras.end(); ++it) {
            SGPropertyNode* nameNode = (*it)->getNode("window/name");
            if (nameNode) {
                // Use that window name for the splash
                setValue(cgroupNode->getNode("splash/window/name", true),
                         nameNode->getStringValue());
                break;
            }
        }
    }

    CameraGroup* cgroup = buildCameraGroup(viewer, cgroupNode);
    setDefault(cgroup);
}

} // of namespace flightgear
