threepp README

README проекта с github.com/markaren/threepp. Одним файлом markdown: README.md.

threepp

Build License: MIT Conan Center PyPI

A cross-platform C++20 3D library with the high-level API of three.js, and two backends behind one scene graph: portable OpenGL, and a deferred Vulkan renderer with ray-traced shadows, reflections, AO and GI.

On top of that: a scene editor, PhysX robot simulation, simulated sensors with ground-truth labels for synthetic data, hardware-in-the-loop flight with ArduPilot, and Python bindings on PyPI.

An Otter X sea drone in a digital twin of a waterfront in Ålesund
An Otter X sea drone under way in a digital twin of a real waterfront in Ålesund, Norway, modelled from Kartverket lidar and sea charts and rendered by the Vulkan backend: the water reflects the moored boats and the buildings ashore (the scene is not in the repository)

New here? Getting started walks through the concepts the library is built from: the scene graph, ownership and lifetimes, geometry and materials, lights, the frame loop, loaders and the two backends. The examples folder is the de-facto reference.

Features

three.js parity. The API follows three.js r129, with selected features from r186 on the OpenGL path (shadow filtering, environment and background controls, material fixes, the newer post-processing passes).

Rendering beyond three.js

Simulation and perception

Content and tooling

Applications

The threepp scene editor

Both build alongside the library in a top-level build (THREEPP_BUILD_EDITOR).

Project status

threepp is built for research, prototyping and teaching, not as a production engine. APIs change, so pin a tag or commit if you need reproducibility.

The three.js port is the mature layer, and the one most users touch. The simulation layer on top (the Vulkan renderer, sensors, PhysX, the editor and Python) is where development goes, and it moves fastest. Limits worth knowing:

Example

#include "threepp/threepp.hpp"

using namespace threepp;

int main() {

    Canvas canvas{"Demo"};
    GLRenderer renderer{canvas};

    auto scene = Scene::create();
    auto camera = PerspectiveCamera::create(75, canvas.aspect(), 0.1f, 100.f);
    camera->position.z = 5;

    OrbitControls controls{*camera, canvas};

    scene->add(HemisphereLight::create());

    auto material = MeshPhongMaterial::create();
    material->color = Color::green;
    auto box = Mesh::create(BoxGeometry::create(), material);
    scene->add(box);

    canvas.onWindowResize([&](WindowSize size) {
        camera->aspect = size.aspect();
        camera->updateProjectionMatrix();
        renderer.setSize(size);
    });

    Clock clock;
    canvas.animate([&] {
        box->rotation.y += 1.f * clock.getDelta();
        renderer.render(*scene, *camera);
    });
}

Swap GLRenderer for VulkanRenderer and the scene code stays the same. Math classes are value types; everything else is created through a static ::create that returns a std::shared_ptr, and GPU resources are released when the last reference goes. threepp/threepp.hpp covers the three.js core; extras/, postprocessing/, splats/ and the newer objects are included explicitly.

Python

pip install threepp

Wheels for CPython 3.10 to 3.14 on Windows x64 and manylinux x86_64 carry the OpenGL and Vulkan renderers and CPU PhysX; the Windows wheels also carry the FSR 3.1 upscaler. macOS builds from source (OpenGL only). Releases are named by date; pin the one you tested.

import threepp as tp

canvas = tp.Canvas("offscreen", width=800, height=600, headless=True)
renderer = tp.GLRenderer(canvas)

scene = tp.Scene()
camera = tp.PerspectiveCamera(75, 800 / 600, 0.1, 100)
camera.position.z = 5

mat = tp.MeshStandardMaterial()
mat.color = 0x00aaff
scene.add(tp.Mesh(tp.BoxGeometry(), mat))
scene.add(tp.HemisphereLight())

renderer.render(scene, camera)
pixels = renderer.read_pixels()   # (H, W, 3) uint8 NumPy array
renderer.save_frame("out.png")

