htn_planner README

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

HTN Planner

HTN Planner is a C++ hierarchical task network planner for game AI. Domains are written in a small declarative language and translated ahead of time into native C. The runtime executes the generated planner directly and does not parse domain source during gameplay.

Project status

HTN Planner is under active development. Published releases are tested, while the public API, domain language and generated-code ABI continue to evolve.

Before upgrading, review the release notes for compatibility changes and migration instructions. Some updates require regenerating domains and rebuilding the integration.

Feedback, bug reports and integration experiences are welcome.

Overview

The repository includes:

Version 2.4.0 is being prepared. Domains use 0/1 for boolean matching; bare true/false are ordinary symbols. The debugger and natvis display BOOL as 0/1. Migrate old boolean literals and regenerate domains. Standalone callterm conditions continue to require a BOOL result.

Optional per-instance allocators now control owning lists and backtracking overflow. List pools can use a safe new/delete fallback; backtracking supports client-owned scratch memory and per-call usage statistics. See the list allocator and backtracking allocator lifetime contracts.

ABI migration: regenerate domains and rebuild the host and runtime bridge with matching headers and libraries. Previous generated modules are rejected.

Instrumented builds retain facts that the domain does not reference in HTNWorldState::GetUnregisteredFacts() for inspection. Those writes still return false, and the planner cannot query the captured rows. Plain builds retain their previous behavior. The instrumented C++ world-state layout also changes. Atom/list layouts remain unchanged. See the 2.4.0 release notes.

Native negative literals, numeric debugger labels and their compiler-tool migration requirements are documented in the 2.3.0 release notes. For Linux builds, hot reload integration and Windows Natvis distribution, see the 2.2.0 release notes. For the runtime-list, callterm and generated-code features introduced in 2.1.0, see its release notes. Upgrades from older releases must also follow the 2.0.4 migration guide and, for 2.0.2 or earlier, the 2.0.3 migration guide.

Domain example

(:domain GuardNPC top_level_domain

    (:method (run) top_level_method
        (patrol
            (and
                (guard_on_duty)
            )
            (
                (!move_to "checkpoint")
                (!scan_area)
            )
        )
    )
)

A successful decomposition returns a plan containing the primitive tasks !move_to and !scan_area. The engine assigns meaning to those tasks and decides when they start, complete or fail.

Choosing an integration pattern

See Planner use cases for NPC behavior, active-plan validation, squad coordination and AI Director integration flows. The client owns action execution, scheduling and cancellation.

Requirements

Windows

Premake, SDL, Dear ImGui, GoogleTest and the remaining development dependencies are included in the repository.

Linux

Ubuntu 24.04 x86_64 is validated with GCC 14 and Clang 18 using libstdc++. Follow the Linux build and SDK guide for dependency installation, compilation, tests, visual demos, hot reload and SDK consumers.

bash BuildAndTestLinux.sh Debug Release Profile ProfileDetailed
bash BuildAndValidateSDK.sh

The SDK script rebuilds all four Linux variants and validates external consumers. It reads VERSION unless --version is supplied; it does not increment the version or publish a release. HTNEditor is excluded on Linux while it remains experimental. See the validation record for scope and evidence.

Build and run the visual demo

Generate the Visual Studio solution from the repository root:

GenerateProjectFiles.bat

Build HTN.sln for x64. Use Debug to include generated decomposition capture and the visual debugger. Use Release for an optimized runtime build without debugger instrumentation.

Run:

bin/<configuration>-windows-x86_64/HTNDemo/HTNDemo.exe

The generated-only HTNDemo provides three views:

The demo loads world-state data for inspection, but its domain definitions are already compiled into native generated planners.

Compiler pipeline

flowchart LR
    Source[".domain source"] --> Lexer["Compiler lexer and tokens"]
    Lexer --> AST["Compiler AST"]
    AST --> Validation["Validation and linking"]
    Validation --> IR["Compiler IR"]
    IR --> Generator["C code generator"]
    Generator --> Native["Native generated planner"]
  1. HTNCompilerDomainLexer creates tokens and source ranges.
  2. HTNCompilerDomainSyntaxParser creates the compiler-owned AST.
  3. Validation and linking resolve declarations, includes, overrides and references.
  4. HTNCompilerIRBuilder lowers the linked domain into compiler IR.
  5. HTNCCodeGenerator emits C source and static metadata.
  6. The client build compiles that C source into the game or a domain module.

The AST and IR are build-time representations. Generated runtime execution does not retain or depend on them. See Compiler pipeline and IR boundary.

Translate a domain

