IRegionModule/de

From OpenSimulator

Revision as of 12:32, 16 July 2018 by Manni (Talk | contribs)

Jump to: navigation, search


Contents

Bitte beachten Sie

Diese Seite behandelt den Mechanismus des Bereichsmoduls, der seit OpenSimulator 0.6.9 vorhanden ist. Eine ältere Version die auf die älteren IRegionModule-Mechanismen verweist, finden Sie unter http://opensimulator.org/index.php?title=IRegionModule&oldid=13166

Siehe Related Software für Links zu vorhandenen Regionsmodulen.

Einführung

Region-Module sind Klassen, die die Schnittstellen INonSharedRegionModule oder ISharedRegionModule von OpenSimulator implementieren. .NET-DLLs, die diese Klassen enthalten, können dann in das Binärverzeichnis von OpenSimulator (bin /) gestellt werden. Beim Start durchsucht OpenSimulator dieses Verzeichnis und lädt dort alle darin enthaltenen Module.

Regionsmodule werden im Herzen des Simulators ausgeführt und haben Zugang zu allen Einrichtungen. Dies macht sie sehr leistungsfähig, bedeutet aber auch, dass bei der Erstellung besonders darauf geachtet werden muss, dass sie sich nicht negativ auf die Simulatorleistung auswirken.

Typischerweise registrieren Regionenmodule Methoden mit dem Ereignismanager des Simulators, die aufgerufen werden, wenn verschiedene Ereignisse auftreten (z. B. Avatar-Chat, Benutzer, der eine Region betritt usw.).

Es gibt zwei Arten von Regions-Modulen.

  • Nicht freigegebene Module, für die ein separates Modul für jede Region/Szene erstellt wird
  • Freigegebene Module, bei denen ein einzelnes Modul zwischen allen Regionen/Szenen geteilt wird, die auf demselben Simulator ausgeführt werden.

Erstellung eines Region Modules

Von Grund auf neu

Zu diesem Zeitpunkt werden Regionsmodule normalerweise in der OpenSimulator-Quellstruktur selbst mithilfe ihrer Build-Mechanismen erstellt.

Die Schritte sind wie folgt:

1. Navigieren Sie zu dem Verzeichnis addon-modules / in der Basis der OpenSimulator-Quellstruktur (nicht zu dem Verzeichnis bin / addon-modules / in der Bin-Baumstruktur, über das wir in Kürze sprechen werden).

2. Erstellen Sie ein Verzeichnis für das Regionsmodulprojekt, normalerweise mit demselben Namen wie das Regionsmodul. Zum Beispiel BareBonesNonSharedModule /

3. Erstellen Sie eine prebuild.xml für das Projekt. Dies ist die Datei, die von ./runprebuild.sh oder ./runprebuild.bat im Basis-OpenSimulator-Verzeichnis verwendet wird, um die entsprechenden Build-Dateien für Visual Studio, Monodevelop und nant zu erstellen. Für ein sehr einfaches Modul hätten Sie etwas wie

<Project frameworkVersion="v4_0" name="BareBonesNonSharedModule" path="addon-modules/BareBonesNonSharedModule/src/BareBonesNonSharedModule" type="Library">
  <Configuration name="Debug">
    <Options>
      <OutputPath>../../../../bin</OutputPath>
    </Options>
  </Configuration>
  <Configuration name="Release">
    <Options>
      <OutputPath>../../../../bin</OutputPath>
    </Options>
  </Configuration>
 
  <ReferencePath>../../../../bin</ReferencePath>
  <Reference name="System"/>
  <Reference name="log4net"/>
  <Reference name="Mono.Addins"/>
  <Reference name="Nini"/>
  <Reference name="OpenMetaverse"/>
  <Reference name="OpenMetaverseTypes"/>
  <Reference name="OpenSim.Framework"/>
  <Reference name="OpenSim.Region.Framework"/>
  <Reference name="OpenSim.Services.Interfaces"/>
 
  <Files>
    <Match pattern="*.cs" recurse="true"/>
    <Match path="Resources" pattern="*.*" buildAction="EmbeddedResource"/>
  </Files>
</Project>