The module also exposes the Vulkan labels as NumPy arrays, PhysX articulations, CUDA interop and threepp.rl, a GPU-vectorized PPO stack. A headless canvas needs no display, so the same code runs on Colab and cloud GPUs. python/README.md is the full guide, with the extras (threepp[rl], threepp[editor]) and the Python examples.

Building

All core dependencies are bundled. CMakePresets.json holds the configurations CI builds:

Preset What you get
gl OpenGL backend, with examples, tests and the editor (start here)
gl-debug as gl, unoptimised and with debug info
vulkan the deferred Vulkan renderer (Vulkan SDK on PATH, or the vcpkg vulkan feature)
vulkan-aaa as vulkan, plus the FSR 3.1 and DLSS upscalers (Windows)
python the pybind11 threepp module
no-glfw build check only: no GLFW frontend, so no rendering
wasm Emscripten/WebGL2 examples (needs an activated emsdk)
cmake --preset gl
cmake --build --preset gl
ctest --preset gl

Each preset builds into build/<preset>. cmake --list-presets also lists the ci-* presets the GitHub workflow runs, and machine-specific presets belong in an untracked CMakeUserPresets.json that inherits from these. Without presets, cmake -B build and cmake --build build work as usual; add -DTHREEPP_USE_EXTERNAL_GLFW=ON to use a system GLFW.

A subset of the examples runs in the browser: try them online.

Some headers need extra packages when you consume them:

Header Dependency Notes
AssimpLoader assimp Import a wide range of 3D formats
ImguiContext imgui Dear ImGui utility
Physx*, ConvexDecomposition physx, v-hacd Physics simulation and concave colliders
Vulkan*, Ocean, ParticleField, SonarSensor, and others Vulkan SDK Linked only under THREEPP_WITH_VULKAN, which the threepp target propagates

Using threepp in your project

CMake FetchContent is the recommended and tested route:

include(FetchContent)
FetchContent_Declare(
        threepp
        GIT_REPOSITORY https://github.com/markaren/threepp.git
        GIT_TAG tag_or_branch
        GIT_SHALLOW TRUE
)
FetchContent_MakeAvailable(threepp)
target_link_libraries(main PUBLIC threepp::threepp)

Consumed this way only the library builds, and the example assets in threepp_data are never downloaded. A complete setup is in tests/threepp_fetchcontent_test, and threepp_wxwidgets embeds threepp in a wxWidgets window. threepp is also on Conan Center, which xmake can consume too; see doc/package_managers.md for both and their caveats.

Why?

Because C++ deserves nice things too. Also, because fun.

It also turns out to suit AI-assisted development: a three.js API that models already know, few dependencies, first-party source all the way down to the Vulkan shaders, and a short loop from code to a rendered image that can be captured headless and judged.

A drone light show writes threepp over the Stigfossen waterfall at Trollstigen
Vulkan and Warp: a drone light show writes the name at dusk over Stigfossen, in a digital twin of Trollstigen, Norway; the drones are a ParticleField and the waterfall is GPU parcels (the scene is not in the repository)
A drone flying low through a pine forest
Vulkan: a Norwegian pine forest, scanned trees placed by a stand simulation as instanced meshes, grass and heath on the floor, and a drone low over the ground (the scene is not in the repository)
Rover on a sand slope
Vulkan and Warp: a rover climbs loose sand in GPU grains, with slip plotted against tilt-bed data (rover)
OpenGL showpiece
OpenGL: room lighting, glass, soft shadows, GTAO, bloom and outline in one frame (showpiece)
Spot RL gait, procedural forest
Vulkan: an RL-trained Spot walks a procedural forest while its depth camera builds a live SLAM surface (spot_slam.py)
OpenGL studio scene
OpenGL from Python: soft shadows, ambient occlusion and a selection outline (gl_studio.py)
GPU particle field
Vulkan: a campfire ParticleField, marched as participating media (vulkan_fire)
Franka FR3 with a depth camera
OpenGL: a depth camera on a Franka FR3, placed by IK, scans a tray (lesson part 2, depth_map.py)
Sphero RVR following a ball
OpenGL: a Sphero RVR follows a ball by what its own camera sees, driven through the real robot's two drive commands (SpheroControl)
SVG loader
OpenGL and Vulkan: the SVG loader (svg_loader)

