Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Special pages
Open Simulator Technical Help
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
OpenSimulator Internals/Code Map/Scene
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
= OpenSimulator Internals/Code Map/Scene = == Overview == Scene is the central object of the region simulator. One Scene instance exists per region. It holds all in-world state and coordinates between the physics engine, script engine, client connections, storage, and grid services. Class hierarchy: Scene β SceneBase β RegionApplicationBase Source: OpenSim/Region/Framework/Scenes/Scene.cs Scene.cs is a partial class -- additional methods are in other files in the same directory. ---- == Constructor == Two constructors: Scene(RegionInfo regInfo) -- base constructor Scene(RegionInfo, AgentCircuitManager, ISimulationDataService, IEstateDataService, IConfigSource, string version) -- full constructor Base constructor: # Creates SceneGraph (holds all entities and physics) # Hooks SceneGraph.UnRecoverableError -- triggers RestartNow() on physics crash # Sets defaults: PhysicalPrims=true, CollidablePrims=true, PhysicsEnabled=true, AllowAvatarCrossing=true, PeriodicBackup=true # Creates EventManager # Creates ScenePermissions Full constructor (called from OpenSimBase.CreateScene()): # Loads RegionSettings from SimulationDataService -- sets default terrain textures if missing, copies classic textures to PBR slots if PBR not set # Loads EstateSettings from EstateDataService # Creates SceneGridInfo from config and ServerURI # Hooks EventManager land object events to SimulationDataService storage # Reads [Startup] config -- draw distances, prim limits, physics flags, script engine, persistence timings, frame rate, viewer allow/deny lists, coarse location update interval, terrain update interval, backup interval # Reads [EntityTransfer] config -- AllowAvatarCrossing, DisableObjectTransfer # Reads [InterestManagement] config -- update prioritization scheme, reprioritization settings, object culling by distance # Creates SimStatsReporter # Starts timer watchdog ---- == Service References == All grid services are accessed through lazy-loaded properties backed by RequestModuleInterface<T>(). They throw if the service is not available (except EstateDataServiceSafe which returns null). {| class="wikitable" ! Property !! Interface !! Notes |- | AssetService || IAssetService || throws if missing |- | InventoryService || IInventoryService || throws if missing, with detailed error message about config |- | GridService || IGridService || throws if missing |- | SimulationDataService || ISimulationDataService || throws if missing |- | EstateDataService || IEstateDataService || throws if missing |- | UserAccountService || IUserAccountService || null if missing |- | PresenceService || IPresenceService || null if missing |- | AuthenticationService || IAuthenticationService || null if missing |- | AvatarService || IAvatarService || null if missing |- | GridUserService || IGridUserService || null if missing |- | AgentPreferencesService || IAgentPreferencesService || null if missing |- | AuthorizationService || IAuthorizationService || null if missing |- | LibraryService || ILibraryService || null if missing |- | SimulationService || ISimulationService || null if missing |} Module references (set by SetModuleInterfaces() after modules load): {| class="wikitable" ! Property !! Interface |- | EntityTransferModule || IEntityTransferModule -- teleport and region crossing |- | AttachmentsModule || IAttachmentsModule |- | AgentTransactionsModule || IAgentAssetTransactions |- | UserManagementModule || IUserManagement |- | AvatarFactory || IAvatarFactoryModule |- | CapsModule || ICapabilitiesModule |} ---- == The Main Loop (Heartbeat) == The scene runs one thread: the Heartbeat thread. Started by Start(): Heartbeat() TriggerOnRegionStarted() Update(1) -- first frame, watchdog not yet active Watchdog alarm enabled Update(-1) -- runs until shutdown Update() loop runs once per frame: Per frame (every frame unless noted): # CheckTerrainUpdates() -- every 4 frames # UpdateTerrain() -- every m_update_terrain frames (default 1000) # UpdatePreparePhysics() -- physics pre-step # SendCoarseLocations() -- every 5 frames, async via thread pool # UpdatePhysics(FrameTime) -- main physics step, returns physicsFPS # CheckAtTargets() -- check llMoveToTarget / llRotLookAt # UpdateObjectGroups() -- send queued object updates to clients # UpdatePresences() -- send presence updates to clients # CleanTempObjects() -- every 180 frames, async # UpdateEvents() -- fires EventManager.OnFrame # UpdateStorageBackup() -- every 200 frames, async # Frame 20: enable logins, inform neighbours region is up, set Ready=true, GC compact Frame timing: FrameTime defaults to 0.0908s (~11fps). Sleep is calculated to hit target frame time. Stats normalized to 55fps for viewer display. Backup runs asynchronously every 200 frames. Objects are only persisted if they have been changed for at least MinimumTimeBeforePersistenceConsidered (default 60s) and no longer than MaximumTimeBeforePersistenceConsidered (default 600s). ---- == Startup Sequence (called from OpenSimBase.CreateRegion) == After construction: # scene.SetModuleInterfaces() -- wires up module references from loaded region modules # loadAllLandObjectsFromStorage() -- loads parcels from region database # LoadPrimsFromStorage() -- loads all objects, calls AddRestoredSceneObject() for each # RegisterRegionWithGrid() -- calls GridService.RegisterRegion(), throws on failure # CreateScriptInstances() -- starts script engine for all loaded objects # scene.Start() -- starts Heartbeat thread AllModulesLoaded() is called after all modules are loaded. Pushes simulator feature data to ISimulatorFeaturesModule (FPS, prim limits, grid info, search URL, etc). ---- == Region Crossing and Teleport == All teleport and crossing logic is delegated to EntityTransferModule: RequestTeleportLocation() β EntityTransferModule.Teleport() CrossAgentToNewRegion() β EntityTransferModule.Cross() TeleportClientHome() β EntityTransferModule.TeleportHome() Incoming objects and attachments from crossings: IncomingCreateObject() β EntityTransferModule.HandleIncomingSceneObject() IncomingAttechments() β EntityTransferModule.HandleIncomingAttachments() Note: IncomingAttechments() -- the typo is in the source. See WTF file. OtherRegionUp() is called when a neighbouring region comes online. If within border distance, enables child agents in that region for all current root avatars via EntityTransferModule.EnableChildAgent(). ---- == Avatar Connection (NewUserConnection) == Called by the login service or another simulator to initiate a connection. Not triggered by the viewer directly. # Checks logins enabled # Checks viewer allow/deny lists # Handles existing ScenePresence (zombie root agents, race conditions during teleport) # Clamps start position within region bounds # CheckLandPositionAccess() -- checks telehub, parcel access, agent limit # VerifyUserPresence() -- checks PresenceService for active session # AuthorizeUser() -- checks estate ban, public access, access list, group membership # Sets up CAPS via CapsModule # ActivateCaps() Connection is activated later when the viewer sends UseCircuitCodePacket UDP packet. ---- == Avatar Removal (RemoveClient) == # Sends shutdown notice to child agents if root # Avatar stands up if seated # Closes child agent connections on neighbouring regions (async) # Triggers ClientClosed and OnRemovePresence events # De-rezzes attachments (root only) # Sends KillObject to all clients # Removes agent transactions # Removes circuit, scene presence, client manager entry, CAPS ---- == Shutdown (Close) == # Deregisters from GridService # Kicks all root avatars with shutdown message # Sets m_shuttingDown = true # Sleeps 500ms to let kick messages reach clients # Closes all agents # Triggers SceneShuttingDown event # Backup(true) -- force persist all pending changes # Closes SceneGraph # Disposes PhysicsScene last (scripts may reference physics during shutdown) ---- == Object Management == Key methods: {| class="wikitable" ! Method !! Notes |- | AddNewPrim() || Creates a new prim via raycast. Checks permissions. Uses entity creator registry if available, else creates SceneObjectGroup directly. Applies user default permissions from AgentPreferencesService. |- | AddRestoredSceneObject() || Adds object loaded from storage. Delegates to SceneGraph. |- | AddNewSceneObject() || Adds newly created object. Delegates to SceneGraph. Triggers ObjectAddedToScene event. |- | DeleteSceneObject() || Removes scripts, keyframe motion, email listeners, physics actors. Unlinks from scene. Triggers ObjectBeingRemovedFromScene. |- | UnlinkSceneObject() || Removes record from scene without destroying. On hard delete, removes from database. |- | IncomingCreateObject() || Handles object arriving from region crossing. Delegates to EntityTransferModule. |- | ForceSceneObjectBackup() || Synchronous backup of a single object. Used for deletes and link/unlink. |} ---- == Client Event Subscriptions == SubscribeToClientEvents() wires all viewer protocol events to scene handlers: * Terrain events (currently empty) * Prim events: position, rotation, scale, shape, texture, name, material, link/unlink, duplicate, permissions, grab, spin, undo/redo * Prim rez events: OnAddPrim β AddNewPrim(), OnRezObject β RezObject() * Inventory events: folder and item CRUD, task inventory, rez script * Teleport events: OnTeleportLocationRequest β RequestTeleportLocation() * Script events: reset, get/set running * Parcel events: return objects, set clean time, buy * Grid events: money transfer * Network events: stats update, viewer effect Note: UnSubscribeToClientEvents() is defined but marked FIXME -- not called anywhere. See WTF file. ---- == Health Monitoring == GetHealth() returns an integer 1-5: {| class="wikitable" ! Value !! Meaning |- | 0 || Starting up |- | 1 || HTTP alive but heartbeat stopped -- possible lockup |- | 2 || Heartbeat running (frame tick < 4s ago) |- | 3 || One packet thread running |- | 4 || Both packet threads running |- | 5 || New user logged in within last 4 minutes |} TimerWatchdog runs every second. Pushes health and root agent count to etcd if the IEtcdModule is present. ---- == Persistence == Objects are persisted via EventManager.OnBackup β SimulationDataService. Objects qualify for persistence if: * HasGroupChanged = true * Time since last change > MinimumTimeBeforePersistenceConsidered (default 60s) * Time since last change < MaximumTimeBeforePersistenceConsidered (default 600s) OR forced=true Auto-return queued in m_returns dictionary. Return messages sent via IMessageTransferModule on next backup cycle. ---- == Notable Details == * MegaRegions (CombineContiguousRegions) are explicitly rejected on startup with a fatal error * The restart console command is registered but disabled -- marked unreliable in source * IncomingAttechments() has a typo -- see WTF file for both file locations * GOTO is used in AuthorizeUser() for group access checks -- commented in source as "some say GOTO is ugly" * Heartbeat restart limit: if heartbeat thread dies and restarts more than 10 times, Environment.Exit(1) * GC.Collect() is called explicitly at frame 20 and on map tile regeneration * etcd integration is optional -- IEtcdModule only -- used for external health monitoring ---- == See Also == * [[OpenSimulator Internals/Code Map]] * [[OpenSimulator Internals/Code Map/OpenSim]] * [[OpenSimulator Internals/Code Map/ScenePresence]] * [[OpenSimulator Internals/Code Map/EntityTransferModule]] * [[OpenSimulator Internals/Code Map/HGEntityTransferModule]] * [[OpenSimulator Internals/Code Map/AttachmentsModule]] * [[OpenSimulator Internals/Code Map/AvatarFactoryModule]] * [[OpenSimulator Internals/Code Map/InventoryAccessModule]] * [[OpenSimulator Internals/Code Map/Shared]] * [[OpenSimulator Internals/Architecture Overview]] * [[OpenSimulator Internals/Connector Architecture]] * [[OpenSimulator Internals/Walkthroughs/Avatar Rez In Region]] * [[OpenSimulator Internals/Walkthroughs/Avatar Logs Out]] * [[OpenSimulator Internals/Walkthroughs/Avatar Transfer Between Regions]]
Summary:
Please note that all contributions to Open Simulator Technical Help may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Open Simulator Technical Help:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
OpenSimulator Internals/Code Map/Scene
(section)
Add topic