.NET Programming Manual

warning: Parameter 1 to generic_productapi() expected to be a reference, value given in /home/visual3d/visual3d.net/community510/includes/module.inc on line 386.

Overview

Intended Audience for Manual


Though examples may be provided in C#, it applies to any .NET programming language supported with Visual Studio (or SharpDevelop and other IDEs), including C#, Visual Basic , C++/CLI, and IronPython.

This documentation is primarily written for programmers and more technical scripters, but also describes major concepts for the new way of defining Entities and Components through toolset (instead of via code) which is one of the primary features of the v0.9.9 release.

Topics Covered


This focuses on the new types of components which can be assembled and configured through the toolset to define Entities (such as Characters, Vehicles, Avatars,  Doors, Weapons, Equipment ), focusing on how to define new components (eg. Abilities, Actions, Events and Entity types) which can be used by non-programmers to setup and configure new entitys (as reusable assets / prefabs shown in Asset Explorer, able to be drag-dropped into the scene, for example) as well as how to define gameplay / mission / scenario scripting (for instances of those entity assets placed into scenes, for example) through Triggers (Scriptable Persisted Events, replacing old Command Mapping way of doing this), Triggered Areas (Proximity Triggers), Behavior Trees, and Key Mappings. 

It also covers how to edit Key Mappings (for the Global Key Map, or Entity type-specific Key Mappings defined with the Input Controller presets) and how to map animations and actions to those Key Mappings.


Related Documentation

 

Creating Visual3D Component Classes with Visual Studio, C#, Visual Basic .NET (VB), C++/CLI, and other .NET Languages

Creating and Using Component Classes and Assets


You can add Scenarios, Entities, Abilitys, Actions and other components into the scene by drag-dropping them from Asset Explorer onto the Scene Editor (Design tab) viewport, or right click on th entity in the Scene Editor or World Explorer (or Asset Explorer, for entity prefabs), and using the "Add" context menus, or using the Add button(s) in the Scene Editor toolbar.    Then after adding a scenario (or other entity/component), it will be selected automatically, you can configure its properties (settings or parameters) in the Object Editor tool window, and expand its abilities, states, and other components there to edit their properties as well.  Also, you can modify existing entities and scenarios in the scene by selecting it in World Explorer (eg. using the search filter box) or clicking on the entity in the Scene Editor (Design tab) viewport, or, if it was added to another "prefab" asset instead of the scene, by selecting that asset in Asset Explorer.  
 
You can use the growing library of components that come standard with Visual3D, such as RobotWarGame, AssaultDroid, Missile, Attack, without any need for programming, or you can create your own component classes based on existing demo ones, or modify the existing ones, most of which have the C# source code provided for them.  You can use the Object Editor to edit any public fields or properties you had defined on your own custom component classes, allowing you or your scripters/programming to provide highly reusable building blocks for your games and simulations which can be fully used and configured by those designing or building the virtual world. 

You can create multiple "prefab" assets for any type of component, whether Scenario, Entity, Ability or Action, for quickly reusing common setups. And, for entities, you can configure their Instance property for each instance (and the default for the prefab) to control whether each instance will be saved as completely unique or share part or all of the settings, components, and edits made to the prefab it was created from, so that they apply to the instances when they are next loaded (eg. the scene they are in is loaded or reloaded).

Through this "Smart Copy" feature for Entity Prefab instances, y can create your own "virtual entity classes" simply by creating an entity prefab asset (selecting its Object Type, like Character, Vehicle, etc., or by creating a copy of an existing entity prefab asset), and just adding abilities, entity states (aka. actions/triggers), and other basic entity building blocks onto it using drag-drop and right-click context menu in Object Editor or Asset Explorer, and use the Behavior Tree Editors and other editors for Conversation, Entity, and Key Maps, to name a few - to define the gameplay or simulation logic visually instead of through programming or scripting languages.

And, you can even use the Visual3D's built-in Script Editor to define your own component classes by creating Python Modules or Python Actions assets.
 

Edit-and-Continue, Visual Studio Integration, and Live Importing of Component Classes


We support use of edit-and-continue with Visual Studio, allowing you to make edits to live components and watch them take effect, without any need to restart the toolset or even reload the scene.  Similarly, Visual3D is unique in allowing you to take advantage of the benefits of Visual Studio's best of breed tools for programming, debugging and rapid development of games/simulations with .NET, while at the same time accelerating and simplifying your building of virtual worlds using the wide range of editors and visual authoring tools included in the Visual3D All-in-One toolset.

Visual3D supports live importing or reloading of media assets  (eg. textures, models, etc.) when it automatically detects that the files they were imported from have been modified have been modified.  Building on this, Visual3D will, in an upcoming release, also provide live importing of new component classes without needing to restart the toolset, as well as have any edits made to existing component classes take effect when your reload the scene (eg. via Ctrl-Shift-R) or begin editing or viewing a different scene or entity prefab.
 
You can also create your own reusable component library with any .NET language and IDE, which can be reused by any of your multiple world projects, similar to how the Standard Assets project is reused.  The easiest way to do this is by compiling a .NET assembly .dll which has the predefined name of My Assets.dll directly into the My Assets/ project folder (not in a subfolder like bin) or into the Visual3D/Projects/ folder (where Standard Assets.dll is found).  You can find out more about how to define many new plugin/library projects with your own names, instead of adding My Assets.dll to the existing My Assets project, by following the steps described in the documentation for "Creating Engine Plugins and Component Libraries with any .NET Language".
 