Zu dieser Datei müssen einige Dinge beachtet werden

  • In OpenSimulator 0.8, wenn Sie auf Windows aufbauen, müssen Sie eine FrameworkVersion von 4_0 anstelle von 3_5 im oberen <Project> -Tag verwenden. Vor OpenSimulator 0.8 muss dies jedoch net 3_5 sein, damit der Build fortgesetzt werden kann. Bei Mono kann dies entweder 3_5 oder 4_0 auf OpenSimulator 0.8 sein, muss aber 4_0 sein, wenn Sie C# 4.0-Funktionen verwenden möchten.
  • Das Pfadattribut in <Projekt> muss auf den Speicherort im Verzeichnis addon-modules verweisen, in dem sich der Quellcode befindet. Dieses Verzeichnis ist relativ zum OpenSimulator-Stammpfad. Im obigen Beispiel befindet sich der Code in addon-modules / BareBonesNonSharedModule / src / BareBonesNonSharedModule.
  • Die <OutputPath> -Tags geben an, wo Ihre kompilierte Modul-DLL kopiert wird, nachdem sie erstellt wurde. Dies ist relativ zum Speicherort Ihres Quellcodes, wie im Pfadattribut von <Project> angegeben. In den meisten Fällen möchten Sie, dass dies zusammen mit dem Rest der DLLs im OpenSimulator-Verzeichnis / bin abgelegt wird. Legen Sie diese Datei nicht in das Verzeichnis bin / addon-modules - dies ist verwirrend nur für Addon-Modul-Konfigurationsdateien (* .ini).
  • Der <ReferencePath> -Wert gibt an, wo das Modulprojekt die DLLs finden kann, auf die es verweisen muss (OpenSimulator.Framework.dll, log4net.dll usw.).
  • Jede Bibliothek, auf die Sie in Ihren Modulen verweisen, benötigt ein <Referenz> -Tag. Das obige Beispiel listet Bibliotheken wie OpenSim.Framework.dll und OpenMetaverse auf.
  • Weitere Beispiele finden Sie in der Hauptdatei prebuild.xml im Stammverzeichnis der OpenSimulator-Quellstruktur. Bitte beachten Sie, dass das obige Beispiel im Vergleich zu vielen anderen Einträgen optimiert ist - die Hauptdatei muss zu einem gewissen Zeitpunkt vereinfacht werden, da es eine große Redundanz gibt (zB muss Pfad nicht in jedem <Reference> angegeben werden) bereits durch <ReferencePath> angegeben).

4. Navigieren Sie zurück zum OpenSimulator-Stammverzeichnis und führen Sie ./runprebuild.sh (Linux, Mac OSX) oder ./runprebuild.bat (Windows) aus. In der resultierenden Ausgabe, in der Nähe der Spitze, sollten Sie die Linie sehen

searchDirectory: addon-modules/BareBonesNonSharedModule

o.ä. Wenn Sie jetzt eine IDE wie Visual Studio oder MonoDevelop verwenden, sollten Sie jetzt in der Lage sein, die OpenSim.sln-Lösung neu zu laden und Ihr Projekt in der Quellstruktur zu sehen.

Wenn etwas schief geht, schauen Sie sich die Ausgabe für runprebuild.sh/.bat genau an. Möglicherweise sehen Sie Nachrichten wie

[!] Could not resolve Solution path: addon-modules/BareBonesNonSharedModule/src/BareBonesNonSharedModule

was darauf hinweist, dass Ihre prebuild.xml-Datei für dieses Modul den Quellordner nicht korrekt aufnimmt.

5. Fügen Sie nach Bedarf Moduldateien in Ihrem Projekt hinzu oder bearbeiten Sie sie.

6. Führen Sie runprebuild.sh erneut aus, wenn Sie Ihrem Modul neue Dateien hinzugefügt haben.

7. Erstellen Sie OpenSim.sln mit Ihrer üblichen Build-Methode, egal ob Sie innerhalb der IDE oder in der Befehlszeile mit xbuild (mono) oder nant arbeiten.

8. Wenn die Kompilierung erfolgreich ist, kopiert der Buildprozess die Binärdatei in das OpenSimulator-Verzeichnis bin /. Wenn Sie OpenSimulator das nächste Mal starten, sollte es in den Simulator geladen werden und in der Ausgabe für den Konsolenbefehl "show modules" erscheinen.

Aus bestehendem Modul-Code

Wenn Sie ein Regionsmodul erstellen möchten, das bereits existiert, sind die Schritte etwas einfacher.

1. Platzieren Sie den Modulcode im OpenSimulator-Addonmodul-Basisverzeichnis. Wenn Sie z. B. ein Modul namens EventRecorderModule kompilieren möchten, befindet es sich unter addon-modules / EventRecorderModule. Bitte beachten Sie, dass der Name des Moduls mit dem Patch in der Datei prebuild.xml übereinstimmen muss (in diesem Beispiel ist die Datei EventRecorderModule / prebuild.xml).