Build HTNTranslator, then validate a domain without producing output:

HTNTranslator.exe --check path\to\npc.domain

Generate C for an exported entry point:

HTNTranslator.exe path\to\npc.domain CreateNpcHTN generated

The generated source exports:

extern "C" const HTNGeneratedPlannerDefinition* CreateNpcHTN_GetDefinition(void);

Useful translation options are:

--backtracking-policy=fixed-with-overflow|fixed-capacity
--backtracking-capacity=<positive integer>
--runtime-backtracking-support=disabled|enabled

Compile generated C with the same configuration definitions and ABI as the runtime. Regenerate domain source whenever the generated planner ABI changes.

Integrate with a C++ engine

The simplest integration uses HTNIntegration, which supplies HTNPlannerHook, HTNPlanningUnit and HTNDatabaseHook:

#include "HTNIntegration.h"

extern "C" const HTNGeneratedPlannerDefinition* CreateNpcHTN_GetDefinition(void);

HTNDatabaseHook Database;
HTNCallTermRegistry CallTerms;
HTNPlannerHook Planner(Database.GetWorldState(), CallTerms);

if (!Planner.SetGeneratedPlannerDefinition(CreateNpcHTN_GetDefinition()))
    return false;

HTNPlanningUnit Unit(Database, Planner, HtnSymbol::sGetSymbol("run"));
Unit.GetExecutionContext().MissingCallTermPolicy = HTNMissingCallTermPolicy::FailSilently;
const HTNDecompositionStatus Status = Unit.DecomposeTopLevelMethod();

The example explicitly chooses silent failure for missing callterms. To report them through your own diagnostics, configure Report and a callback as described in Missing callterm policy.

After a successful decomposition, use ResolveCurrentPrimitiveTask() and GetCurrentPrimitiveTask() to inspect the next action. Call CompleteCurrentPrimitiveTask() after the engine finishes that action. The engine owns action dispatch, replanning policy, scheduling and world-state updates.

Call terms connect domain expressions to engine functions through HTNCallTermRegistry and HTNCallTermBindingContext. The packaged IntegrationConsumer and CoreConsumer examples demonstrate the optional integration layer and the lower-level runtime API respectively.

Generated execution debugger

Instrumented builds can capture generated execution without changing planner logic:

#ifdef HTN_DEBUG_DECOMPOSITION
HTNGeneratedDebugger Debugger;
Debugger.SetEnabled(true);
Unit.SetGeneratedDebugger(&Debugger);
#endif

The debugger records methods, branches, conditions, axioms, tasks, results, source ranges and scoped values. Its data model is independent of ImGui; an engine can render the captured nodes in its own editor. HTNDemo includes an ImGui reference view.

The application owns the debugger object. Instrumented generated domains and their host runtime must use matching ABI definitions. See Generated execution debugger.

SDK package

On Windows, build and validate all eight SDK variants with:

BuildAndValidateSDK.bat

This command:

  1. Generates HTNSDK.sln.
  2. Builds the eight CRT, configuration and instrumentation variants.
  3. Creates a versioned directory and ZIP under dist.
  4. Extracts the package outside the source tree.
  5. Builds and runs its core, integration and dynamic-domain consumers.

On Linux, bash BuildAndValidateSDK.sh builds the four Linux variants, creates a .tar.gz and SHA-256 sidecar, and validates consumers with GCC and Clang. See the Linux guide for dependencies and binary compatibility.

To generate only the SDK solution:

GenerateSDKProjectFiles.bat

The package exports CMake targets for HTNFramework, HTNIntegration, HTNRuntimeBridge and HTNTranslator. Choose an SDK variant that matches the engine's CRT and instrumentation settings. See SDK variants and SDK distribution.

Repository layout

Path Purpose
HTNFramework Core data types, world state, compiler frontend, IR, code generator and generated runtime.
HTNIntegration Optional C++ engine integration and active-plan handling.
HTNRuntimeBridge Optional bridge for dynamically loaded generated domain modules.
HTNTranslator Command-line domain validator and C source generator.
HTNDemo SDL and ImGui generated planner demo.
HTNHotReloadDemo Example generated-domain DLL compilation and hot reload flow.
HTNEditor Domain authoring tool.
HTNLanguageServer Diagnostics and language tooling backend.
HTNVSCode VS Code extension client.
HTNTest Runtime, compiler, integration and regression tests.
HTNBenchmark Generated planner benchmarks.
Domains Example domains, includes and inheritance hierarchies.
WorldStates Example world-state inputs used by demos and tests.
SDK Packaging, CMake configuration and external consumer validation.
docs Architecture, debugger, SDK distribution and release documentation.