Creating Engine Plugins and Component Libraries with any .NET Language

In addition to using Visual Studio with the C# project automatically generated for you, you can add projects for any other .NET language such as Visual Basic, IronPython, C++/CLI or JavaScript, and use those as well to define your own custom component classes which will automatically appear in Asset Explorer for use from the toolset.  

The Visual3D toolset automatically generates a Visual Studio solution .sln and C# .csproj project file - with a few (not required) sample components in C# - for you when you create a new world project, and then automatically compiles this (just when the project is first created) to <Visual3D Install Path>/Visual3D/Projects/<World Project Name>.dll.  
Visual3D also automatically compiles these auto-generated solutions and projects when it first creates them.when you use Visual3D to create a new world project.

However, that sample C# project is not required, and you can develop and create entity classes, scripting components, and plugins for the Visual3D engine and toolset with any .NET language and IDE of your choice, including free IDEs such as Visual C# 2010 (or 2008) ExpressVisual C++ 2010 ExpressVisual Basic 2010 ExpressSharpDevelop IDE for C#, VB.NET and Python-like Boo (which can import the auto-generated .sln solutions), as well as commercial IDEs like Visual Studio 2008, 2010, and 2012 for example.
Any .NET assembly compiled to <Visual3D Install Path>/Visual3D/Projects/<World Project Name>.dll (even if it was compiled from C++/CLI or VB, etc.) will automatically be loaded and have its components (derived from base classes like AvatarBase, EntityBase, AbilityBase, ActionBase, etc.) will have prefab assets, for for your entity and scripting classes, automatically added  Asset Explorer in the Visual3D toolset.  
Your project should reference Visual3D dlls (for example, Visual3D.dll, Visual3D.Engine.dll, Visual3D.Scripting.dll, and Microsoft.Xna.Framework.dll, etc. - which are all found in the Visual3D/ folder), targeting .NET Framework 3.5.1 (.NET 4.0 will be supported later), as well as often Standard Assets.dll and Demo Assets.dll (which are found in the Visual3D/Projects/ folder, pre-compiled so you don't need Visual C# Express to compile them yourself).

You can also create reusable component library dlls which are shared between projects, similar to Demo Assets or Standard Assets, by compiling them to <Visual3D Install Path>/Visual3D/Projects/<Component Library Name>.dll and then adding a Content Package with the same name as your dll (without the .dll extension) to the Content Packages, when editing your world project in Visual3D toolset.  
This can be done by going to Settings (menu in top-right of the toolbar) > World Manifest, then right clicking on Content Packages property in Object Editor > Add Item, then expanding the Content Package and changing its Name property to the file base name for your plugin or shared component library .dll (without the .dll extension), then performing File > Save World Project and restarting Visual3D.   Alternatively, you can manually edit the World Manifest XML file (as found at <Visual3D Install Path>/<World Project Name>/<World Project Name>.v3d) to add a new ContentPackage there.

For each class you have which is either derived from a Visual3D base class or which has [ComponentTypeAttribute] applied to your class (or to your own base classes), one asset prefab will automatically be added to Asset Explorer for that class (if no other component with that class already exists in the Asset Database). 
New classes will be automatically added to Asset Explorer as components whenever your startup thet toolset  (after recompiling your project or adding a reference to a new Content Package), and existing prefab assets will be updated when your classes are updated.
You can easily find these new components (just like you can find your own model, texture and media files in your project or My Assets folder) by starting to type the class name (sometimes with spaces added between words) into the search/filter box at the top of the Asset Explorer tool window in the editor, and the AssetGroup (top level folder) and Category (subfolder path) that component is found is customizable through the [ComponentTypeAttribute].
Common base classes which you can use to create your own avatar, entity and scripting component classes include ModelEntity, Scenario, Ability or ActionBase, or derived demo classes like RobotWar, AssaultDroid, NewLizardman, or Character). 

Common Component and Entity Classes

You can find more details regarding base classes, common component types, and demo implementations of avatars, actions, and abilities in the Demo Game, Entity, and Scripting Component Classes Overview and API Reference Documentation.