2. Führen Sie wie oben prebuild.sh/prebuild.bat erneut aus. Dies ist das Einfügen des Moduls in die OpenSimulator-Build-Lösung (OpenSim.sln).

3. Sie können das Modul jetzt mit Visual Studio, MonoDeveloper, xbuild oder nant kompilieren.

4. Beim nächsten Start von OpenSimulator sollte das Modul geladen werden (die Datei prebuild.xml platziert das eingebaute Modul in das Bin / des OpenSimulator).

Installieren von Regionsmodulen

Wenn Sie nur eine vorhandene Region-Modul-DLL installieren, anstatt sie aus der Quelle zu erstellen, müssen Sie dies tun

1. Kopieren Sie die DLL und alle anderen zugehörigen Dateien in $ OPENSIM_BASE / bin

2. In den meisten Fällen konfigurieren Sie das Modul, indem Sie entweder den gewünschten Abschnitt zu OpenSim.ini hinzufügen, ihn als bin / addon-modules / MyModule / config / config.ini hinzufügen oder indem Sie explizit die Konfigurationsdatei des Moduls hinzufügen.

Region Module Interfaces

All region modules must implement INonSharedRegionModule or ISharedRegionModule from OpenSim.Region.Framework.Interfaces. If a region module implements INonSharedRegionModule then an instance of that module is created for each region (aka scene) in the simulator. Each module only knows about its own region. If a region module implements ISharedRegionModule then only a single instance of the module exists and it is informed about all regions/scenes in the simulators.

Both INonSharedRegionModule and ISharedRegionModule extend IRegionModuleBase which implements the bulk of the interface methods. These are as follows.

public interface IRegionModuleBase
{
     string Name { get; }
     Type ReplaceableInterface { get; }
     void Initialise(IConfigSource source);
     void AddRegion(Scene scene);
     void RemoveRegion(Scene scene);
     void RegionLoaded(Scene scene);
     void Close();
}
Method Description
Name This name is shown when the console command "show modules" is run. For example, "Sim Chat Module" or "The Best Region Module Ever".
ReplaceableInterface If this is not null, then the module is not loaded if any other module implements the given interface. One use for this is to provide 'stub' functionality implementations that are only active if no other module is present
Initialise This method is called immediately after the region module has been loaded into the runtime, before it has been added to a scene or scenes. IConfigSource is a Nini class that contains the concatentation of config parameters from OpenSim.ini, OpenSimDefaults.ini and the appropriate ini files in bin/config-include
AddRegion This method is called when a region is added to the module. For shared modules this will happen multiple times (one for each module). For non-shared modules this will happen only once. The module can store the scene reference and use it later to reach and invoke OpenSimulator internals and interfaces.
RemoveRegion Called when a region is removed from a module. For shared modules this can happen multiple times. For non-shared region modules this will happen only once and should shortly be followed by a Close(). On simulator shutdown, this method will be called before Close(). RemoveRegion() can also be called if a region/scene is manually removed while the simulator is running.
RegionLoaded Called when all modules have been added for a particular scene/region. Since all other modules are now loaded, this gives the module an opportunity to obtain interfaces or subscribe to events on other modules. Called once for a non-shared region module and multiple times for shared region modules.
Close
  • For a non-shared region module, this will be called when its region is closed. This usually occurs on shutdown. However, it's also possible for a region to be removed whilst the simulator remains running.
  • For a shared region module, this should be called when the simulator is shutdown. However, due to a regression in OpenSimulator 0.8 (and probably in many earlier versions) this was not occurring. This is fixed in current development code (from commit 889194d, 3rd July 2014). In the mean time, the easiest workaround is to count the number of scenes added to the module and then shutdown if the same number are removed. However, this will stop it being possible to operate a simulator with temporarily no regions (a somewhat minor use case). For an example of this approach, see https://github.com/justincc/EventRecordingModule/blob/master/src/EventRecorder/EventRecordingModule.cs

INonSharedRegionModule itself contains no methods, being defined simply as

public interface INonSharedRegionModule : IRegionModuleBase
{
}

ISharedRegionModule has one additional method.

public interface ISharedRegionModule : IRegionModuleBase
{
    void PostInitialise();
}
Method Description
PostInitialise Guaranteed to be called after Initialise() on all other modules has been called but before modules are added.

Example Region Module

