{"id":"thunn/behavior-tree","name":"behavior-tree","scope":"thunn","platform":"roblox","description":"BehaviorTree is an implementation of the \"behavior tree\" paradigm for managing behavior. ","version":"5.0.2","latest":"5.0.2","versions":["1.0.2","5.0.0","5.0.1","5.0.2"],"license":"Apache-2.0","licenseRating":"safe","licenseCaveats":["Modified files must carry a notice of changes. If the package ships a NOTICE file, its attributions must be preserved.","The package archive does not include its license text; the license is declared in its manifest metadata."],"licenseVerified":false,"dependencies":{},"integrity":"96ef6e4af02b1316ffb80f6009dcb10ae5edc5d6c877706d992bb94be92f0cc7","likes":0,"downloads":0,"install":"forest install thunn/behavior-tree","url":"https://forest.dev/p/roblox/thunn/behavior-tree","files":"https://api.forest.dev/ai/package/roblox/thunn/behavior-tree/files","readme":"# BehaviorTree5(Latest update: May 5th, 2022)\n\nThis module is a fork of BehaviorTrees2 by oniich_n. The following are the improvements/changes:\n* Previously, Decorators would only work when parented to Task node. Now, they can be placed arbitrarily, and even chained together, and will work as expected. Internally, decorators work slightly differently, but I preserved the clever and efficient tree traversal algorithm that oniich_n implemented in BehaviorTrees2. Should still be just as fast.\n* Calling tree:run() will return the outcome of the tree (success [1], fail [2], running [3])\n* Added repeater node\n    * can repeat infinitely with a \"count\" parameter of nil or <= 0\n    * returns success when done repeating\n    * returns fail if a \"breakonfail\" parameter is true and it receives a failed result from its child\n* Added tree node which will call another tree and return the result of the other tree\n* If a success/fail node is left hanging without a child, it will directly return success/fail\n* Improved ProcessNode organization and readability by adding the interateNodes() iterator and the addNode() function\n* Changed node runner from using string node states to using number enums, to avoid string comparisons. Should be slightly faster.\n* Changed tasks to report their status by returning a status number enum, instead of calling a success/fail/running function on self\n* Added some more assertions in ProcessNode\n* Added comments and documentation so it's a little easier to add new nodes\n* Changed \"Task\"/\"Selector\" language to more generic \"Leaf\"/\"Composite\"\n\nV5: (May 2022)\n\n* Added Metaprox's External Task fork, to allow for rojo support\n* Fixed critical issue in behavior trees where multiple actors wouldn't properly keep track of their running states\n\n\nBehaviorTree5 is an implementation of the \"behavior tree\" paradigm for managing behavior. This allows us to create relatively complex patterns of behavior without much getting \"lost in the sauce\", so to speak. In *behavior trees*, actions are represented as **tasks**, or \"leaves\". These tasks are then collected in a container called a **tree**, which we \"run\" through in order to determine what task should be done at a given point in time.\n\n## Nodes\nNodes contain information about how to handle *something*. This can either be a task, or a manipulation of tasks. In BT2, there are 3 types of nodes:\n* Leafs\n* Composites\n* Decorators\n\nCreating nodes creates new objects, so be aware of that when reusing them for different agents.\n\n### Leafs\nLeafs are the foundation of BT3. They define how to act.\n\n#### Tasks\nThe most commonly used leaf is a `Task`. Let's take a look at how they're written.\n\n```\nlocal SUCCESS,FAIL,RUNNING = 1,2,3\n\nlocal NewNode = BehaviorTree5.Task({\n\n   -- 'start' and 'finish' functions are optional. only \"run\" is required!\n\n   start = function(object, ...)\n      object.i = 0\n      print(\"I've prepped the task!\")\n   end,\n\n   run = function(object, ...)\n      object.i = object.i+1\n      if object.i == 5 then\n          return SUCCESS\n      elseif object.i > 5 then\n         return FAIL\n   end\n\n   print(\"The task is still running...\")\n      return RUNNING\n   end,\n\n   finish = function(object, status, ...)\n      object.i = nil\n      print(\"I'm done with the task! My outcome was: \")\n      if status == SUCCESS then\n         print(\"Success!\")\n      elseif status == FAIL then\n         print(\"Fail!\")\n      end\n   end\n})\n```\nTasks are created by calling `BehaviorTree5.Task()`, with a table defining different **task functions**. When we run a behavior tree, it will \"process\" a node in the order `start -> run -> finish`. These functions will *always be called in this order*.\n\nThe `start` and `finish` functions are usually used to prep and cleanup the work that a task does, like initializing and destroying object properties. However, it is not necessary to define them. A task will function perfectly fine with just the `run` function alone.\n\nThe `run` function is the \"base of operations\" for a task. Here, we handle anything we would want to do. When we \"run\" a behavior tree, we would do so in steps. If we wanted real-time behavior, for example, we could run our trees within `RunService.Heartbeat`. Keep in mind the rate at which you will be processing trees when defining this function. Think about where to change the *task state* of a node when writing your function as well. Consider when it should `fail` so that you don't create unintended behavior. (i.e. attacking when you should be walking instead) Remember that you can **only call one state** per step.\n\nNotice the `object, ...` parameters passed to `start`, `run`, and `finish`. This object is a table that is passed to the tree when `run` is called on it, and any additional parameters are also passed along.\n\n#### Blackboard Query\n\nWhen running a tree on an object, a `Blackboard` table will be injected into the object if one does not exist already. This can be used by the Blackboard Query node for easy state lookup. A blackboard query is commonly used to see if a value is set or not in order to dictate the flow of relevant logic in a tree.\n\nYou can achieve the same effect with tasks, but it's a bit faster if you only need to perform a simple boolean or nil check\n\n#### Trees\nThe `Tree` is a special `Leaf` type that will execute another tree and pass the result of that tree to its parent.\n\n```\nlocal AnotherTree = BehaviorTree5:new(...)\nlocal NewNode = BehaviorTree5.Task({tree = AnotherTree})\n````\n### Composites\nThese nodes take multiple `Leafs` and give them order. In BT3, we have `Sequence`, `Selector`, `Random` types for `Compites`.\n\n#### Sequence\nThe `Sequence` process the nodes it is given in sequence of the order they are defined. If any of its subnodes fail, then it will not continue to process the `subnodes` that follow it and return a `fail` state itself.\n\n```\nSequence = BehaviorTree5.Sequence({\n    nodes = {\n        node1,\n        node2, -- if this failed, the next step would process node1\n        node3\n    }\n})\n```\n#### Selector\nThe `Selector` node will process every node until one of them succeeds, after which it will return `success` itself. If none of its subnodes succeed, then this `Composite` would return a `fail` state.\n\n```\nPriority = BehaviorTree5.Selector({\n    nodes = {\n        node1,\n        node2,\n        node3 -- this is the only node that suceeded, so Priority would return success\n    }\n})\n```\n#### Random\nThis `Selector` will randomly select a subnode to process, and will return whatever state that node returns.\n```\nRandom = BehaviorTree5.Random({\n    nodes = {\n        node1,\n        node2,\n        node3\n    }\n})\n```\nNodes can also have an optional `weight` attribute that will affect `Random`. Default is `1`.\n\n```\nlocal SUCCESS,FAIL,RUNNING = 1,2,3\n\nnode1 = BehaviorTree5.Task({\n    weight = 10,\n    run = function(object)\n        print(\"Weight: 10\")\n        return SUCCESS\n    end\n})\n\nnode2 = BehaviorTree5.Task({\n    weight = 10,\n    run = function(object)\n        print(\"Also weight: 10\")\n        return SUCCESS\n    end\n})\n\nnode3 = BehaviorTree5.Task({\n    weight = 200,\n    run = function(object)\n        print('You probably won't see \"Weight: 10\" printed'.)\n        return SUCCESS\n    end\n})\n```\n#### While\nThe `While` Only accepts two children, a condition(1st child), and an action(2nd child) It repeats until either the condition returns fail, wherein the node itself returns fail, or the action returns success, wherein the node itself returns success.\n\n```\nWhile = BehaviorTree5.While({\n    nodes = {\n        condition, -- If this node returns fail, return fail\n        action -- When this node returns success, return success\n    }\n})\n```\n### Decorators\nDecorators are nodes that wrap other nodes and alter their task state. Right now, there are `Succeed`, `Fail`, `Invert`, and `Repeat` decorators. `Succeed`, `Fail`, and `Invert` are pretty self-explanatory, and are helpful for when you start making more complex trees via nested `Collections`. \n\nThese can be written as such.\n```\nInvert = BehaviorTree5.Invert({\n    nodes = {nodeHere}\n})\n````\n`Repeat` decorators will repeat their children node tasks until `count`, or indefinitely if `count` is nil or < 0, after which they will return a `success` state. If `breakonfail` is true and its child node fails, it will stop repeating and return a `fail` state.\n````\nRepeat = BehaviorTree5.Repeat({\n    nodes = {nodeHere},\n    count = 3,\n    breakonfail = true\n})\n````\n## The Tree\nOnce you have your nodes set up and ready to go, we can start planting some trees. A `Tree` usually starts with any `Selector`, which should have `Task` nodes in them or other `Selector` nodes with other nodes in them. They can be instantiated by calling `BehaviorTree5:new()` with a `table` containing tree information as its only argument.\n\n```\nTree = BehaviorTree5:new({\n    tree = BehaviorTree5.Sequence({\n        nodes = {\n            node1,\n            node2,\n\n            BehaviorTree5.Random({\n                nodes = {\n                    node3,\n                    node4\n                }\n            })\n        }\n    })\n})\n```\nAs you can see, we can nest `Composite` nodes within each other. This is where the magic of behavior trees come in! \n\n### Running trees\nTo run a tree, call `:run` on the tree object, passing it a table. This table is the relevant object or actor that tree is dictating behavior for. You can also pass any additional parameters you desire, and these will be passed along to the task functions.\n\n```\nlocal actorObject = {...}\n\nTree = BehaviorTree5:new({\n    tree = BehaviorTree5.Sequence({\n        -- nodes from earlier\n    })\n})\n\nwhile true do\n    local treeStatus = Tree:run(actorObject)\n    wait(1)\nend\n```\n\nThat's pretty much all there is to BehaviorTree5. Go nuts with it or something. If you have any issues or questions, feel free to ask about them on the devforum post: \nhttps://devforum.roblox.com/t/btreesv5-rojo-support-fixes/\n","readmeTruncated":false}