Key Base Classes

  1. EntityBase
    1. General base type for complex entities ranging from user-controlled Players, AI-controlled Enemies, NPCs (eg. with dialogue/trade), Vehicle, (Simulation/RTS) Units, or Creatures (Simulated animals or flocks)
  2. Ability and BehaviorSystem (derives from ActivatedComponent)
  3. ActionBase (derives from LightComponent)
  4. LightComponent (and EntityComponent, for "data objects")
    1. Currently EntityComponent is required for full component functionality (Name, Prefab/Prototype Asset Linking, etc.), however, EntityComponent will soon be fully merged into ComponentBase.
  5. BaseEvent (and more commonly used EventWithTarget, EventWithSubject derived classes)
    1. EventWithTarget , which defines the "Target" (Actor/Entity/Owner) parameter (as well as EventWithSubject, which defines both Target and Subject parameters) are most common base classes used for events.
  6. Condition (derived from ActionBase)
    1. Evaluates the condition, such as IsInArea, IsKeyPressed, IsDoorOpened used by ConditionalTrigger
  7. Trigger: EventTrigger and ConditionalTrigger (Trigger is a composite action, which waits for the event, and when an event occurs, executes its child actions in parallel.)
    1. Usually Triggers should be created for an Entity (or SceneObject) asset (prototype/prefab/preset) defined in Asset Explorer, which is then placed (instanced) into scenes, instead of defined via code.  However, some abilities will automatically add new triggers to their owner entity, when they are attached to an entity, which part of how they expose scriptable events or new actions that they extent that entity with.
  8. EventBase (derived from EventArgs, used for non-scriptable events, often BaseEvent is used instead, as is currently required for scriptable events (which work with Triggers, Behavior Trees, etc.) 


Entities, Actors, Scene Objects

 

Entities

 
It is now suggested to derive from EntityBase instead of SceneObject or Actor, and to derive from AvatarBase instead of Avatar, since these are the base classes for user-defined scriptable entities which "have" or "own" a SceneObject (eg. an Actor) for their appearance, a SpatialNode for their position, and a PhysicalEntity / ObjectPhysics for their physics/collision support, as well as other components (or abilities) which are now decoupled (more modular) so that they can be more easily used if/when needed, or added to any SceneObject in the scene entire through the toolset.
 
Class Hierarchy
  EntityComponent (in Visual3D)
    ActivatedComponent (in Visual3D)
      EntityBase (in Visual3D)
        SceneEntity (in Visual3D.Engine)
          ModelEntity (in Visual3D.Engine)
             AvatarBase (in Visual3D.Demo)
 
To extend the functionality of entity we do not recommend inherit from entity class (AvatarBase for example). Instead of this, we recommend to create their components, abilities. And combine entity of them.
 

Scene Objects (legacy base class)

 
SceneObject (as well as Actor) are common base classes to allow customized rendering (appearance or low-level engine / scene graph support), though they had been used previously as base classes for user-defined Avatars, it is now suggested that such user-defined "entity" or "item" classes derive from EntityBase (or AvatarBase) class instead of SceneObject, Actor or Avatar.
In some cases it may still be neccisary to define a class derived from SceneObject or Actor.  However, in those cases, it is suggested that a new EntityBase-derived class (which is tightly coupled / mapped 1-to-1 with the new SceneObject-derived class) should often be defined.  Most of the editable and persisted or high-level (eg. game/application-specific) properties and logic defined on the EntityBase-derived class instead.  We will be reducing the number of cases in which users need to derive from SceneObject, Actor or Avatar base class at all.

Entities and Base Entities examples

  • AvatarBase (General base type for complex entities ranging from user-controlled Players, AI-controlled Enemies, NPCs (eg. with dialogue/trade), Vehicle, (Simulation/RTS) Units, or Creatures (Simulated animals or flocks))
  • CharacterBase
    • AssaultDroid
    • NewLizardman
  • CreatureBase
    • Golem
    • SeaBeast
    • FlockOfSeagulls
  • WatercraftBase
    • GalleonShip
  • AircraftBase
    • FlyingAvatar
  • BaseVehicle
    • DesertPatrolVehicle
    • MitsubishiPajero
  • Missile (various projectiles used with the Missile Launcher)
    • Rocket
    • WaterBall
    • Laser
    • Bullet
  • DesignTimeEntity/DesignTimeModelEntity (Base class for entities which are not usually visible at runtime (eg. during gameplay) but are visible during editing to allow positioning them. These can also be considered "Scripting Entities")
    • Area
    • SceneArea
    • WayPoint
    • SpawnPoint
 

Creating Your Own Entity Assets and Classes


You can create a copy of one of the existing Entity assets / Prefabs, for example, by selecting "F-38" or "Lizardman" under Entities folder in Asset Explorer, then right clicking it and selecting "Create Derived Copy", renaming it, and customizing it in Object Editor (and Entity/Model Editor) and drag-dropping it into a scene.  
You can also right click on a folder in Asset Explorer like Entities and select   > Add New (or click on the "+" icon in Asset Explorer toolbar) and select one of the more common Entity classes (or your own common prefabs/presets if you drag-drop them into the Base Types group in Asset Explorer).

You can also create a new Avatar class by creating a copy of one of the sample entity classes (as listed below in Example Classes for Entities section) and adding it to your own Visual Studio project (such as the .csproj generated for you by Visual3D in your world project folder when creating a new world).  For example, you can copy the file found at \Demo Assets\Actors\Custom\F38Jet.cs, renaming it to something like Aircraft.cs, renaming the class  to something like Aircraft, apply the ComponentTypeAttribute to ensure it will get automatically added as an Entity asset to Visual3D, such as by applying [ComponentType("Entities", "Vehicles")] and [DataContract] (if not already defined) to the class.  (For your most common entity or component classes, you can apply [AssetBaseType] attribute as well to them, to have them automatically added to Base Types asset group, to show up in the Add New > context menu.)

Then, when you next startup Visual3D Architect, it should show up in Asset Explorer (in this example, under Entities/Vehicles).  You can find it there and select it to continue configuring it, and setting up/selecting a model for it.

You could then select your avatar/entity prefab asset (which, for example, you had created through right click > Create Derived Copy in Asset Explorer or which was auto-created for your own custom class defined in, for example, C# code, which had [ComponentType] and [DataContract] attributes applied to it). 
After selecting the asset, go to Object Editor and change its model by clicking on "..." for the Model property and selecting your model from the Model Selector dialog shown.

You can configure other properties shown in Object Editor for it, as well as attach Abilities and other components or child objects to it (eg. via Add New, Add Asset, or other context menu options shown when right clicking your asset in Asset Explorer) and can preview and further configure it by double clicking on your asset and previewing it in Entity Editor (Entities > Entity tab), and editing the shared settings for its Model (Physics, etc.) through Model Editor (Entities > Model tab).  

One of common properties to edit for it is the Object Type (or Physical Entity Class) property, for example to change it from being an Obstacle to being a Character or Vehicle or Scripted Movement Object or Moveable (Physics-controlled / Dynamic) Object.  In v0.9.7, this and a few other common properties are shown in a dialog the first time you try to drag-drop a new Model into the scene. 

Creating Entity Prefabs and Instances Example

Creating New Entity Types (Prefab Assets) for Models

Create a new Entity (Prefab) Asset by one of the following methods:

  1. Select one of the common Base Types to create an instance of, for example by:

    1. Right clicking on folder in Asset Explorer (any under "Entities", "Objects" or for a specific Entity type like Weapons, Items, Avatars, etc.) and select > Add New > Actor (or Avatar, Vehicle, etc.)

    2. Click on the "+" ("Add/Create New") icon (shown the a "+" symbol icon) in Asset Explorer toolbar, and select the type of asset to be created (which will be added into default group/folder for that asset)

  1. Create Copy of Existing Asset

    1. Right click on an existing Entity Asset in Asset Explorer and select > "Create Derived Copy"

    2.  of an existing Asset an instance of a common "Base Type", which includes

    3. Avatar (any Entity which can be controlled by user/player or AI), with specialized Avatar types including:

      1. (Ground) Vehicle
      2. Aircraft (or Flying Avatar)
      3. Watercraft (or Ship)
  1. Right click on a Model in Asset Explorer and select > Create Actor, and an Actor with that model will be added into the default location (under Objects/ or Entities/ folder)

  2. Create Prefab from Object in the Scene

    1. Right-click on any Object in Scene Editor or World Explorer and select "> Save as Base Asset"

      1. Or select multiple objects instead of a single one and right click > "Save Objects as Base Assets" (which will create a separate Asset/Prefab for each selected object, and place them all in the same asset folder)
    1. Then select the Asset Folder (for the Asset Library/Database, like shown in Asset Explorer) where to place the new asset

      1. Rename the asset and/or create a new folder if desired here or after it is created

    1. where in Asset Explorer to save the new assets to o, and thenor "Save as Base Assets" and then select category (folder) to place it in, find(in Asset Explorer) and select > Add New > Actor (or Avatar, Entity, Vehicle, etc.)

Select Model and Configure Settings For Entity

  1. Going to Object Editor tool window after creating the entity (or after selecting the entity, in Asset Explorer if was an Entity Type asset, or from World Explorer if it was an entity instance in the scene, or from drop-down at top of Object Editor if was recently selected) selected to that its properties can be edited in the Object Editor tool window.

  2. You can then select (or change) the Model used by the Entity via the Model Selector dialog shown when clicking on the "…" button next to the Model property in Object Editor (found under the "Appearance" or "Visual Object" property category).

  3. You can find a model in Asset Explorer or Model Selector dialog by typing part of its name (or folder) into the Search/Filter box shown at the top of it.

  4. Alternatively, you can right click on the Entity (eg. in Asset Explorer or World Explorer) and select > Add Asset (or Add Instance) > Models > {Path to model from Project Folder}"

Place an Instance of Entity Type (or Model) Into the Scene

  1. Drag-drop an Entity (Object, Avatar, Actor, etc.) Asset or Model from Asset Explorer onto the Scene to create (and place) an "Instance" of it

    1. You can drag this onto the Scene Editor (viewport) to place it at mouse cursor position as a top-level child (attached to) the Scene (as a child of its "Scene Graph" root node)

    2. Or you could drag-drop a Model from Asset Explorer onto Scene Editor, which will result in a new Entity being created

    3. based on the Model's Object Type property, whether it has a Skeleton or not),

  1. When a Model is first used/selected (via drag-drop or otherwise) for use by an Entity (Actor scene object), you will see a dialog allowing you to choose what type of Entity it should be (and what type of collision/physics it should have), by selecting its Object Type (eg. Character, Vehicle, Obstacle, Weapon, etc.)

    1. The default Object Type (Physical Class) is "Obstacle" which will result in an "Object" (aka. Actor) entity type

      1. Obstacle is a physical/collidable object which, by default, uses a box collision shape and is optimized for static (not moved at runtime) use.
      2. If the Model has a Skeleton (eg. bones or skeletal animations), then it will default to an Object Type of Character and an Entity Type of Avatar (AvatarBase Entity Class, Avatar SceneObject Class).
      3. You can change the Object Type from (basic model instance) scene object) and an Object Type of "Obstacle" (making it physical, collidable, but optimized for static
    1. You can (or will) be able to select an existing Entity (Type or Base Type) Asset to use for it instead of the default one.it created, usually an Actor (basic "Object" entity or model instance Scene Object) will be created.

Create an Attached Entity Spatially Linked to a Parent Object/Entity

  1. You can drag it onto an Entity from Asset Explorer onto a different entity shown in World Explorer (for an instance in the scene) or shown in Asset Explorer or Entity Editor (Entities > Entity tab) for to create a new Entity which is attached as a spatially linked "child" to the existing "parent" Object/Entity

    1. As a child object, the new entity instance will be moved with (aka. spatially linked to) its parent object, as well as hidden/shown, saved/loaded, grouped (in World/Asset Explorer), and owned by its parent object.

  1. Or, you can hold right mouse button down during drag-drop from Asset Explorer onto Scene Editor (viewport) - possibly also onto Entity Editor (Entities > Entity tab) as well - to perform "Advanced Drag Drop".

    1. Then select "Attach To {Parent Object Name}" from context menu to specify which of one or more objects under the mouse cursor the new entity should be attached as a child to.
      (By default, objects aren't attached when drag-dropped over another object, to avoid accidental attachment)

  1. Or you can right click on Scene Editor (viewport) or parent Entity/Object (in World Explorer) and select Entity Type to create an instance (added to scene, or attached to parent object/entity) by selecting the entity type from a context menu instead of via drag-drop

    1. You can select from the "Add New" context (right click) menu for common entity Base Types / Classes found in "Base Types" group in Asset Explorer

    2. Or you can select from the "Add Instance" context menu (to create an instance of user-defined entity types/prefabs/presets and models)which shows a submenu for each folder in Asset Explorer)for all other Entity assets in Asset Explorer/Library/Database, with a subfolder for each Asset)

  1. Or you could drag-drop a Model from Asset Explorer onto Scene Editor,

  2. In most places where an Entity (or Actor/SceneObject) can be drag-dropped, you can also drag-drop a Model (from Asset Explorer)

  1. If placed into the Scene, the entity instance (aka. Scene Object) can be manipulated (moved, scaled, and rotated) through by dragging it with the mouse (moving the mouse while holding down left, right, and/or middle mouse buttons). 

    1. Different combinations of mouse buttons and the Alt, Shift, and Ctrl modifier keys will result in different manipulations (movement and rotation on different axes and scaling in different dimensions).

    2. Also the manipulator Widget shown in corner of the Scene Editor (when in Design mode and an object is selected) can be used to move, rotate, and scale it for specific axes or dimensions

    3. This is covered in more detail in the Scene Design tutorial videos and Keyboard & Mouse Reference Sheet (Keyboard/Mouse/Hotkey) from the Scene Design user manual page.
       


Abilities: Extending Entity Capabilities

Abilities are components which can be attached to any Entity (EntityBase) through the toolset or code.
Ability is derived from ActivatedComponent, which is a common base class for components which can be "activated" and attached to an entity, and which can, optionally (if their UpdateInterval property is set) be updated at a pre-defined frequency (which is scaled and paused with game time, by default).

Abilities in toolset


Abilities are located in the Asset Explorer-> Scripting-> AI-> Abilities / BehaviorSystem.
To add ability to entity, drag drop it to an entity. In the World Explorer abilities appear as entity components only in "Advanced" mode .  You can manage abilities in Object Explorer. See "Abilities" category in OE.
 

Abilities in code

 
Abilities are added to the entity as components, and registered by a key, which is a type of ability. Ie entity can have only one ability of one type. (key must be unique) See more about ComponentTypeKey property below in section about "ActivatedComponent".
 
EntityBase.Create<Perception>()
---
var perception = EntityBase.Get<Perception>()
 
However, the key may not be identical to the type of ability:
 
EntityBase.Create<Mobile, SimpleMobile>() // typeof(Mobile) - key
---
var mobile = EntityBase.Get<Mobile>() // mobile.GetType() == typeof(SimpleMobile)
---
EntityBase.Remove<Mobile>();

 

Abilities examples:

 
The engine contains a lot of ready to use abilities, for example:
  • AnimationSet - management of the character animations.
  • ObjectPhysics - physics of entity.
  • Inventory - inventory of game character.
  • Perception - the perception of the surrounding entities with the help of sensors (Sight, Hearing)
 
Classes are inherited from BehaviorSystem: 
(BehaviorSystem’s this kind of abilities, which are responsible for the behavior of the entities)
  • Combatant - responsible for the fight: attack, shots, choice of the enemy, pursuit of the enemy.
  • Speaker - state machine which controls the process of conversation between two characters.
  • Mobile, HumanoidMobile, SimpleMobile - movement of entity to desired goals in the form of coordinates, other entity, or script computed during run-time.
  • Navigator - moving by path, see: http://game-engine.visual3d.net/wiki/path-editor-waypoints-and-pathfinding-ai?
 

Addition of custom Ability example:


See “Addition of custom Ability. CTFStatistics ability“ section in the Mission and Avatar Scripting tutorial/manual for further information on how to create your own ability components in C#, VB.NET, IronPyton and other .NET languages, as well as how to hook them up with avatar and entity prefab assets.
 

Actions: Basic Building Blocks for Scripting

Actions are the most basis building blocks for a scripting. For example, Animate PlaySound, Attack, Jump are actions which can be added to Entity as triggered state, to Trigger, Cinematics Sequence, Conversation or to other composite actions. Actions can be written in C#, Python, or another .NET language, using Visual Studio or Visual3D's built-in Script Editor.
 
Action parameters can be set to values or variables (or other properties/parameters) by typing them on the same line in the Script Editor or when selecting an Action (eg. Talk, PlayCinematic, MoveToPosition, etc.), you can use the Object Editor (or Properties panel) to configure each of the parameters for it, in the same way you do so for editing the properties of an Entity (or SceneObject, Asset, Component, etc.).
 
Actions can also be drag-dropped onto an Entity or Trigger. This can be used to automate setup at design-time using them like "Macros", or can be used to "issue commands" to entities for testing purposes, or an RTS or simulation game. And you can just right click > Execute (or sometimes "Activate") it, to execute (run) it.
 
Also action can be started and stopped from the Interactive Console (press “~” to open console).  For example: ActivatePythonAction("droid2", "Test1", "TEST_ARG!!!")
 
Actions can be organized into a actions trees with the help of composite actions such as: Parallel and Sequence.

More about Action/Behavior Trees:
 
1. Building AI for a Simulation Game from the Ground Up
2. The Backbone of AI Behaviors: Movement and Animation
3. On the Effectiveness of Random Decisions in Structured Behaviors
4. A Lazy Approach to Designing Consistent AI Behaviors
 
Using Decorators to Improve Behaviors
The Power of Sequences for Hierarchical Behaviors
The Flexibility of Selectors for Hierarchical Logic
Enabling Concurrency in Your Behavior Hierarchy
http://aigamedev.com/open/hierarchical-logic/parallel/

 

States, Actions in code:


Root entity actions are called states. Following API is used to working with the states:
  • EntityBase.EntityStates
  • EntityBase.GetState(name)
  • EntityBase.ExecuteState(name)
  • EntityBase.DeactivateState(name)
  • EntityBase.StateIsActive(name)
  • EntityBase.AddState(name, state)
  • EntityBase.RemoveState(name)
From the name of the method is clear its purpose
 

Python and C# actions examples:

  • ActivatePythonAction - starts a python action script for an entity
  • CameraCinematicTest - a simple script which executes one command - cinematic start «CutScene2». The script does not demand an entity as argument.
  • Destroy - the script destroys an entity, deleting it from a scene. Try to drag it onto entity to see how it works.
  • MoveToRandomPoint – Forces the entity to move to a random point in small radius.
  • ShowCaption - a simple script which displays the entity name to which it has been applied, on screen.
  • Deactivate - stops action (entity state)
  • ThousandSoldiers is more complex utilitarian script. It generates 1000 entities on a scene with a prototype «EvilAssaultDroid». The position and other parameters are set in a script.
  • TreesGenerator - also as well as the previous script this script generates 150 trees of one of three types. And the tree prototype gets out with the set accident(/randomness). You can experiment this script, changing its parameters. Then simply drag it onto a scene, and you will see result of your experiments.
  • Aggressive - the action consists of two states: If to entity by which this action is set, will come nearer on distance more close 40 units, it will start to attack, then if to leave from it on distance more than 100 units, the entity ceases to attack.
  • Fleeing - simple action with one state. The entity by which this action is set, will avoid in every possible way a meeting with other entities, escaping from them.
  • Test1 - Action for a scene «Scripting Demo». Move this action on entity near to a control point «point1» and the entity will start to be patrolled/walk in radius from this point.

C# actions: Animate, Attack, Move , Navigate, Talk, OpenDoor, PlaySound, CreateEntity, Parallel, Parallel, Sequence, Trigger

You can see a lot of other actions in the Asset Explorer-> Scripting-> Behaviors-> Actions
 

Action Script in Python (using Script Editor)

The script represents a class in Python which is inherited from class PythonBehavior. For more complex logic it is possible to override additional functions:

__ init __(self, testArg = None): - it is executed at action creation. (self - it is not defined, testArg - the additional arguments transferred in action, for example "target")

Start(self) - is executed at action start. (self - it is defined)
 
Stop(self) - is executed at action end. (E.g. when the entity of which is set action given the command deactivate)
 
Attach(self) - is executed at attaching of self.
 
To entity to which the action is set, it is possible to receive access by using of the variable self.state
To create additional states of action, other than «Update» default state, it is necessary to define simply additional functions and to transfer in their control returning the name of this function from a current state. For example:
 
def Update(self):
    <…code…>
    return "NewState"
def NewState(self):
    <…code…>
 
It is possible to redefine the first state of action which is by default equal «Update», for this purpose it is necessary to return a name of a state from function Start:
 
def Start(self):
return "State1"
 
As an example it is possible to look «Test1» action.

Tutorials with C# and IronPython actions:

http://game-engine.visual3d.net/wiki/creating-action-script-csharp 
http://game-engine.visual3d.net/wiki/triggering-entity-states-behaviors-for-events-user-controls 
 

 

Entity Triggers and Events handling in Toolset:


Trigger is a composite action, which waits for the event, and when an event occurs, executes its child actions in parallel.

You can create a new Trigger on an Entity In toolset by drag-drop an event or condition from Asset Explorer onto an Entity to create a new Trigger (under Triggers folder shown when that entity is expanded in World Explorer or Asset Explorer).  You can then enter a name for that trigger and drag-drop actions (or behaviors or abilities) onto that trigger. On trigger, you can drag other actions what you want to execute. They can be combined in parallel and sequentially sequents.



There are two types of triggers:
 

Event trigger.


This trigger (EventTrigger class) expects event (BaseEvent class), which can be generated with help of the method EntityBase.TriggerEvent(BaseEvent evnt) or EventManager.Instance.TriggerEvent(BaseEvent evnt) and as soon as the event occurs, the trigger executes its child actions.
 
Events examples: SceneLoad, TimeElapse, EntityActivated, EntityMouseDown, EntityCollided
 

Conditional trigger.


This trigger (ConditionalTrigger class) waits for a condition (Condition class), as soon as the condition becomes true, the trigger will start to execute child actions, if the condition is again becomes false, the trigger will stop to execute child actions. I.e. trigger execute child actions until the condition is true.
 
Condition examples: IsKeyPressed, IsAttack, IsInArea
 
Triggers are expected event/truth-conditions only when they are active. Activate/Add/Delete a trigger can be, as well as any other action. See "States, Actions in code" above.
 

Examples of Event and Conditional Triggers:


 

Example of custom event creation from C#:



Action Trees design examples


Trigger can be a child action, this allows to create quite complicated logic like fsm states, for example:

Door with Key example

  • CompositeAction “ClosedState”, IsActive = true, IsSerializeState = true
    • Trigger “OpenDoor” Event = “DefaultAction (press “E”)” Actions =
      • Sequence
        • Condition “There is a key?”
        • PlayAnimation “Open door”
        • Action “Change state to <OpenedState>” (ClosedState deactivation)
  • CompositeAction “OpenedState”
    • Trigger “CloseDoor” Event = “DefaultAction (press “E”)” Actions =
      • Sequence
        • PlayAnimation “Close door”
        • Action “Change state to <ClosedState>” (OpenedState deactivation)

Pac-Man like enemy AI example

  • ParallelAction “AggresivePursuitState”, IsActive = true, IsSerializeState = true
    • Action “ChangeToAggresiveColor”
    • Action “PursuitPlayer”
    • Trigger “Eating Dot” Event = “EatingDot” Actions =
      • Action “Change state to <EscapeFromPlayerState>”
    • Trigger “CatchPlayer” Event = “Collided” Actions =
      • Action “Kill player”
  • ParallelAction “EscapeFromPlayerState”
    • Action “ChangeToEscapeColor”
    • Action “EscapeFromPlayer”
    • Trigger “PlayerDotPowerIsOver” Event = “DorPowerIsOver” Actions =
      • Action “Change state to <AggresivePursuitState>”
    • Trigger “CatchedByPlayer”  Event = “Collided” Actions =
      • Action “KillSelf”
 

Area with triggers example:


Area (instance of the Visual3D.Scripting.Areas.Area class) is entity on scene, with already defined triggers "Entered", "Exited", “EnteredOrExited”. By default, visible only in design mode. The events of triggers occur when entering and leaving the area.
 
 
Hooking up events, actions, and Python scripts to Triggers is covered in the Event Triggered Scripts & Actions tutorial. This shows how to use a PythonAction script to trigger a cinematic, as an example, though you can trigger cinematics more easily by using the PlayCinematic action, which, like other edits, has parameters easily and visually edited through the Object Editor without any need for coding. 

Key Mapping

 
KeyMap is a list consisting of pairs “User Input - Event Name”. This pair also called KeyMapEntry. Every time you press keyboard key defined in the KeyMap, occurs event that can be handled by Avatar, Scene, GUI, or globally by any object, subscribed at event.
 
In KeyMapEntry can be defined two keys (Primary and Secondary), keys modification (Alt, Ctrl, Shift) , type of press (Up, Down, UpDown) or mouse click.
 
KeyMaps support inheritance. You can define a base KeyMap and inherit it by specifying its name for BaseKeyMapName property in the Object Explorer for successor keymap.
 
KeyMap assets can be seen in the Asset Explorer -> Scripting -> Key Maps.
 
Let us consider some variants of use of KeyMaps:
 

Custom KeyMap with InputHandler in C#

 
If we need to handle custom user input eg for a scene, we can create KeyMap with keys, InputHandler for processing, and subscribe to InputHandler event. For example: 

new Input.KeyMap("CustomKeyMap", Input.KeyMap.Ids.FullMouseHandlerKeyCodes,
    new Input.KeyMapEntry(Key.AltLeft, "IncreaseMouseConstraintPower", true, ModifierKeyDependencies.NoDependencies),
    new Input.KeyMapEntry(Key.ShiftLeft, "ShiftPickingPlane", true, ModifierKeyDependencies.NoDependencies),
    new Input.KeyMapEntry(Key.MouseButtonLeft, "AddMouseConstraint", true, ModifierKeyDependencies.NoDependencies)
);

Input.InputHandlerConfig config = Input.InputHandlerConfig.CreateKeyboardOnly("CustomInput", "CustomKeyMap", true, ModifierKeys.None, false);
_controller = new Input.InputHandler(World.Input, "CustomInput", config);
_controller.InputEventProcessed += _controller_InputEventProcessed;
_controller.Priority = Priority.Higher;
_controller.Activate(this);


_controller_InputEventProcessed event will be triggered each time the key is pressed.

 

KeyMap for GuiForm

 
GuiForm already has its own InputHandler. Access to KeyMap is carried out by means GuiForm.KeyMap property. To receive events you need to override GuiForm.OnHandleInputEvent.

 

KeyMaps for Avatars: Entity Input Controllers

 
To control the avatars / characters and the camera, there are special InputHandler's,which are called InputController's. They contain additional logic to control avatar and taking input events only when a character focused.
 
One of the main tasks of InputController  is to activate Entity States, which have the same name as KeyMapEntry. ie if we have KeyMapEntry "MoveForward : W", then when you press "W", will be activated "MoveForward" entity state.
 
Various InputControllers located in Asset Explorer -> Scripting -> Input Controllers. You can use Object Explorer to set InputController. See entity property: entity-> Gameplay-> User Controls-> Input Controller Prefab.
 
Access to KeyMap is carried out through the InputController.KeyMap property.
 
In addition to OE, you can edit Avatar KeyMap during the initial entity setup in Entity Hookup Editor, as well as using "Keymap Console", which can be called with the F7 hotkey on the scene.
 
See the Key Mapping tutorial in the Avatar & Entity Creation manual for details.

 

Global KeyMap.

 
Input events defined in the Global KeyMap will receive each active InputHandler (custom handlers, Gui, Avatars). Global KeyMap is used for global actions, such as "Screenshot", "Show/Hide Architect", "Show/Hide Settings form", "Exit from the cinematic/cut scene".
 
Global KeyMap is located in the Asset Explorer -> Scrpting -> Key Maps->GlobalKeyMap and in World Explorer -> World -> User Controls -> GlobalKeyMap
You can use GlobalInputHandler, to subscribe to event:
 
World.RenderPipeline.InputManager.GlobalInputHandler.InputEventProcessed += new Input.InputEventHandler(EventDispatcher_InputEventProcessed);


Low-level Components and Data Objects


LightComponent and EntityComponent:   For Persistant Data Objects and Entity-Owned/Attached Components


ComponentBase is the primary, lowest-level base class shared between many different class heirarchies.  

Currently, some of its core functionality (such as support for naming and linking to base asset (aka. prototype / prefab / preset) an instance was created from - are only defined in the derived EntityComponent and LightComponent class.
 
LightComponent and EntityComponent derived from ComponentBase. These classes provide a component-based approach for entity creating. LightComponent unlike EntityComponent can work without ComponentContainer. This allows to organize composite components.

LightComponent/EntityComponent can be thought of as a "Data Object" as much of what it handles relates to persistance (serialization, persisted references, smart copy "instancing", etc.).  However, it has also adds support for new, under-development service model (looking up services) and event mapping.  It also has some functionality previously only available to SceneObjects (and other Entity-derived classes like Scene and GuiForm), such as the ability to "own" other components, however, it only provides low-level support for this, and you should derive from EntityBase (or, in some rare cases, from SceneObject or Actor as well) to ensure that most components are able to be attached to your component class instance (for example, via drag-drop or the right click > "Add New" or > "Add Asset" or other Add/Attach ... context menu options) and to ensure that many scripting tools and features work with your class. 

Currently many scripting features, such as Actions's, Script Events, Entity Triggers, require an EntityBase-derived class which owns a SceneObject (exposed via the EntityBase.VisualObject property) to provide full scripting support.


ActivatedComponent: For Activateable (Startable/Stoppable) and (Optionally) Updated Components



ActivatedComponent is the base class for Ability.  Similar to ActionBase, this class is used for things which need to have an "Active" state (via its implementation of IsActive, Activate(), and Deactivate() defined on the IActivated interface), however, unlike ActionBase, this class is not intended as a lightweight temporary activity/state which is recreated each time a action is started.  Instead, it derived from EntityComponent (and therefore ComponentBase), and is intended to be attached directly to any Entity or SceneObject.   Custom update logic can be defined for classes deriving from ActivatedComponent  by overriding OnUpdated() and ensuruing that the UpdateInterval is set to an update time (or frequency) other than 0 (which is currently the default, to prevent updating component which don't require it).

The ComponentTypeKey property can be set to (or overriden to always return) a the component classes type (or base type), to allow looking up a component by its type, which is usually done if want to ensure that there is only one component a specific type defined for an entity at a time (though in some cases, this can be supported without preventing additional secondary instances of a ActivatedComponent class). 
IsAutoActivated can be set to true to ensure that a component is always activated when its own is activated, by default, though  components can be deactivated later manually, still, even when auto-activation is enabled.

By default,  ActivatedComponent  (and derived classes like Ability) are updated based on "Scene (aka. Game/Simulation) Time", meaning they are paused (not updated, as they still remain "Active") when the game/simulation/scene is paused, and are updated more often when game time is "sped up" or "slowed down".
 

Additional Information

Additional information can be found in the Asset Management (Explorer, Pipeline, and Database) user manual describing how to work with the Asset Database and write persisted component classes which are automatically added to, or persisted through, the Asset Database, and viewed/used/edited through the Asset Explorer, as well as how this relates to Asset Pipeline for importing/exporting media assets (eg. models) and saving edits made.  The Asset Management manual does show a number of screenshots for how to use Asset Explorer, however, it is somewhat outdated, and information describes in this Programming User manual is currently more up-to-date in places. 
We plan on providing separate manual and video tutorial covering use of Asset Explorer, and have other documentation (including video tutorials) covering importing, exporting, and Entity/Model Editor use under our Asset Creation user manual.