This example assumes that you are using the file already in the OpenSimulator source tree (from 0.7.1 onwards) at OpenSim/Region/OptionalModules/Example/BareBonesNonShared/BareBonesNonSharedModule.cs. There's also a bare bones shared module example there. To build this as a separate project, please see the instructions above.

BareBonesNonShareadModule is very basic. It does nothing more than log calls made to IRegionModule methods in the process of activating the module.

In the source tree, the [Extension... attribute line is commented. You can uncomment this, rebuild OpenSimulator and start it to see the module in action.

using System;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
 
[assembly: Addin("BareBonesNonSharedModule", "0.1")]
[assembly: AddinDependency("OpenSim", "0.5")]
 
namespace OpenSim.Region.OptionalModules.Example.BareBonesNonShared
{
    /// <summary>
    /// Simplest possible example of a non-shared region module.
    /// </summary>
    /// <remarks>
    /// This module is the simplest possible example of a non-shared region module (a module where each scene/region
    /// in the simulator has its own copy).
    ///
    /// When the module is enabled it will print messages when it receives certain events to the screen and the log
    /// file.
    /// </remarks>
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BareBonesNonSharedModule")]
    public class BareBonesNonSharedModule : INonSharedRegionModule
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
        public string Name { get { return "Bare Bones Non Shared Module"; } }        
 
        public Type ReplaceableInterface { get { return null; } }
 
        public void Initialise(IConfigSource source)
        {
            m_log.DebugFormat("[BARE BONES]: INITIALIZED MODULE");
        }
 
        public void Close()
        {
            m_log.DebugFormat("[BARE BONES]: CLOSED MODULE");
        }
 
        public void AddRegion(Scene scene)
        {
            m_log.DebugFormat("[BARE BONES]: REGION {0} ADDED", scene.RegionInfo.RegionName);
        }
 
        public void RemoveRegion(Scene scene)
        {
            m_log.DebugFormat("[BARE BONES]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
        }        
 
        public void RegionLoaded(Scene scene)
        {
            m_log.DebugFormat("[BARE BONES]: REGION {0} LOADED", scene.RegionInfo.RegionName);
        }                
    }
}

Enabling the module

Creating the module code itself isn't quite enough to enable it. To do that, we need to make it visible to OpenSimulator's module mechanism (which is currently Mono.Addins).

This is done by adding an Extension attribute to the class, for example.

[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BareBonesNonSharedModule")]

The important part here is the "Path" section "/OpenSim/RegionModules" - this is how OpenSimulator retrieves modules from Mono.Addins. The Id can be anything meaningful to the module.

Newer Mono versions also need this kind of section before the namespace declaration:

[assembly: Addin("BareBonesNonSharedModule", "0.1")]
[assembly: AddinDependency("OpenSim", "0.5")]

At the beginning of your module source code file you need to add this line:

using Mono.Addins;

And prebuild.xml needs to include such a line for newer Mono versions:

<Reference name="Mono.Addins.dll"/>

Integrating with OpenSimulator

NOTE: This section is very incomplete and parts are out of date. If you need to know something, please ask on the OpenSimulator mailing lists where we can both answer the question and add the necessary documentation here.

However, please note that OpenSimulator is a very young project and the internal interfaces can change at short notice. If this happens, it is up to you to keep your module up to date with later versions of OpenSimulator.

Accessible Objects

In the AddRegion routine you get access to the scene object for the region, from here you can spider down into the scene and get access to many other objects of interest.

  • scene.GetEntities() - returns a list of all the Entities in the environment. This will be a combined list of SceneObjectGroups (prim sets) and ScenePresences (avatars).
  • scene.GetAvatars() - get only the avatars in the scene (very handy for sending messages to clients)
  • scene.EventManager - this is the object from which you can register callbacks for scene events. Some examples provided below.
  • scene.RegionInfo - properties about the region

Events

Various occurrences in OpenSimulator (e.g. avatar entering a region, chat) have event hooks to which a module can subscribe. The major sets of events are available from Scene.EventManager.

In many cases, you want to do as little work as possible in the thread that fires the event as many coming from time-critical areas in the OpenSimulator code (e.g. within main scene frame processing) or areas where a holdup will cause other disruption (e.g. events which notify that a root agent has arrived).

These events are somewhat rough and ready because they were originally created for internal OpenSimulator use and by default modules started to use them. Thus, there is inconsistency with names, arguments and the events exposed. Please be prepared for all of these to change over time or be superseded by more appropriate events.

Registering for events

Taking the SunModule as an example we can see the following code:

In Initialise():

...
m_scene.EventManager.OnFrame += SunUpdate;
...

Pretty simple, we just got the EventManager and registered the SunUpdate method as a callback for the OnFrame event. OnFrame is triggered every time there is a render frame in Opensim, which is about 20 times per second. So in this particular case, you want to be very careful about the actions you perform in this event as they will have a direct impact on scene loop performance (where taking a long time will result in symptoms of lag for moving avatars, etc.).

Here's the function itself

public void SunUpdate()
{
    // this code just means only do this on every 1000th frame, and don't do it if the sun is in a fixed possition
    if (((m_frame++%m_frame_mod) != 0) || !ready || sunFixed)
    {
        return;
    }
 
    GenSunPos();        // Generate shared values once
 
    List<ScenePresence> avatars = m_scene.GetAvatars();
    foreach (ScenePresence avatar in avatars)
    {
        if (!avatar.IsChildAgent)
            avatar.ControllingClient.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
    }
 
    // set estate settings for region access to sun position
    m_scene.RegionInfo.RegionSettings.SunVector = Position;
}

SunUpdate() takes no parameter (some events may require them). It only fires every 1000th frame by default (m_frame_mod = 1000 in this module), so it doesn't take too many cycles.

In order for the sun position to change for the clients, they need to be told that it changes. This is done by getting a list of all the Avatars from the scene, then sending the Sun Position to each of them in turn. Moreover, you only want to do this for root agents (agents that actually have an attached avatar that can move around, etc.). Updates sent to child agents (which allow viewers to see into neighbouring regions) will simply be ignored.

Available Events

Here is an extremely incomplete list of available events (which hopefully should be filled out as time goes by). For more details, please see the OpenSimulator code itself. Please also note that OpenSimulator is still in development. Event parameters and names may change over time.

In the table below, the delay columns signal whether a delay in processing the event is likely to disrupt the simulator as a whole and/or the entity (e.g. a user) in question. However, please be aware that even if there is no immediate disruption from delaying one event thread, delaying many will eventually cause simulator wide problems as the threadpool is exhausted.

In OpenSim.Region.Framework.Scenes.EventManager

Event name Parameters Delay can disrupt simulator Delay can disrupt user Description
OnClientLogin IClientAPI client No Yes Triggered on the region entered by a client when it first logs in. A delay in processing this event will hold up the entrance of the avatar to the scene.
OnSetRootAgentScene UUID agentID, Scene scene No Yes Triggered when an avatar enters a scene and before any setup work has been done (such as initializing of attachments, etc.). A delay in processing this event will hold up the entrance of the avatar to the scene, which may be a particular issue with region crossings.
OnMakeRootAgent ScenePresence presence No Yes Triggered when an avatar enters a scene and after setup work has been done (recreation of attachment data, etc.). A delay in processing this event will hold up the entrance of the avatar to the scene, which may be a particular issue with region crossings. One can inspect the ScenePresence.TeleportFlags to determine if this is the initial login region for the viewer (ViaLogin) or whether their avatar is entering it in an existing session.
OnMakeChildAgent ScenePresence presence No Yes Triggered when an avatar is converted from a root agent to a child agent. This happens when an avatar moves away from a scene, either by teleporting or region cross. It is not fired when an avatar directly logs out. A delay in processing this event should not cause too much disruption to the avatar moving away, though a long delay may prevent them from successfully re-entering the scene.
OnClientClosed UUID agentID, Scene scene No Yes Triggered when a client is closed. This can be due to either a child agent no longer being needed or the user directly logging out from that region. If you want to distinguish between these two events, you will need to check the ScenePresence.IsChildAgent property. At this point, the agent will still be complete (e.g. it will have attachments registered to it) and it will be present in the scene graph. A delay in processing this event may cause issues if the user attempts to re-enter the simulator before the delay is complete.

Where to go from here

  • Getting Started with Region Modules -- the Hello World of OpenSimulator application development. Rather old by now but still worth a look.
  • http://bluewallvirtual.com/example_region_module - More shared region module example code by Bluewall.
  • Development discussion of the current region module mechanism
  • Read the source for existing opensim core modules. These are in the OpenSim.Region.CoreModules and OpenSim.Region.OptionalModules projects. Looking through this code is an extremely good way to find out what region modules can do and how they can do it.
  • Read the source code for the EventManager class in the OpenSim.Region.Framework.Scenes project. These list the many events that exist. Some modules may also export their own events (e.g. OnInventoryArchiveSaved in the InventoryArchiverModule at OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/).
  • Help write some examples here. OpenSimulator grows with your contributions.
Personal tools
General
About This Wiki