什么是 OSG?
全稱:OpenSceneGraph(開源場景圖)
定位:一個基于 C++/OpenGL 的高性能開源3D圖形開發工具包,專注于實時渲染和復雜場景管理。
核心思想:通過 場景圖(Scene Graph) 數據結構高效組織和管理3D對象(如模型、燈光、相機),優化渲染流程。
說白了,就是個基于C++的渲染引擎。
老規矩,學習任何代碼,第一個當然是我們的hello,world程序
安裝OSG
我這里用的是ubuntu系統,直接執行安裝命令:
sudo apt-get update
sudo apt-get install libopenscenegraph-dev cmake build-essential g++
安裝完成后,打開我們的編輯器vscode或者vim或者其他的,實現如下代碼和cmake文件。
從Hello,World開始
上代碼:
hello_world.cpp
#include <osgViewer/Viewer>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>int main(int argc, char** argv)
{// 創建一個視圖器對象osgViewer::Viewer viewer;// 創建一個 Box 形狀osg::ref_ptr<osg::Box> box = new osg::Box(osg::Vec3(0.0f, 0.0f, 0.0f), 1.0f);// 創建一個 ShapeDrawable 對象osg::ref_ptr<osg::ShapeDrawable> shapeDrawable = new osg::ShapeDrawable(box.get());// 創建一個 Geode 節點osg::ref_ptr<osg::Geode> geode = new osg::Geode();geode->addDrawable(shapeDrawable.get());// 創建一個 PositionAttitudeTransform 節點以設置位置、旋轉和縮放osg::ref_ptr<osg::PositionAttitudeTransform> transform = new osg::PositionAttitudeTransform();transform->setPosition(osg::Vec3(0.0f, 0.0f, 0.0f));transform->addChild(geode.get());// 將 Transform 節點添加到場景中viewer.setSceneData(transform.get());// 運行查看器主循環return viewer.run();
}
代碼什么含義先不用管,先運行看看效果。
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)project(OSG_HelloWorld)find_package(OpenSceneGraph REQUIRED COMPONENTS osgDB osgViewer)add_executable(hello_world hello_world.cpp)target_link_libraries(hello_world ${OPENSCENEGRAPH_LIBRARIES})
執行編譯命令:
mkdir build
cd build
cmake ../
make
運行效果
編譯完了運行看下效果:
./hello_world
OK,到這里我們就生成了一個立方體在場景中。是不是很簡單。_
今天就到這里了,下課。