htn_planner README

The project's README from github.com/urosidoki/htn_planner. As one markdown file: 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.0.4 removes native method/task recursion from generated planners, extends callterm error reporting and fixes axiom output assignments/backtracking. It changes the public callterm error API and generated/runtime bridge ABIs despite the patch version. Migrate client configuration, regenerate domains and rebuild the host, libraries and domain DLLs together. See the 2.0.4 release notes and migration guide. When upgrading from 2.0.2 or earlier, also follow 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

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

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

To build and validate all supported SDK variants:

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.

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

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.

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)

Searching Database…

这是什么?HTN Planner 是一个面向游戏 AI 的 C++ 层级任务网络(HTN)规划器:领域用一门小型声明式语言编写,并提前翻译成原生 C 代码,因此运行时直接执行生成的代码,游戏过程中无需解析领域源码。
这是运行时库,还是也包含编译器和工具?两者都有:HTNFramework 提供核心运行时,HTNTranslator 把领域源码编译成 C,仓库还附带编辑器、语言服务器、VS Code 扩展、演示应用和基准测试。
怎么让它跑起来?在仓库根目录生成 Visual Studio 解决方案,并为 x64 构建 HTN.sln(要看可视化调试器用 Debug,要优化构建用 Release),然后运行生成的 HTNDemo。
构建之前需要安装什么?Windows x64 系统、Visual Studio 2022(含“使用 C++ 的桌面开发”工作负载)、MSVC v143 和 Windows SDK;如果通过 CMake 使用打包的 SDK,还需要 CMake 3.25+。
直接换上新版本安全吗?不安全——公共 API、领域语言和生成代码的 ABI 仍在演变中,升级可能需要按照版本迁移指南重新生成领域代码,并把宿主程序、库和领域 DLL 一起重新构建。
它是面向谁的?面向需要在引擎内进行 NPC 行为规划(例如小队协同或 AI Director 系统)的 C++ 游戏开发者,而不是只需要脚本化方案的人。
它也能在 Mac 或 Linux 上运行吗?不能,该项目目前仅面向使用 MSVC 的 Windows x64。
游戏实际如何运行它生成的计划?分解完成后,引擎调用 ResolveCurrentPrimitiveTask() 和 GetCurrentPrimitiveTask() 获取下一个动作,动作完成后调用 CompleteCurrentPrimitiveTask();动作分发、调度和重新规划由引擎自己负责。
我能看到规划器为什么选择某条路径吗?带插桩的构建包含一个生成的执行调试器,可记录方法、分支、条件、公理、任务和绑定的变量,演示中还附带一个 ImGui 参考查看器。
除运行时外,SDK 还附带哪些工具?仓库包含领域编辑器、用于诊断的 HTNLanguageServer、VS Code 扩展客户端、SDL/ImGui 演示、热重载示例、测试套件和基准测试。
调用项(call term)如何把领域逻辑接到我的游戏代码上?HTNCallTermRegistry 和 HTNCallTermBindingContext 把领域表达式绑定到引擎函数,你还可以配置 Report 回调,避免在缺少调用项时静默失败。
What are similar projects?MonoGame, cppinsights, bgfx, zenc, spinel, SFML, GATE, rust-analyzer
Creator
urosidoki
Size
10.4 MB
Stars
369
Age
29d
Commits · 90 Days