Validation

Build HTNTest and run its executable from the HTNTest directory so relative test assets resolve correctly:

..\bin\Release-windows-x86_64\HTNTest\HTNTest.exe

The test suite covers compiler diagnostics, AST and IR behavior, generated planning, backtracking, includes, overrides, call terms, lists, ABI validation, dynamic modules, concurrency and the public integration API.

See CI validation for the repository build matrix.

Documentation

Start with the domain language guide: a complete example followed by syntax, facts, methods, axioms, assignment, operators, callterms, lists, includes, backtracking and deferred decomposition.

The documentation index links the compiler architecture, generated debugger, SDK distribution and release guides. See CONTRIBUTING.md for development workflow and CHANGELOG.md for release history.

Contributors

The generated planner, compiler pipeline and public release are developed and maintained by Jose Antonio Escribano. The shared 2023 foundation retained in the core, parsing, world-state and integration layers was co-authored with Sandra Alvarez (HTN planner repository).

See CONTRIBUTORS.md and NOTICE.md for contributor credits and formal copyright attribution.

Third-party software

Applicable notices are included when producing an SDK package.

References

License

Licensed under the MIT License. See copyright and attribution and third-party notices before redistributing binaries or SDK packages.

Variable declarations

Use (= ?value expression) to declare and initialize a fresh local variable. The compiler rejects destinations already declared or used in the same path. == remains equality comparison; implicit (?value (call ...)) binding is rejected. See assignment syntax and migration.

htn_planner (urosidoki/htn_planner)

Ищем в базе…

Что это?HTN Planner — это планировщик иерархических сетей задач на C++ для игрового ИИ: домены пишутся на небольшом декларативном языке и заранее транслируются в нативный C, так что рантайм исполняет сгенерированный код напрямую, без разбора исходников домена во время игры.
Это рантайм-библиотека или в него также входят компилятор и инструменты?И то и другое: HTNFramework предоставляет основной рантайм, HTNTranslator компилирует исходники домена в C, а в репозитории также есть редактор, language server, расширение для VS Code, демо-приложение и бенчмарки.
Как его запустить?Сгенерируйте решение Visual Studio из корня репозитория и соберите HTN.sln для x64 (Debug для визуального отладчика, Release для оптимизированной сборки), затем запустите собранный HTNDemo.
Что нужно установить перед сборкой?Windows x64 с Visual Studio 2022 (ворклоад Desktop development with C++), MSVC v143, Windows SDK и CMake 3.25+, если подключаете упакованный SDK через CMake.
Можно ли просто подменить его новой версией?Нет — публичный API, язык доменов и ABI сгенерированного кода всё ещё развиваются, поэтому обновление может потребовать перегенерации доменов и совместной пересборки хоста, библиотек и DLL доменов согласно миграционному гайду релиза.
Для кого это предназначено?Для разработчиков игр на C++, которым нужно планирование поведения NPC внутри движка, например координацию отрядов или системы AI Director, а не решение только на скриптах.
Работает ли он также на Mac или Linux?Нет, проект сейчас нацелен только на Windows x64 с MSVC.
Как игра на самом деле исполняет план, сгенерированный этим инструментом?После декомпозиции движок вызывает ResolveCurrentPrimitiveTask() и GetCurrentPrimitiveTask(), чтобы получить следующее действие, а затем CompleteCurrentPrimitiveTask() по его завершении; диспетчеризация действий, планирование и перепланирование остаются на стороне движка.
Могу ли я увидеть, почему планировщик выбрал определённый путь?Инструментированные сборки включают сгенерированный отладчик исполнения, который записывает методы, ветвления, условия, аксиомы, задачи и связанные переменные; в демо входит просмотрщик на ImGui.
Какие дополнительные инструменты входят в SDK помимо рантайма?В репозиторий входят редактор доменов, HTNLanguageServer для диагностики, клиент расширения для VS Code, демо на SDL/ImGui, пример hot-reload, набор тестов и бенчмарки.
Как call-термы связывают логику домена с кодом моей игры?HTNCallTermRegistry и HTNCallTermBindingContext привязывают выражения домена к функциям движка, а вместо молчаливого сбоя из-за отсутствующих callterm можно настроить колбэк Report.
Какие есть похожие проекты?grit, MonoGame, cppinsights, zenc-lang, bgfx, spinel, SFML, GATE
Автор
urosidoki
Размер
10.4 MB
Звёзды
385
Возраст
2 мес
Коммиты · 90 дней