VTK——设置交互样式上的鼠标回调函数

函数介绍

VTKPointPickerInteractorStyle是一个自定义的交互样式类,它是VTK库中vtkInteractorStyleTrackballCamera类的子类。VTK(Visualization Toolkit)是一个开源的,跨平台的库,用于处理、渲染和视觉化科学数据。它包括一系列的类和方法用于3D计算机图形、图像处理和可视化。

vtkInteractorStyleTrackballCamera是VTK中的一个交互样式类,它定义了用户与3D场景交互的方式,例如:旋转、缩放、平移等。VTKPointPickerInteractorStyle类继承了vtkInteractorStyleTrackballCamera类,并重写了一些方法,以自定义用户的交互行为。


class VTKPointPickerInteractorStyle : public vtkInteractorStyleTrackballCamera
{
public:
    static VTKPointPickerInteractorStyle* New();
    vtkTypeMacro(VTKPointPickerInteractorStyle, vtkInteractorStyleTrackballCamera);

    void setObjectIndex(int index) { m_index = index; }
    int getObjectIndex() const { return m_index; }
    VTKPointPickerInteractorStyle()
    {
        LastPickedActor = NULL;
        LastPickedProperty = vtkProperty::New();
    }
    virtual ~VTKPointPickerInteractorStyle()
    {
        LastPickedProperty->Delete();
    }
    virtual void OnLeftButtonUp() override
    {
        // Forward events
        vtkInteractorStyleTrackballCamera::OnLeftButtonUp();
    }
    virtual void OnLeftButtonDown() override
    {
        int* clickPos = this->GetInteractor()->GetEventPosition();
        this->Interactor->GetPicker()->Pick(clickPos[0], clickPos[1], 0,  // always zero.
                                            this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer());

        double picked[3];
        this->Interactor->GetPicker()->GetPickPosition(picked);
//        std::cout << "Picked value: " << picked[0] << " " << picked[1] << " " << picked[2] << std::endl;

        // Forward events
        vtkInteractorStyleTrackballCamera::OnLeftButtonDown();
    }
//    virtual void OnMouseMove() override
//    {

//    }

private:
    vtkActor    *LastPickedActor;
    vtkProperty *LastPickedProperty;
    int m_index;

};

被重写的方法还能保留之前的功能吗?重写一个方法会完全覆盖父类中的该方法的实现。但是,可以在子类的方法中显式调用父类的方法来保留父类的功能。

例如,在VTKPointPickerInteractorStyle类的OnLeftButtonDown方法中,在方法的最后,调用了vtkInteractorStyleTrackballCamera::OnLeftButtonDown()。这样,就可以在执行完VTKPointPickerInteractorStyle类的OnLeftButtonDown方法的自定义操作后,再执行vtkInteractorStyleTrackballCamera类的OnLeftButtonDown方法。这样做可以保证在执行完子类的自定义操作后,还能执行父类的操作。

设置回调

下面是用于设置回调,同时为了在鼠标点击窗口时确认当前窗口索引,将每个窗口的索引或objectName存储在类的某个成员变量中,并添加一个方法来检索它。

class VTKPointPickerInteractorStyle : public vtkInteractorStyleTrackballCamera
{
    ...
public:
    void setObjectIndex(int index) { m_index = index; }
    int getObjectIndex() const { return m_index; }
    ...
private:
    int m_index;
};

然后在创建VTKPointPickerInteractorStyle对象时设置索引i。

    for(int i=0;i<8;i++){
    vtkSmartPointer<VTKPointPickerInteractorStyle> style =
        vtkSmartPointer<VTKPointPickerInteractorStyle>::New();
        style->setObjectIndex(i);

        render[i]->GetInteractor()->SetInteractorStyle(style);
    }
    

将交互样式设置为 nullptr,也就是清除交互样式,回到默认的交互方法。

render[i]->GetInteractor()->SetInteractorStyle(nullptr);