License

threepp is MIT-licensed. It ports the API and shaders of three.js (MIT) and bundles or fetches a number of third-party libraries and assets; see THIRD_PARTY.md for the full index, including the parts that are not MIT (the optional NVIDIA DLSS SDK, and the Boston Dynamics Spot model in threepp_data).

threepp (markaren/threepp)

Ищем в базе…

1.2K ·GitHub
Что это такое?threepp — это кроссплатформенная библиотека на C++20 для 3D-графики с привязками к Python, которая повторяет высокоуровневый API three.js. Она предназначена для создания 3D-сцен и симуляций в коде.
Это фреймворк, движок или просто библиотека?Это библиотека, которую подключают к своей программе на C++ или импортируют из Python. Редактор сцен и безголовый проигрыватель входят в состав как отдельные приложения, построенные на её основе.
Как добавить её в свой проект?Рекомендуемый и проверенный способ — CMake FetchContent. Также можно выполнить cmake -B build, а затем cmake --build build. Для Python установите wheel-пакеты threepp из PyPI.
Что нужно подготовить перед началом?Все основные зависимости уже включены в состав, поэтому для сборки с OpenGL нужны только компилятор C++20 и CMake. Для бэкенда Vulkan нужен Vulkan SDK, а wheel-пакеты Python поддерживают CPython 3.10–3.14 на Windows x64 и manylinux x86_64.
Работает ли рендерер Vulkan на моём Mac?Нет. Бэкенду Vulkan нужны расширения трассировки лучей, которых MoltenVK не предоставляет, поэтому на macOS следует использовать рендерер OpenGL (GLRenderer).
С какого бэкенда лучше начать?Начните с бэкенда OpenGL, который работает в Windows, Linux, macOS и браузерах через Emscripten/WebGL2. Vulkan выбирайте позже, если нужны трассировка лучей для теней, отражений и глобального освещения (GI).
Можно ли использовать её бесплатно в коммерческих целях?Библиотека распространяется под лицензией MIT. Некоторые встроенные или необязательные части не под MIT, в частности NVIDIA DLSS SDK и модель Boston Dynamics Spot в threeppdata, поэтому перед выпуском продукта проверьте THIRDPARTY.md.
Можно ли запускать её в CI без GPU?Да. В README сказано, что в CI нет GPU. Бэкенд Vulkan там работает на lavapipe со слоями валидации, которые проверяют соответствие спецификации, а не отрисованные пиксели.
Можно ли загружать существующие сцены three.js и 3D-модели?Да. Документы редактора three.js открываются без изменений. Загрузчики поддерживают glTF/GLB, OBJ/MTL, STL, COLLADA, SVG, URDF/xacro, PNG/JPEG, HDR и EXR, а USD и FBX подключаются по желанию.
Для чего нужна симуляция, кроме рендеринга?Она добавляет твёрдые тела, артикуляции, мягкие тела и транспортные средства на базе PhysX, а также симулированные датчики: лидар, глубины, IMU и камеры с эталонными метками для синтетических данных. Кроме того, она может в пошаговой синхронизации управлять немодифицированным летательным аппаратом ArduPilot.
Есть ли готовое приложение, с которого стоит начать?Да, threepp editor включает окно просмотра, иерархию, инспектор, отмену и повтор действий, а также режим Play на базе PhysX. Он собран для Windows и устанавливается командой pip install threepp-editor. Сцены сохраняются как обычный JSON three.js.
Почему автор говорит, что это подходит для разработки с помощью ИИ?API three.js уже знаком моделям, зависимостей немного, а исходный код доходит до шейдеров Vulkan. Благодаря этому путь от кода до отрисованного изображения короткий: его можно сохранить в безоконном режиме и проверить.
Какие есть похожие проекты?f3d, bgfx, filament, assimp, SculptForge, mutracer, spirula-studio, natural-disasters
Автор
markaren
Размер
309.5 MB
Звёзды
1.2K
Возраст
5 г
Коммиты · 90 дней