Merge branch 'master' of ssh://opensimulator.org/var/git/opensim

cpu-performance
Justin Clark-Casey (justincc) 2013-07-08 22:07:27 +01:00
commit c3db595944
27 changed files with 476 additions and 358 deletions

View File

@ -67,10 +67,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// </summary> /// </summary>
protected bool m_merge; protected bool m_merge;
/// <value> protected IInventoryService m_InventoryService;
/// We only use this to request modules protected IAssetService m_AssetService;
/// </value> protected IUserAccountService m_UserAccountService;
protected Scene m_scene;
/// <value> /// <value>
/// The stream from which the inventory archive will be loaded. /// The stream from which the inventory archive will be loaded.
@ -118,9 +117,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
protected Dictionary<UUID, UUID> m_creatorIdForAssetId = new Dictionary<UUID, UUID>(); protected Dictionary<UUID, UUID> m_creatorIdForAssetId = new Dictionary<UUID, UUID>();
public InventoryArchiveReadRequest( public InventoryArchiveReadRequest(
Scene scene, UserAccount userInfo, string invPath, string loadPath, bool merge) IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, string loadPath, bool merge)
: this( : this(
scene, inv,
assets,
uacc,
userInfo, userInfo,
invPath, invPath,
new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress), new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress),
@ -129,9 +130,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
} }
public InventoryArchiveReadRequest( public InventoryArchiveReadRequest(
Scene scene, UserAccount userInfo, string invPath, Stream loadStream, bool merge) IInventoryService inv, IAssetService assets, IUserAccountService uacc, UserAccount userInfo, string invPath, Stream loadStream, bool merge)
{ {
m_scene = scene; m_InventoryService = inv;
m_AssetService = assets;
m_UserAccountService = uacc;
m_merge = merge; m_merge = merge;
m_userInfo = userInfo; m_userInfo = userInfo;
m_invPath = invPath; m_invPath = invPath;
@ -162,7 +165,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
List<InventoryFolderBase> folderCandidates List<InventoryFolderBase> folderCandidates
= InventoryArchiveUtils.FindFoldersByPath( = InventoryArchiveUtils.FindFoldersByPath(
m_scene.InventoryService, m_userInfo.PrincipalID, m_invPath); m_InventoryService, m_userInfo.PrincipalID, m_invPath);
if (folderCandidates.Count == 0) if (folderCandidates.Count == 0)
{ {
@ -297,7 +300,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
string plainPath = ArchiveConstants.ExtractPlainPathFromIarPath(archivePath); string plainPath = ArchiveConstants.ExtractPlainPathFromIarPath(archivePath);
List<InventoryFolderBase> folderCandidates List<InventoryFolderBase> folderCandidates
= InventoryArchiveUtils.FindFoldersByPath( = InventoryArchiveUtils.FindFoldersByPath(
m_scene.InventoryService, m_userInfo.PrincipalID, plainPath); m_InventoryService, m_userInfo.PrincipalID, plainPath);
if (folderCandidates.Count != 0) if (folderCandidates.Count != 0)
{ {
@ -380,7 +383,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
= new InventoryFolderBase( = new InventoryFolderBase(
newFolderId, newFolderName, m_userInfo.PrincipalID, newFolderId, newFolderName, m_userInfo.PrincipalID,
(short)AssetType.Unknown, destFolder.ID, 1); (short)AssetType.Unknown, destFolder.ID, 1);
m_scene.InventoryService.AddFolder(destFolder); m_InventoryService.AddFolder(destFolder);
// Record that we have now created this folder // Record that we have now created this folder
iarPathExisting += rawDirsToCreate[i] + "/"; iarPathExisting += rawDirsToCreate[i] + "/";
@ -406,7 +409,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// Don't use the item ID that's in the file // Don't use the item ID that's in the file
item.ID = UUID.Random(); item.ID = UUID.Random();
UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.UserAccountService); UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_UserAccountService);
if (UUID.Zero != ospResolvedId) // The user exists in this grid if (UUID.Zero != ospResolvedId) // The user exists in this grid
{ {
// m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId); // m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId);
@ -436,7 +439,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// relying on native tar tools. // relying on native tar tools.
m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid; m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid;
m_scene.AddInventoryItem(item); if (!m_InventoryService.AddItem(item))
m_log.WarnFormat("[INVENTORY ARCHIVER]: Unable to save item {0} in folder {1}", item.Name, item.Folder);
return item; return item;
} }
@ -533,7 +537,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString()); AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString());
asset.Data = data; asset.Data = data;
m_scene.AssetService.Store(asset); m_AssetService.Store(asset);
return true; return true;
} }

View File

@ -294,7 +294,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
try try
{ {
request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream, merge); request = new InventoryArchiveReadRequest(m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadStream, merge);
} }
catch (EntryPointNotFoundException e) catch (EntryPointNotFoundException e)
{ {
@ -342,7 +342,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
try try
{ {
request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath, merge); request = new InventoryArchiveReadRequest(m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadPath, merge);
} }
catch (EntryPointNotFoundException e) catch (EntryPointNotFoundException e)
{ {

View File

@ -229,7 +229,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
{ {
// Test replication of path1 // Test replication of path1
new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, null, (Stream)null, false)
.ReplicateArchivePathToUserInventory( .ReplicateArchivePathToUserInventory(
iarPath1, scene.InventoryService.GetRootFolder(ua1.PrincipalID), iarPath1, scene.InventoryService.GetRootFolder(ua1.PrincipalID),
foldersCreated, nodesLoaded); foldersCreated, nodesLoaded);
@ -246,7 +246,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
{ {
// Test replication of path2 // Test replication of path2
new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, null, (Stream)null, false)
.ReplicateArchivePathToUserInventory( .ReplicateArchivePathToUserInventory(
iarPath2, scene.InventoryService.GetRootFolder(ua1.PrincipalID), iarPath2, scene.InventoryService.GetRootFolder(ua1.PrincipalID),
foldersCreated, nodesLoaded); foldersCreated, nodesLoaded);
@ -292,7 +292,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName });
new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, null, (Stream)null, false)
.ReplicateArchivePathToUserInventory( .ReplicateArchivePathToUserInventory(
itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID),
new Dictionary<string, InventoryFolderBase>(), new HashSet<InventoryNodeBase>()); new Dictionary<string, InventoryFolderBase>(), new HashSet<InventoryNodeBase>());
@ -343,7 +343,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName });
new InventoryArchiveReadRequest(scene, ua1, folder1ExistingName, (Stream)null, true) new InventoryArchiveReadRequest(scene.InventoryService, scene.AssetService, scene.UserAccountService, ua1, folder1ExistingName, (Stream)null, true)
.ReplicateArchivePathToUserInventory( .ReplicateArchivePathToUserInventory(
itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID),
new Dictionary<string, InventoryFolderBase>(), new HashSet<InventoryNodeBase>()); new Dictionary<string, InventoryFolderBase>(), new HashSet<InventoryNodeBase>());

View File

@ -86,7 +86,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));
InventoryArchiveReadRequest iarr InventoryArchiveReadRequest iarr
= new InventoryArchiveReadRequest(null, null, null, (Stream)null, false); = new InventoryArchiveReadRequest(null, null, null, null, null, (Stream)null, false);
iarr.LoadControlFile(filePath, data); iarr.LoadControlFile(filePath, data);
Assert.That(iarr.ControlFileLoaded, Is.True); Assert.That(iarr.ControlFileLoaded, Is.True);

View File

@ -176,7 +176,7 @@ namespace OpenSim.Region.CoreModules.Framework.Library
m_log.InfoFormat("[LIBRARY MODULE]: Loading library archive {0} ({1})...", iarFileName, simpleName); m_log.InfoFormat("[LIBRARY MODULE]: Loading library archive {0} ({1})...", iarFileName, simpleName);
simpleName = GetInventoryPathFromName(simpleName); simpleName = GetInventoryPathFromName(simpleName);
InventoryArchiveReadRequest archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, simpleName, iarFileName, false); InventoryArchiveReadRequest archread = new InventoryArchiveReadRequest(m_MockScene.InventoryService, m_MockScene.AssetService, m_MockScene.UserAccountService, uinfo, simpleName, iarFileName, false);
try try
{ {
HashSet<InventoryNodeBase> nodes = archread.Execute(); HashSet<InventoryNodeBase> nodes = archread.Execute();
@ -185,7 +185,7 @@ namespace OpenSim.Region.CoreModules.Framework.Library
// didn't find the subfolder with the given name; place it on the top // didn't find the subfolder with the given name; place it on the top
m_log.InfoFormat("[LIBRARY MODULE]: Didn't find {0} in library. Placing archive on the top level", simpleName); m_log.InfoFormat("[LIBRARY MODULE]: Didn't find {0} in library. Placing archive on the top level", simpleName);
archread.Close(); archread.Close();
archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, "/", iarFileName, false); archread = new InventoryArchiveReadRequest(m_MockScene.InventoryService, m_MockScene.AssetService, m_MockScene.UserAccountService, uinfo, "/", iarFileName, false);
archread.Execute(); archread.Execute();
} }

View File

@ -58,7 +58,7 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
if (umanmod == Name) if (umanmod == Name)
{ {
m_Enabled = true; m_Enabled = true;
RegisterConsoleCmds(); Init();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name); m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name);
} }
} }

View File

@ -28,9 +28,11 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Threading;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.ClientStack.LindenUDP;
using OpenSim.Region.Framework; using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
@ -57,6 +59,10 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
// The cache // The cache
protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>(); protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>();
// Throttle the name requests
private OpenSim.Framework.BlockingQueue<NameRequest> m_RequestQueue = new OpenSim.Framework.BlockingQueue<NameRequest>();
#region ISharedRegionModule #region ISharedRegionModule
public void Initialise(IConfigSource config) public void Initialise(IConfigSource config)
@ -65,7 +71,7 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
if (umanmod == Name) if (umanmod == Name)
{ {
m_Enabled = true; m_Enabled = true;
RegisterConsoleCmds(); Init();
m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name); m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name);
} }
} }
@ -160,16 +166,9 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
} }
else else
{ {
string[] names; NameRequest request = new NameRequest(remote_client, uuid);
bool foundRealName = TryGetUserNames(uuid, out names); m_RequestQueue.Enqueue(request);
if (names.Length == 2)
{
if (!foundRealName)
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Sending {0} {1} for {2} to {3} since no bound name found", names[0], names[1], uuid, remote_client.Name);
remote_client.SendNameReply(uuid, names[0], names[1]);
}
} }
} }
@ -514,9 +513,8 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
return; return;
} }
//try update unknown users //try update unknown users, but don't update anyone else
//and creator's home URL's if (oldUser.FirstName == "Unknown" && !creatorData.Contains("Unknown"))
if ((oldUser.FirstName == "Unknown" && !creatorData.Contains("Unknown")) || (oldUser.HomeURL != null && !creatorData.StartsWith(oldUser.HomeURL)))
{ {
lock (m_UserCache) lock (m_UserCache)
m_UserCache.Remove(id); m_UserCache.Remove(id);
@ -597,6 +595,18 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
#endregion IUserManagement #endregion IUserManagement
protected void Init()
{
RegisterConsoleCmds();
Watchdog.StartThread(
ProcessQueue,
"NameRequestThread",
ThreadPriority.BelowNormal,
true,
false);
}
protected void RegisterConsoleCmds() protected void RegisterConsoleCmds()
{ {
MainConsole.Instance.Commands.AddCommand("Users", true, MainConsole.Instance.Commands.AddCommand("Users", true,
@ -663,5 +673,40 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
MainConsole.Instance.Output(cdt.ToString()); MainConsole.Instance.Output(cdt.ToString());
} }
private void ProcessQueue()
{
while (true)
{
Watchdog.UpdateThread();
NameRequest request = m_RequestQueue.Dequeue();
string[] names;
bool foundRealName = TryGetUserNames(request.uuid, out names);
if (names.Length == 2)
{
if (!foundRealName)
m_log.DebugFormat("[USER MANAGEMENT MODULE]: Sending {0} {1} for {2} to {3} since no bound name found", names[0], names[1], request.uuid, request.client.Name);
request.client.SendNameReply(request.uuid, names[0], names[1]);
} }
}
}
}
class NameRequest
{
public IClientAPI client;
public UUID uuid;
public NameRequest(IClientAPI c, UUID n)
{
client = c;
uuid = n;
}
}
} }

View File

@ -195,19 +195,20 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{ {
InventoryCollection invCol = m_RemoteConnector.GetFolderContent(userID, folderID); InventoryCollection invCol = m_RemoteConnector.GetFolderContent(userID, folderID);
if (invCol != null && UserManager != null) // Commenting this for now, because it's causing more grief than good
{ //if (invCol != null && UserManager != null)
// Protect ourselves against the caller subsequently modifying the items list //{
List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items); // // Protect ourselves against the caller subsequently modifying the items list
// List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items);
if (items != null && items.Count > 0) // if (items != null && items.Count > 0)
Util.FireAndForget(delegate // //Util.FireAndForget(delegate
{ // //{
foreach (InventoryItemBase item in items) // foreach (InventoryItemBase item in items)
if (!string.IsNullOrEmpty(item.CreatorData)) // if (!string.IsNullOrEmpty(item.CreatorData))
UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData); // UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData);
}); // //});
} //}
return invCol; return invCol;
} }

View File

@ -505,7 +505,11 @@ namespace OpenSim.Region.Framework.Scenes
CreatorID = uuid; CreatorID = uuid;
} }
if (parts.Length >= 2) if (parts.Length >= 2)
{
CreatorData = parts[1]; CreatorData = parts[1];
if (!CreatorData.EndsWith("/"))
CreatorData += "/";
}
if (parts.Length >= 3) if (parts.Length >= 3)
name = parts[2]; name = parts[2];

View File

@ -43,12 +43,10 @@ public sealed class BSCharacter : BSPhysObject
private OMV.Vector3 _size; private OMV.Vector3 _size;
private bool _grabbed; private bool _grabbed;
private bool _selected; private bool _selected;
private OMV.Vector3 _position;
private float _mass; private float _mass;
private float _avatarVolume; private float _avatarVolume;
private float _collisionScore; private float _collisionScore;
private OMV.Vector3 _acceleration; private OMV.Vector3 _acceleration;
private OMV.Quaternion _orientation;
private int _physicsActorType; private int _physicsActorType;
private bool _isPhysical; private bool _isPhysical;
private bool _flying; private bool _flying;
@ -70,10 +68,10 @@ public sealed class BSCharacter : BSPhysObject
: base(parent_scene, localID, avName, "BSCharacter") : base(parent_scene, localID, avName, "BSCharacter")
{ {
_physicsActorType = (int)ActorTypes.Agent; _physicsActorType = (int)ActorTypes.Agent;
_position = pos; RawPosition = pos;
_flying = isFlying; _flying = isFlying;
_orientation = OMV.Quaternion.Identity; RawOrientation = OMV.Quaternion.Identity;
RawVelocity = OMV.Vector3.Zero; RawVelocity = OMV.Vector3.Zero;
_buoyancy = ComputeBuoyancyFromFlying(isFlying); _buoyancy = ComputeBuoyancyFromFlying(isFlying);
Friction = BSParam.AvatarStandingFriction; Friction = BSParam.AvatarStandingFriction;
@ -133,7 +131,7 @@ public sealed class BSCharacter : BSPhysObject
PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody); PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
ZeroMotion(true); ZeroMotion(true);
ForcePosition = _position; ForcePosition = RawPosition;
// Set the velocity // Set the velocity
if (m_moveActor != null) if (m_moveActor != null)
@ -272,38 +270,33 @@ public sealed class BSCharacter : BSPhysObject
public override void LockAngularMotion(OMV.Vector3 axis) { return; } public override void LockAngularMotion(OMV.Vector3 axis) { return; }
public override OMV.Vector3 RawPosition
{
get { return _position; }
set { _position = value; }
}
public override OMV.Vector3 Position { public override OMV.Vector3 Position {
get { get {
// Don't refetch the position because this function is called a zillion times // Don't refetch the position because this function is called a zillion times
// _position = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID); // RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
return _position; return RawPosition;
} }
set { set {
_position = value; RawPosition = value;
PhysScene.TaintedObject("BSCharacter.setPosition", delegate() PhysScene.TaintedObject("BSCharacter.setPosition", delegate()
{ {
DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
PositionSanityCheck(); PositionSanityCheck();
ForcePosition = _position; ForcePosition = RawPosition;
}); });
} }
} }
public override OMV.Vector3 ForcePosition { public override OMV.Vector3 ForcePosition {
get { get {
_position = PhysScene.PE.GetPosition(PhysBody); RawPosition = PhysScene.PE.GetPosition(PhysBody);
return _position; return RawPosition;
} }
set { set {
_position = value; RawPosition = value;
if (PhysBody.HasPhysicalBody) if (PhysBody.HasPhysicalBody)
{ {
PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
} }
} }
} }
@ -331,16 +324,16 @@ public sealed class BSCharacter : BSPhysObject
float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
if (Position.Z < terrainHeight) if (Position.Z < terrainHeight)
{ {
DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, _position, terrainHeight); DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
_position.Z = terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters; RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters);
ret = true; ret = true;
} }
if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
{ {
float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(_position); float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
if (Position.Z < waterHeight) if (Position.Z < waterHeight)
{ {
_position.Z = waterHeight; RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight);
ret = true; ret = true;
} }
} }
@ -360,8 +353,8 @@ public sealed class BSCharacter : BSPhysObject
// just assign to "Position" because of potential call loops. // just assign to "Position" because of potential call loops.
PhysScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate() PhysScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate()
{ {
DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
ForcePosition = _position; ForcePosition = RawPosition;
}); });
ret = true; ret = true;
} }
@ -466,19 +459,14 @@ public sealed class BSCharacter : BSPhysObject
get { return _acceleration; } get { return _acceleration; }
set { _acceleration = value; } set { _acceleration = value; }
} }
public override OMV.Quaternion RawOrientation
{
get { return _orientation; }
set { _orientation = value; }
}
public override OMV.Quaternion Orientation { public override OMV.Quaternion Orientation {
get { return _orientation; } get { return RawOrientation; }
set { set {
// Orientation is set zillions of times when an avatar is walking. It's like // Orientation is set zillions of times when an avatar is walking. It's like
// the viewer doesn't trust us. // the viewer doesn't trust us.
if (_orientation != value) if (RawOrientation != value)
{ {
_orientation = value; RawOrientation = value;
PhysScene.TaintedObject("BSCharacter.setOrientation", delegate() PhysScene.TaintedObject("BSCharacter.setOrientation", delegate()
{ {
// Bullet assumes we know what we are doing when forcing orientation // Bullet assumes we know what we are doing when forcing orientation
@ -486,10 +474,10 @@ public sealed class BSCharacter : BSPhysObject
// This forces rotation to be only around the Z axis and doesn't change any of the other axis. // This forces rotation to be only around the Z axis and doesn't change any of the other axis.
// This keeps us from flipping the capsule over which the veiwer does not understand. // This keeps us from flipping the capsule over which the veiwer does not understand.
float oRoll, oPitch, oYaw; float oRoll, oPitch, oYaw;
_orientation.GetEulerAngles(out oRoll, out oPitch, out oYaw); RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw);
OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw); OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw);
// DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}", // DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}",
// LocalID, _orientation, OMV.Vector3.UnitX * _orientation, // LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation,
// trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation); // trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation);
ForceOrientation = trimmedOrientation; ForceOrientation = trimmedOrientation;
}); });
@ -501,16 +489,16 @@ public sealed class BSCharacter : BSPhysObject
{ {
get get
{ {
_orientation = PhysScene.PE.GetOrientation(PhysBody); RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
return _orientation; return RawOrientation;
} }
set set
{ {
_orientation = value; RawOrientation = value;
if (PhysBody.HasPhysicalBody) if (PhysBody.HasPhysicalBody)
{ {
// _position = PhysicsScene.PE.GetPosition(BSBody); // RawPosition = PhysicsScene.PE.GetPosition(BSBody);
PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
} }
} }
} }
@ -723,9 +711,9 @@ public sealed class BSCharacter : BSPhysObject
{ {
// Don't change position if standing on a stationary object. // Don't change position if standing on a stationary object.
if (!IsStationary) if (!IsStationary)
_position = entprop.Position; RawPosition = entprop.Position;
_orientation = entprop.Rotation; RawOrientation = entprop.Rotation;
// Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
// and will send agent updates to the clients if velocity changes by more than // and will send agent updates to the clients if velocity changes by more than
@ -740,8 +728,8 @@ public sealed class BSCharacter : BSPhysObject
// Do some sanity checking for the avatar. Make sure it's above ground and inbounds. // Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
if (PositionSanityCheck(true)) if (PositionSanityCheck(true))
{ {
DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, _position); DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition);
entprop.Position = _position; entprop.Position = RawPosition;
} }
// remember the current and last set values // remember the current and last set values
@ -755,7 +743,7 @@ public sealed class BSCharacter : BSPhysObject
// base.RequestPhysicsterseUpdate(); // base.RequestPhysicsterseUpdate();
DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
LocalID, _position, _orientation, RawVelocity, _acceleration, _rotationalVelocity); LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, _rotationalVelocity);
} }
} }
} }

View File

@ -144,7 +144,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin
public void SetupVehicleDebugging() public void SetupVehicleDebugging()
{ {
enableAngularVerticalAttraction = true; enableAngularVerticalAttraction = true;
enableAngularDeflection = false; enableAngularDeflection = true;
enableAngularBanking = true; enableAngularBanking = true;
if (BSParam.VehicleDebuggingEnable) if (BSParam.VehicleDebuggingEnable)
{ {
@ -173,7 +173,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin
switch (pParam) switch (pParam)
{ {
case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY: case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
m_angularDeflectionEfficiency = Math.Max(pValue, 0.01f); m_angularDeflectionEfficiency = ClampInRange(0f, pValue, 1f);
break; break;
case Vehicle.ANGULAR_DEFLECTION_TIMESCALE: case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
m_angularDeflectionTimescale = Math.Max(pValue, 0.01f); m_angularDeflectionTimescale = Math.Max(pValue, 0.01f);
@ -774,7 +774,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin
// Since the computation of terrain height can be a little involved, this routine // Since the computation of terrain height can be a little involved, this routine
// is used to fetch the height only once for each vehicle simulation step. // is used to fetch the height only once for each vehicle simulation step.
Vector3 lastRememberedHeightPos; Vector3 lastRememberedHeightPos = new Vector3(-1, -1, -1);
private float GetTerrainHeight(Vector3 pos) private float GetTerrainHeight(Vector3 pos)
{ {
if ((m_knownHas & m_knownChangedTerrainHeight) == 0 || pos != lastRememberedHeightPos) if ((m_knownHas & m_knownChangedTerrainHeight) == 0 || pos != lastRememberedHeightPos)
@ -788,14 +788,16 @@ namespace OpenSim.Region.Physics.BulletSPlugin
// Since the computation of water level can be a little involved, this routine // Since the computation of water level can be a little involved, this routine
// is used ot fetch the level only once for each vehicle simulation step. // is used ot fetch the level only once for each vehicle simulation step.
Vector3 lastRememberedWaterHeightPos = new Vector3(-1, -1, -1);
private float GetWaterLevel(Vector3 pos) private float GetWaterLevel(Vector3 pos)
{ {
if ((m_knownHas & m_knownChangedWaterLevel) == 0) if ((m_knownHas & m_knownChangedWaterLevel) == 0 || pos != lastRememberedWaterHeightPos)
{ {
lastRememberedWaterHeightPos = pos;
m_knownWaterLevel = ControllingPrim.PhysScene.TerrainManager.GetWaterLevelAtXYZ(pos); m_knownWaterLevel = ControllingPrim.PhysScene.TerrainManager.GetWaterLevelAtXYZ(pos);
m_knownHas |= m_knownChangedWaterLevel; m_knownHas |= m_knownChangedWaterLevel;
} }
return (float)m_knownWaterLevel; return m_knownWaterLevel;
} }
private Vector3 VehiclePosition private Vector3 VehiclePosition
@ -991,11 +993,17 @@ namespace OpenSim.Region.Physics.BulletSPlugin
{ {
Vector3 vel = VehicleVelocity; Vector3 vel = VehicleVelocity;
if ((m_flags & (VehicleFlag.NO_X)) != 0) if ((m_flags & (VehicleFlag.NO_X)) != 0)
{
vel.X = 0; vel.X = 0;
}
if ((m_flags & (VehicleFlag.NO_Y)) != 0) if ((m_flags & (VehicleFlag.NO_Y)) != 0)
{
vel.Y = 0; vel.Y = 0;
}
if ((m_flags & (VehicleFlag.NO_Z)) != 0) if ((m_flags & (VehicleFlag.NO_Z)) != 0)
{
vel.Z = 0; vel.Z = 0;
}
VehicleVelocity = vel; VehicleVelocity = vel;
} }
@ -1505,10 +1513,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin
// TODO: implement reference frame. // TODO: implement reference frame.
public void ComputeAngularDeflection() public void ComputeAngularDeflection()
{ {
// Since angularMotorUp and angularDeflection are computed independently, they will calculate
// approximately the same X or Y correction. When added together (when contributions are combined)
// this creates an over-correction and then wabbling as the target is overshot.
// TODO: rethink how the different correction computations inter-relate.
if (enableAngularDeflection && m_angularDeflectionEfficiency != 0 && VehicleForwardSpeed > 0.2) if (enableAngularDeflection && m_angularDeflectionEfficiency != 0 && VehicleForwardSpeed > 0.2)
{ {
@ -1523,10 +1527,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin
// The direction the vehicle is pointing // The direction the vehicle is pointing
Vector3 pointingDirection = Vector3.UnitX * VehicleOrientation; Vector3 pointingDirection = Vector3.UnitX * VehicleOrientation;
pointingDirection.Normalize(); //Predict where the Vehicle will be pointing after AngularVelocity change is applied. This will keep
// from overshooting and allow this correction to merge with the Vertical Attraction peacefully.
Vector3 predictedPointingDirection = pointingDirection * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f);
predictedPointingDirection.Normalize();
// The difference between what is and what should be. // The difference between what is and what should be.
Vector3 deflectionError = movingDirection - pointingDirection; // Vector3 deflectionError = movingDirection - predictedPointingDirection;
Vector3 deflectionError = Vector3.Cross(movingDirection, predictedPointingDirection);
// Don't try to correct very large errors (not our job) // Don't try to correct very large errors (not our job)
// if (Math.Abs(deflectionError.X) > PIOverFour) deflectionError.X = PIOverTwo * Math.Sign(deflectionError.X); // if (Math.Abs(deflectionError.X) > PIOverFour) deflectionError.X = PIOverTwo * Math.Sign(deflectionError.X);
@ -1539,15 +1547,16 @@ namespace OpenSim.Region.Physics.BulletSPlugin
// ret = m_angularDeflectionCorrectionMotor(1f, deflectionError); // ret = m_angularDeflectionCorrectionMotor(1f, deflectionError);
// Scale the correction by recovery timescale and efficiency // Scale the correction by recovery timescale and efficiency
deflectContributionV = (-deflectionError) * m_angularDeflectionEfficiency; // Not modeling a spring so clamp the scale to no more then the arc
deflectContributionV /= m_angularDeflectionTimescale; deflectContributionV = (-deflectionError) * ClampInRange(0, m_angularDeflectionEfficiency/m_angularDeflectionTimescale,1f);
//deflectContributionV /= m_angularDeflectionTimescale;
VehicleRotationalVelocity += deflectContributionV * VehicleOrientation;
// VehicleRotationalVelocity += deflectContributionV * VehicleOrientation;
VehicleRotationalVelocity += deflectContributionV;
VDetailLog("{0}, MoveAngular,Deflection,movingDir={1},pointingDir={2},deflectError={3},ret={4}", VDetailLog("{0}, MoveAngular,Deflection,movingDir={1},pointingDir={2},deflectError={3},ret={4}",
ControllingPrim.LocalID, movingDirection, pointingDirection, deflectionError, deflectContributionV); ControllingPrim.LocalID, movingDirection, pointingDirection, deflectionError, deflectContributionV);
VDetailLog("{0}, MoveAngular,Deflection,fwdSpd={1},defEff={2},defTS={3}", VDetailLog("{0}, MoveAngular,Deflection,fwdSpd={1},defEff={2},defTS={3},PredictedPointingDir={4}",
ControllingPrim.LocalID, VehicleForwardSpeed, m_angularDeflectionEfficiency, m_angularDeflectionTimescale); ControllingPrim.LocalID, VehicleForwardSpeed, m_angularDeflectionEfficiency, m_angularDeflectionTimescale, predictedPointingDirection);
} }
} }

View File

@ -35,62 +35,6 @@ using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin namespace OpenSim.Region.Physics.BulletSPlugin
{ {
/*
// When a child is linked, the relationship position of the child to the parent
// is remembered so the child's world position can be recomputed when it is
// removed from the linkset.
sealed class BSLinksetCompoundInfo : BSLinksetInfo
{
public int Index;
public OMV.Vector3 OffsetFromRoot;
public OMV.Vector3 OffsetFromCenterOfMass;
public OMV.Quaternion OffsetRot;
public BSLinksetCompoundInfo(int indx, OMV.Vector3 p, OMV.Quaternion r)
{
Index = indx;
OffsetFromRoot = p;
OffsetFromCenterOfMass = p;
OffsetRot = r;
}
// 'centerDisplacement' is the distance from the root the the center-of-mass (Bullet 'zero' of the shape)
public BSLinksetCompoundInfo(int indx, BSPrimLinkable root, BSPrimLinkable child, OMV.Vector3 centerDisplacement)
{
// Each child position and rotation is given relative to the center-of-mass.
OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(root.RawOrientation);
OMV.Vector3 displacementFromRoot = (child.RawPosition - root.RawPosition) * invRootOrientation;
OMV.Vector3 displacementFromCOM = displacementFromRoot - centerDisplacement;
OMV.Quaternion displacementRot = child.RawOrientation * invRootOrientation;
// Save relative position for recomputing child's world position after moving linkset.
Index = indx;
OffsetFromRoot = displacementFromRoot;
OffsetFromCenterOfMass = displacementFromCOM;
OffsetRot = displacementRot;
}
public override void Clear()
{
Index = 0;
OffsetFromRoot = OMV.Vector3.Zero;
OffsetFromCenterOfMass = OMV.Vector3.Zero;
OffsetRot = OMV.Quaternion.Identity;
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("<i=");
buff.Append(Index.ToString());
buff.Append(",p=");
buff.Append(OffsetFromRoot.ToString());
buff.Append(",m=");
buff.Append(OffsetFromCenterOfMass.ToString());
buff.Append(",r=");
buff.Append(OffsetRot.ToString());
buff.Append(">");
return buff.ToString();
}
};
*/
public sealed class BSLinksetCompound : BSLinkset public sealed class BSLinksetCompound : BSLinkset
{ {
private static string LogHeader = "[BULLETSIM LINKSET COMPOUND]"; private static string LogHeader = "[BULLETSIM LINKSET COMPOUND]";
@ -151,7 +95,9 @@ public sealed class BSLinksetCompound : BSLinkset
public override bool MakeStatic(BSPrimLinkable child) public override bool MakeStatic(BSPrimLinkable child)
{ {
bool ret = false; bool ret = false;
DetailLog("{0},BSLinksetCompound.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child)); DetailLog("{0},BSLinksetCompound.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child));
child.ClearDisplacement();
if (IsRoot(child)) if (IsRoot(child))
{ {
// Schedule a rebuild to verify that the root shape is set to the real shape. // Schedule a rebuild to verify that the root shape is set to the real shape.
@ -315,7 +261,6 @@ public sealed class BSLinksetCompound : BSLinkset
// Note that this works for rebuilding just the root after a linkset is taken apart. // Note that this works for rebuilding just the root after a linkset is taken apart.
// Called at taint time!! // Called at taint time!!
private bool UseBulletSimRootOffsetHack = false; // Attempt to have Bullet track the coords of root compound shape private bool UseBulletSimRootOffsetHack = false; // Attempt to have Bullet track the coords of root compound shape
private bool disableCOM = true; // For basic linkset debugging, turn off the center-of-mass setting
private void RecomputeLinksetCompound() private void RecomputeLinksetCompound()
{ {
try try
@ -326,55 +271,70 @@ public sealed class BSLinksetCompound : BSLinkset
// to what they should be as if the root was not in a linkset. // to what they should be as if the root was not in a linkset.
// Not that bad since we only get into this routine if there are children in the linkset and // Not that bad since we only get into this routine if there are children in the linkset and
// something has been updated/changed. // something has been updated/changed.
// Have to do the rebuild before checking for physical because this might be a linkset
// being destructed and going non-physical.
LinksetRoot.ForceBodyShapeRebuild(true); LinksetRoot.ForceBodyShapeRebuild(true);
// There is no reason to build all this physical stuff for a non-physical linkset. // There is no reason to build all this physical stuff for a non-physical linkset.
if (!LinksetRoot.IsPhysicallyActive) if (!LinksetRoot.IsPhysicallyActive)
{ {
// Clean up any old linkset shape and make sure the root shape is set to the root object.
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID);
return; // Note the 'finally' clause at the botton which will get executed. return; // Note the 'finally' clause at the botton which will get executed.
} }
// Get a new compound shape to build the linkset shape in. // Get a new compound shape to build the linkset shape in.
BSShape linksetShape = BSShapeCompound.GetReference(m_physicsScene); BSShape linksetShape = BSShapeCompound.GetReference(m_physicsScene);
// The center of mass for the linkset is the geometric center of the group.
// Compute a displacement for each component so it is relative to the center-of-mass. // Compute a displacement for each component so it is relative to the center-of-mass.
// Bullet presumes an object's origin (relative <0,0,0>) is its center-of-mass // Bullet presumes an object's origin (relative <0,0,0>) is its center-of-mass
OMV.Vector3 centerOfMassW = ComputeLinksetCenterOfMass(); OMV.Vector3 centerOfMassW = ComputeLinksetCenterOfMass();
OMV.Quaternion invRootOrientation = OMV.Quaternion.Normalize(OMV.Quaternion.Inverse(LinksetRoot.RawOrientation)); OMV.Quaternion invRootOrientation = OMV.Quaternion.Normalize(OMV.Quaternion.Inverse(LinksetRoot.RawOrientation));
OMV.Vector3 origRootPosition = LinksetRoot.RawPosition;
// 'centerDisplacement' is the value to subtract from children to give physical offset position // 'centerDisplacementV' is the vehicle relative distance from the simulator root position to the center-of-mass
OMV.Vector3 centerDisplacementV = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation; OMV.Vector3 centerDisplacementV = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation;
if (UseBulletSimRootOffsetHack || disableCOM) if (UseBulletSimRootOffsetHack || !BSParam.LinksetOffsetCenterOfMass)
{ {
// Zero everything if center-of-mass displacement is not being done.
centerDisplacementV = OMV.Vector3.Zero; centerDisplacementV = OMV.Vector3.Zero;
LinksetRoot.ClearDisplacement(); LinksetRoot.ClearDisplacement();
} }
else else
{ {
LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacementV); // The actual center-of-mass could have been set by the user.
centerDisplacementV = LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacementV);
} }
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,rootPos={1},com={2},comDisp={3}", DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,rootPos={1},com={2},comDisp={3}",
LinksetRoot.LocalID, LinksetRoot.RawPosition, centerOfMassW, centerDisplacementV); LinksetRoot.LocalID, origRootPosition, centerOfMassW, centerDisplacementV);
// Add the shapes of all the components of the linkset // Add the shapes of all the components of the linkset
int memberIndex = 1; int memberIndex = 1;
ForEachMember(delegate(BSPrimLinkable cPrim) ForEachMember(delegate(BSPrimLinkable cPrim)
{
if (IsRoot(cPrim))
{ {
// Root shape is always index zero. // Root shape is always index zero.
cPrim.LinksetChildIndex = IsRoot(cPrim) ? 0 : memberIndex; cPrim.LinksetChildIndex = 0;
}
else
{
cPrim.LinksetChildIndex = memberIndex;
memberIndex++;
}
// Get a reference to the shape of the child and add that shape to the linkset compound shape // Get a reference to the shape of the child for adding of that shape to the linkset compound shape
BSShape childShape = cPrim.PhysShape.GetReference(m_physicsScene, cPrim); BSShape childShape = cPrim.PhysShape.GetReference(m_physicsScene, cPrim);
OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacementV;
// Offset the child shape from the center-of-mass and rotate it to vehicle relative.
OMV.Vector3 offsetPos = (cPrim.RawPosition - origRootPosition) * invRootOrientation - centerDisplacementV;
OMV.Quaternion offsetRot = OMV.Quaternion.Normalize(cPrim.RawOrientation) * invRootOrientation; OMV.Quaternion offsetRot = OMV.Quaternion.Normalize(cPrim.RawOrientation) * invRootOrientation;
// Add the child shape to the compound shape being built
m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}", DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}",
LinksetRoot.LocalID, memberIndex, childShape, offsetPos, offsetRot); LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot);
// Since we are borrowing the shape of the child, disable the origional child body // Since we are borrowing the shape of the child, disable the origional child body
if (!IsRoot(cPrim)) if (!IsRoot(cPrim))
@ -386,8 +346,6 @@ public sealed class BSLinksetCompound : BSLinkset
cPrim.PhysBody.collisionType = CollisionType.LinksetChild; cPrim.PhysBody.collisionType = CollisionType.LinksetChild;
} }
memberIndex++;
return false; // 'false' says to move onto the next child in the list return false; // 'false' says to move onto the next child in the list
}); });
@ -409,8 +367,9 @@ public sealed class BSLinksetCompound : BSLinkset
{ {
// Enable the physical position updator to return the position and rotation of the root shape. // Enable the physical position updator to return the position and rotation of the root shape.
// This enables a feature in the C++ code to return the world coordinates of the first shape in the // This enables a feature in the C++ code to return the world coordinates of the first shape in the
// compound shape. This eleviates the need to offset the returned physical position by the // compound shape. This aleviates the need to offset the returned physical position by the
// center-of-mass offset. // center-of-mass offset.
// TODO: either debug this feature or remove it.
m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE);
} }
} }

View File

@ -188,6 +188,8 @@ public class BSVMotor : BSMotor
CurrentValue = current; CurrentValue = current;
return Step(timeStep); return Step(timeStep);
} }
// Given and error, computer a correction for this step.
// Simple scaling of the error by the timestep.
public virtual Vector3 StepError(float timeStep, Vector3 error) public virtual Vector3 StepError(float timeStep, Vector3 error)
{ {
if (!Enabled) return Vector3.Zero; if (!Enabled) return Vector3.Zero;
@ -221,7 +223,7 @@ public class BSVMotor : BSMotor
CurrentValue, TargetValue); CurrentValue, TargetValue);
LastError = BSMotor.InfiniteVector; LastError = BSMotor.InfiniteVector;
while (maxOutput-- > 0 && !LastError.ApproxEquals(Vector3.Zero, ErrorZeroThreshold)) while (maxOutput-- > 0 && !ErrorIsZero())
{ {
Vector3 lastStep = Step(timeStep); Vector3 lastStep = Step(timeStep);
MDetailLog("{0},BSVMotor.Test,{1},cur={2},tgt={3},lastError={4},lastStep={5}", MDetailLog("{0},BSVMotor.Test,{1},cur={2},tgt={3},lastError={4},lastStep={5}",
@ -375,7 +377,6 @@ public class BSPIDVMotor : BSVMotor
// The factors are vectors for the three dimensions. This is the proportional of each // The factors are vectors for the three dimensions. This is the proportional of each
// that is applied. This could be multiplied through the actual factors but it // that is applied. This could be multiplied through the actual factors but it
// is sometimes easier to manipulate the factors and their mix separately. // is sometimes easier to manipulate the factors and their mix separately.
// to
public Vector3 FactorMix; public Vector3 FactorMix;
// Arbritrary factor range. // Arbritrary factor range.
@ -413,14 +414,14 @@ public class BSPIDVMotor : BSVMotor
// If efficiency is high (1f), use a factor value that moves the error value to zero with little overshoot. // If efficiency is high (1f), use a factor value that moves the error value to zero with little overshoot.
// If efficiency is low (0f), use a factor value that overcorrects. // If efficiency is low (0f), use a factor value that overcorrects.
// TODO: might want to vary contribution of different factor depending on efficiency. // TODO: might want to vary contribution of different factor depending on efficiency.
float factor = ((1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow) / 3f; // float factor = ((1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow) / 3f;
// float factor = (1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow; float factor = (1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow;
proportionFactor = new Vector3(factor, factor, factor); proportionFactor = new Vector3(factor, factor, factor);
integralFactor = new Vector3(factor, factor, factor); integralFactor = new Vector3(factor, factor, factor);
derivFactor = new Vector3(factor, factor, factor); derivFactor = new Vector3(factor, factor, factor);
MDetailLog("{0},BSPIDVMotor.setEfficiency,eff={1},factor={2}", BSScene.DetailLogZero, Efficiency, factor); MDetailLog("{0}, BSPIDVMotor.setEfficiency,eff={1},factor={2}", BSScene.DetailLogZero, Efficiency, factor);
} }
} }
@ -441,8 +442,8 @@ public class BSPIDVMotor : BSVMotor
+ derivitive / TimeScale * derivFactor * FactorMix.Z + derivitive / TimeScale * derivFactor * FactorMix.Z
; ;
MDetailLog("{0}, BSPIDVMotor.step,ts={1},err={2},runnInt={3},deriv={4},ret={5}", MDetailLog("{0}, BSPIDVMotor.step,ts={1},err={2},lerr={3},runnInt={4},deriv={5},ret={6}",
BSScene.DetailLogZero, timeStep, error, RunningIntegration, derivitive, ret); BSScene.DetailLogZero, timeStep, error, LastError, RunningIntegration, derivitive, ret);
return ret; return ret;
} }

View File

@ -176,6 +176,7 @@ public static class BSParam
// Linkset implementation parameters // Linkset implementation parameters
public static float LinksetImplementation { get; private set; } public static float LinksetImplementation { get; private set; }
public static bool LinksetOffsetCenterOfMass { get; private set; }
public static bool LinkConstraintUseFrameOffset { get; private set; } public static bool LinkConstraintUseFrameOffset { get; private set; }
public static bool LinkConstraintEnableTransMotor { get; private set; } public static bool LinkConstraintEnableTransMotor { get; private set; }
public static float LinkConstraintTransMotorMaxVel { get; private set; } public static float LinkConstraintTransMotorMaxVel { get; private set; }
@ -684,6 +685,8 @@ public static class BSParam
new ParameterDefn<float>("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)", new ParameterDefn<float>("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)",
(float)BSLinkset.LinksetImplementation.Compound ), (float)BSLinkset.LinksetImplementation.Compound ),
new ParameterDefn<bool>("LinksetOffsetCenterOfMass", "If 'true', compute linkset center-of-mass and offset linkset position to account for same",
false ),
new ParameterDefn<bool>("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.", new ParameterDefn<bool>("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.",
false ), false ),
new ParameterDefn<bool>("LinkConstraintEnableTransMotor", "Whether to enable translational motor on linkset constraints", new ParameterDefn<bool>("LinkConstraintEnableTransMotor", "Whether to enable translational motor on linkset constraints",

View File

@ -90,6 +90,8 @@ public abstract class BSPhysObject : PhysicsActor
PhysBody = new BulletBody(localID); PhysBody = new BulletBody(localID);
PhysShape = new BSShapeNull(); PhysShape = new BSShapeNull();
UserSetCenterOfMassDisplacement = null;
PrimAssetState = PrimAssetCondition.Unknown; PrimAssetState = PrimAssetCondition.Unknown;
// Default material type. Also sets Friction, Restitution and Density. // Default material type. Also sets Friction, Restitution and Density.
@ -180,6 +182,7 @@ public abstract class BSPhysObject : PhysicsActor
Material = (MaterialAttributes.Material)material; Material = (MaterialAttributes.Material)material;
// Setting the material sets the material attributes also. // Setting the material sets the material attributes also.
// TODO: decide if this is necessary -- the simulator does this.
MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false); MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false);
Friction = matAttrib.friction; Friction = matAttrib.friction;
Restitution = matAttrib.restitution; Restitution = matAttrib.restitution;
@ -194,10 +197,10 @@ public abstract class BSPhysObject : PhysicsActor
// Update the physical location and motion of the object. Called with data from Bullet. // Update the physical location and motion of the object. Called with data from Bullet.
public abstract void UpdateProperties(EntityProperties entprop); public abstract void UpdateProperties(EntityProperties entprop);
public abstract OMV.Vector3 RawPosition { get; set; } public virtual OMV.Vector3 RawPosition { get; set; }
public abstract OMV.Vector3 ForcePosition { get; set; } public abstract OMV.Vector3 ForcePosition { get; set; }
public abstract OMV.Quaternion RawOrientation { get; set; } public virtual OMV.Quaternion RawOrientation { get; set; }
public abstract OMV.Quaternion ForceOrientation { get; set; } public abstract OMV.Quaternion ForceOrientation { get; set; }
public OMV.Vector3 RawVelocity { get; set; } public OMV.Vector3 RawVelocity { get; set; }

View File

@ -51,12 +51,8 @@ public class BSPrim : BSPhysObject
private bool _isSelected; private bool _isSelected;
private bool _isVolumeDetect; private bool _isVolumeDetect;
// _position is what the simulator thinks the positions of the prim is.
private OMV.Vector3 _position;
private float _mass; // the mass of this object private float _mass; // the mass of this object
private OMV.Vector3 _acceleration; private OMV.Vector3 _acceleration;
private OMV.Quaternion _orientation;
private int _physicsActorType; private int _physicsActorType;
private bool _isPhysical; private bool _isPhysical;
private bool _flying; private bool _flying;
@ -88,10 +84,10 @@ public class BSPrim : BSPhysObject
{ {
// m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID); // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID);
_physicsActorType = (int)ActorTypes.Prim; _physicsActorType = (int)ActorTypes.Prim;
_position = pos; RawPosition = pos;
_size = size; _size = size;
Scale = size; // prims are the size the user wants them to be (different for BSCharactes). Scale = size; // prims are the size the user wants them to be (different for BSCharactes).
_orientation = rotation; RawOrientation = rotation;
_buoyancy = 0f; _buoyancy = 0f;
RawVelocity = OMV.Vector3.Zero; RawVelocity = OMV.Vector3.Zero;
_rotationalVelocity = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero;
@ -270,46 +266,42 @@ public class BSPrim : BSPhysObject
return; return;
} }
public override OMV.Vector3 RawPosition
{
get { return _position; }
set { _position = value; }
}
public override OMV.Vector3 Position { public override OMV.Vector3 Position {
get { get {
// don't do the GetObjectPosition for root elements because this function is called a zillion times. // don't do the GetObjectPosition for root elements because this function is called a zillion times.
// _position = ForcePosition; // RawPosition = ForcePosition;
return _position; return RawPosition;
} }
set { set {
// If the position must be forced into the physics engine, use ForcePosition. // If the position must be forced into the physics engine, use ForcePosition.
// All positions are given in world positions. // All positions are given in world positions.
if (_position == value) if (RawPosition == value)
{ {
DetailLog("{0},BSPrim.setPosition,call,positionNotChanging,pos={1},orient={2}", LocalID, _position, _orientation); DetailLog("{0},BSPrim.setPosition,call,positionNotChanging,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
return; return;
} }
_position = value; RawPosition = value;
PositionSanityCheck(false); PositionSanityCheck(false);
PhysScene.TaintedObject("BSPrim.setPosition", delegate() PhysScene.TaintedObject("BSPrim.setPosition", delegate()
{ {
DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
ForcePosition = _position; ForcePosition = RawPosition;
}); });
} }
} }
// NOTE: overloaded by BSPrimDisplaced to handle offset for center-of-gravity.
public override OMV.Vector3 ForcePosition { public override OMV.Vector3 ForcePosition {
get { get {
_position = PhysScene.PE.GetPosition(PhysBody); RawPosition = PhysScene.PE.GetPosition(PhysBody);
return _position; return RawPosition;
} }
set { set {
_position = value; RawPosition = value;
if (PhysBody.HasPhysicalBody) if (PhysBody.HasPhysicalBody)
{ {
PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
ActivateIfPhysical(false); ActivateIfPhysical(false);
} }
} }
@ -343,10 +335,10 @@ public class BSPrim : BSPhysObject
float targetHeight = terrainHeight + (Size.Z / 2f); float targetHeight = terrainHeight + (Size.Z / 2f);
// If the object is below ground it just has to be moved up because pushing will // If the object is below ground it just has to be moved up because pushing will
// not get it through the terrain // not get it through the terrain
_position.Z = targetHeight; RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, targetHeight);
if (inTaintTime) if (inTaintTime)
{ {
ForcePosition = _position; ForcePosition = RawPosition;
} }
// If we are throwing the object around, zero its other forces // If we are throwing the object around, zero its other forces
ZeroMotion(inTaintTime); ZeroMotion(inTaintTime);
@ -355,7 +347,7 @@ public class BSPrim : BSPhysObject
if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
{ {
float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(_position); float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
// TODO: a floating motor so object will bob in the water // TODO: a floating motor so object will bob in the water
if (Math.Abs(RawPosition.Z - waterHeight) > 0.1f) if (Math.Abs(RawPosition.Z - waterHeight) > 0.1f)
{ {
@ -364,7 +356,7 @@ public class BSPrim : BSPhysObject
// Apply upforce and overcome gravity. // Apply upforce and overcome gravity.
OMV.Vector3 correctionForce = upForce - PhysScene.DefaultGravity; OMV.Vector3 correctionForce = upForce - PhysScene.DefaultGravity;
DetailLog("{0},BSPrim.PositionSanityCheck,applyForce,pos={1},upForce={2},correctionForce={3}", LocalID, _position, upForce, correctionForce); DetailLog("{0},BSPrim.PositionSanityCheck,applyForce,pos={1},upForce={2},correctionForce={3}", LocalID, RawPosition, upForce, correctionForce);
AddForce(correctionForce, false, inTaintTime); AddForce(correctionForce, false, inTaintTime);
ret = true; ret = true;
} }
@ -383,11 +375,11 @@ public class BSPrim : BSPhysObject
uint wayOutThere = Constants.RegionSize * Constants.RegionSize; uint wayOutThere = Constants.RegionSize * Constants.RegionSize;
// There have been instances of objects getting thrown way out of bounds and crashing // There have been instances of objects getting thrown way out of bounds and crashing
// the border crossing code. // the border crossing code.
if ( _position.X < -Constants.RegionSize || _position.X > wayOutThere if ( RawPosition.X < -Constants.RegionSize || RawPosition.X > wayOutThere
|| _position.Y < -Constants.RegionSize || _position.Y > wayOutThere || RawPosition.Y < -Constants.RegionSize || RawPosition.Y > wayOutThere
|| _position.Z < -Constants.RegionSize || _position.Z > wayOutThere) || RawPosition.Z < -Constants.RegionSize || RawPosition.Z > wayOutThere)
{ {
_position = new OMV.Vector3(10, 10, 50); RawPosition = new OMV.Vector3(10, 10, 50);
ZeroMotion(inTaintTime); ZeroMotion(inTaintTime);
ret = true; ret = true;
} }
@ -713,23 +705,19 @@ public class BSPrim : BSPhysObject
get { return _acceleration; } get { return _acceleration; }
set { _acceleration = value; } set { _acceleration = value; }
} }
public override OMV.Quaternion RawOrientation
{
get { return _orientation; }
set { _orientation = value; }
}
public override OMV.Quaternion Orientation { public override OMV.Quaternion Orientation {
get { get {
return _orientation; return RawOrientation;
} }
set { set {
if (_orientation == value) if (RawOrientation == value)
return; return;
_orientation = value; RawOrientation = value;
PhysScene.TaintedObject("BSPrim.setOrientation", delegate() PhysScene.TaintedObject("BSPrim.setOrientation", delegate()
{ {
ForceOrientation = _orientation; ForceOrientation = RawOrientation;
}); });
} }
} }
@ -738,14 +726,14 @@ public class BSPrim : BSPhysObject
{ {
get get
{ {
_orientation = PhysScene.PE.GetOrientation(PhysBody); RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
return _orientation; return RawOrientation;
} }
set set
{ {
_orientation = value; RawOrientation = value;
if (PhysBody.HasPhysicalBody) if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
} }
} }
public override int PhysicsActorType { public override int PhysicsActorType {
@ -802,6 +790,7 @@ public class BSPrim : BSPhysObject
// isSolid: other objects bounce off of this object // isSolid: other objects bounce off of this object
// isVolumeDetect: other objects pass through but can generate collisions // isVolumeDetect: other objects pass through but can generate collisions
// collisionEvents: whether this object returns collision events // collisionEvents: whether this object returns collision events
// NOTE: overloaded by BSPrimLinkable to also update linkset physical parameters.
public virtual void UpdatePhysicalParameters() public virtual void UpdatePhysicalParameters()
{ {
if (!PhysBody.HasPhysicalBody) if (!PhysBody.HasPhysicalBody)
@ -888,7 +877,7 @@ public class BSPrim : BSPhysObject
// PhysicsScene.PE.ClearAllForces(BSBody); // PhysicsScene.PE.ClearAllForces(BSBody);
// For good measure, make sure the transform is set through to the motion state // For good measure, make sure the transform is set through to the motion state
ForcePosition = _position; ForcePosition = RawPosition;
ForceVelocity = RawVelocity; ForceVelocity = RawVelocity;
ForceRotationalVelocity = _rotationalVelocity; ForceRotationalVelocity = _rotationalVelocity;
@ -1125,7 +1114,9 @@ public class BSPrim : BSPhysObject
OMV.Vector3 addForce = force; OMV.Vector3 addForce = force;
PhysScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate() PhysScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate()
{ {
// Bullet adds this central force to the total force for this tick // Bullet adds this central force to the total force for this tick.
// Deep down in Bullet:
// linearVelocity += totalForce / mass * timeStep;
DetailLog("{0},BSPrim.addForce,taint,force={1}", LocalID, addForce); DetailLog("{0},BSPrim.addForce,taint,force={1}", LocalID, addForce);
if (PhysBody.HasPhysicalBody) if (PhysBody.HasPhysicalBody)
{ {
@ -1493,6 +1484,8 @@ public class BSPrim : BSPhysObject
returnMass = Util.Clamp(returnMass, BSParam.MinimumObjectMass, BSParam.MaximumObjectMass); returnMass = Util.Clamp(returnMass, BSParam.MinimumObjectMass, BSParam.MaximumObjectMass);
// DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3}", LocalID, Density, volume, returnMass); // DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3}", LocalID, Density, volume, returnMass);
DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3},pathB={4},pathE={5},profB={6},profE={7},siz={8}",
LocalID, Density, volume, returnMass, pathBegin, pathEnd, profileBegin, profileEnd, _size);
return returnMass; return returnMass;
}// end CalculateMass }// end CalculateMass
@ -1528,6 +1521,8 @@ public class BSPrim : BSPhysObject
// The physics engine says that properties have updated. Update same and inform // The physics engine says that properties have updated. Update same and inform
// the world that things have changed. // the world that things have changed.
// NOTE: BSPrim.UpdateProperties is overloaded by BSPrimLinkable which modifies updates from root and children prims.
// NOTE: BSPrim.UpdateProperties is overloaded by BSPrimDisplaced which handles mapping physical position to simulator position.
public override void UpdateProperties(EntityProperties entprop) public override void UpdateProperties(EntityProperties entprop)
{ {
// Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator. // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
@ -1536,8 +1531,8 @@ public class BSPrim : BSPhysObject
// DetailLog("{0},BSPrim.UpdateProperties,entry,entprop={1}", LocalID, entprop); // DEBUG DEBUG // DetailLog("{0},BSPrim.UpdateProperties,entry,entprop={1}", LocalID, entprop); // DEBUG DEBUG
// Assign directly to the local variables so the normal set actions do not happen // Assign directly to the local variables so the normal set actions do not happen
_position = entprop.Position; RawPosition = entprop.Position;
_orientation = entprop.Rotation; RawOrientation = entprop.Rotation;
// DEBUG DEBUG DEBUG -- smooth velocity changes a bit. The simulator seems to be // DEBUG DEBUG DEBUG -- smooth velocity changes a bit. The simulator seems to be
// very sensitive to velocity changes. // very sensitive to velocity changes.
if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(RawVelocity, BSParam.UpdateVelocityChangeThreshold)) if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(RawVelocity, BSParam.UpdateVelocityChangeThreshold))
@ -1550,21 +1545,19 @@ public class BSPrim : BSPhysObject
// The sanity check can change the velocity and/or position. // The sanity check can change the velocity and/or position.
if (PositionSanityCheck(true /* inTaintTime */ )) if (PositionSanityCheck(true /* inTaintTime */ ))
{ {
entprop.Position = _position; entprop.Position = RawPosition;
entprop.Velocity = RawVelocity; entprop.Velocity = RawVelocity;
entprop.RotationalVelocity = _rotationalVelocity; entprop.RotationalVelocity = _rotationalVelocity;
entprop.Acceleration = _acceleration; entprop.Acceleration = _acceleration;
} }
OMV.Vector3 direction = OMV.Vector3.UnitX * _orientation; // DEBUG DEBUG DEBUG OMV.Vector3 direction = OMV.Vector3.UnitX * RawOrientation; // DEBUG DEBUG DEBUG
DetailLog("{0},BSPrim.UpdateProperties,call,entProp={1},dir={2}", LocalID, entprop, direction); DetailLog("{0},BSPrim.UpdateProperties,call,entProp={1},dir={2}", LocalID, entprop, direction);
// remember the current and last set values // remember the current and last set values
LastEntityProperties = CurrentEntityProperties; LastEntityProperties = CurrentEntityProperties;
CurrentEntityProperties = entprop; CurrentEntityProperties = entprop;
// Note that BSPrim can be overloaded by BSPrimLinkable which controls updates from root and children prims.
PhysScene.PostUpdate(this); PhysScene.PostUpdate(this);
} }
} }

View File

@ -23,11 +23,6 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The quotations from http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial
* are Copyright (c) 2009 Linden Research, Inc and are used under their license
* of Creative Commons Attribution-Share Alike 3.0
* (http://creativecommons.org/licenses/by-sa/3.0/).
*/ */
using System; using System;
@ -44,14 +39,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin
{ {
public class BSPrimDisplaced : BSPrim public class BSPrimDisplaced : BSPrim
{ {
// The purpose of this module is to do any mapping between what the simulator thinks // The purpose of this subclass is to do any mapping between what the simulator thinks
// the prim position and orientation is and what the physical position/orientation. // the prim position and orientation is and what the physical position/orientation.
// This difference happens because Bullet assumes the center-of-mass is the <0,0,0> // This difference happens because Bullet assumes the center-of-mass is the <0,0,0>
// of the prim/linkset. The simulator tracks the location of the prim/linkset by // of the prim/linkset. The simulator, on the other hand, tracks the location of
// the location of the root prim. So, if center-of-mass is anywhere but the origin // the prim/linkset by the location of the root prim. So, if center-of-mass is anywhere
// of the root prim, the physical origin is displaced from the simulator origin. // but the origin of the root prim, the physical origin is displaced from the simulator origin.
// //
// This routine works by capturing the Force* setting of position/orientation/... and // This routine works by capturing ForcePosition and
// adjusting the simulator values (being set) into the physical values. // adjusting the simulator values (being set) into the physical values.
// The conversion is also done in the opposite direction (physical origin -> simulator origin). // The conversion is also done in the opposite direction (physical origin -> simulator origin).
// //
@ -59,8 +54,8 @@ public class BSPrimDisplaced : BSPrim
// are converted into simulator origin values before being passed to the base // are converted into simulator origin values before being passed to the base
// class. // class.
// PositionDisplacement is the vehicle relative distance from the root prim position to the center-of-mass.
public virtual OMV.Vector3 PositionDisplacement { get; set; } public virtual OMV.Vector3 PositionDisplacement { get; set; }
public virtual OMV.Quaternion OrientationDisplacement { get; set; }
public BSPrimDisplaced(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, public BSPrimDisplaced(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size,
OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
@ -69,50 +64,82 @@ public class BSPrimDisplaced : BSPrim
ClearDisplacement(); ClearDisplacement();
} }
// Clears any center-of-mass displacement introduced by linksets, etc.
// Does not clear the displacement set by the user.
public void ClearDisplacement() public void ClearDisplacement()
{ {
if (UserSetCenterOfMassDisplacement.HasValue)
PositionDisplacement = (OMV.Vector3)UserSetCenterOfMassDisplacement;
else
PositionDisplacement = OMV.Vector3.Zero; PositionDisplacement = OMV.Vector3.Zero;
OrientationDisplacement = OMV.Quaternion.Identity;
} }
// Set this sets and computes the displacement from the passed prim to the center-of-mass. // Set this sets and computes the displacement from the passed prim to the center-of-mass.
// A user set value for center-of-mass overrides whatever might be passed in here. // A user set value for center-of-mass overrides whatever might be passed in here.
// The displacement is in local coordinates (relative to root prim in linkset oriented coordinates). // The displacement is in local coordinates (relative to root prim in linkset oriented coordinates).
public virtual void SetEffectiveCenterOfMassDisplacement(Vector3 centerOfMassDisplacement) // Returns the relative offset from the root position to the center-of-mass.
// Called at taint time.
public virtual Vector3 SetEffectiveCenterOfMassDisplacement(Vector3 centerOfMassDisplacement)
{ {
PhysScene.AssertInTaintTime("BSPrimDisplaced.SetEffectiveCenterOfMassDisplacement");
Vector3 comDisp; Vector3 comDisp;
if (UserSetCenterOfMassDisplacement.HasValue) if (UserSetCenterOfMassDisplacement.HasValue)
comDisp = (OMV.Vector3)UserSetCenterOfMassDisplacement; comDisp = (OMV.Vector3)UserSetCenterOfMassDisplacement;
else else
comDisp = centerOfMassDisplacement; comDisp = centerOfMassDisplacement;
// Eliminate any jitter caused be very slight differences in masses and positions
if (comDisp.ApproxEquals(Vector3.Zero, 0.01f) )
comDisp = Vector3.Zero;
DetailLog("{0},BSPrimDisplaced.SetEffectiveCenterOfMassDisplacement,userSet={1},comDisp={2}", DetailLog("{0},BSPrimDisplaced.SetEffectiveCenterOfMassDisplacement,userSet={1},comDisp={2}",
LocalID, UserSetCenterOfMassDisplacement.HasValue, comDisp); LocalID, UserSetCenterOfMassDisplacement.HasValue, comDisp);
if (comDisp == Vector3.Zero) if ( !comDisp.ApproxEquals(PositionDisplacement, 0.01f) )
{ {
// If there is no diplacement. Things get reset. // Displacement setting is changing.
PositionDisplacement = OMV.Vector3.Zero; // The relationship between the physical object and simulated object must be aligned.
OrientationDisplacement = OMV.Quaternion.Identity;
}
else
{
// Remember the displacement from root as well as the origional rotation of the
// new center-of-mass.
PositionDisplacement = comDisp; PositionDisplacement = comDisp;
OrientationDisplacement = OMV.Quaternion.Identity; this.ForcePosition = RawPosition;
}
} }
return PositionDisplacement;
}
// 'ForcePosition' is the one way to set the physical position of the body in the physics engine.
// Displace the simulator idea of position (center of root prim) to the physical position.
public override Vector3 ForcePosition public override Vector3 ForcePosition
{ {
get { return base.ForcePosition; } get {
OMV.Vector3 physPosition = PhysScene.PE.GetPosition(PhysBody);
if (PositionDisplacement != OMV.Vector3.Zero)
{
// If there is some displacement, return the physical position (center-of-mass)
// location minus the displacement to give the center of the root prim.
OMV.Vector3 displacement = PositionDisplacement * ForceOrientation;
DetailLog("{0},BSPrimDisplaced.ForcePosition,get,physPos={1},disp={2},simPos={3}",
LocalID, physPosition, displacement, physPosition - displacement);
physPosition -= displacement;
}
RawPosition = physPosition;
return physPosition;
}
set set
{ {
if (PositionDisplacement != OMV.Vector3.Zero) if (PositionDisplacement != OMV.Vector3.Zero)
{ {
OMV.Vector3 displacedPos = value - (PositionDisplacement * RawOrientation); // This value is the simulator's idea of where the prim is: the center of the root prim
DetailLog("{0},BSPrimDisplaced.ForcePosition,val={1},disp={2},newPos={3}", LocalID, value, PositionDisplacement, displacedPos); RawPosition = value;
base.ForcePosition = displacedPos;
// Move the passed root prim postion to the center-of-mass position and set in the physics engine.
OMV.Vector3 displacement = PositionDisplacement * RawOrientation;
OMV.Vector3 displacedPos = RawPosition + displacement;
DetailLog("{0},BSPrimDisplaced.ForcePosition,set,simPos={1},disp={2},physPos={3}",
LocalID, RawPosition, displacement, displacedPos);
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetTranslation(PhysBody, displacedPos, RawOrientation);
ActivateIfPhysical(false);
}
} }
else else
{ {
@ -121,25 +148,12 @@ public class BSPrimDisplaced : BSPrim
} }
} }
public override Quaternion ForceOrientation // These are also overridden by BSPrimLinkable if the prim can be part of a linkset
{
get { return base.ForceOrientation; }
set
{
// TODO:
base.ForceOrientation = value;
}
}
// TODO: decide if this is the right place for these variables.
// Somehow incorporate the optional settability by the user.
// Is this used?
public override OMV.Vector3 CenterOfMass public override OMV.Vector3 CenterOfMass
{ {
get { return RawPosition; } get { return RawPosition; }
} }
// Is this used?
public override OMV.Vector3 GeometricCenter public override OMV.Vector3 GeometricCenter
{ {
get { return RawPosition; } get { return RawPosition; }
@ -148,15 +162,18 @@ public class BSPrimDisplaced : BSPrim
public override void UpdateProperties(EntityProperties entprop) public override void UpdateProperties(EntityProperties entprop)
{ {
// Undo any center-of-mass displacement that might have been done. // Undo any center-of-mass displacement that might have been done.
if (PositionDisplacement != OMV.Vector3.Zero || OrientationDisplacement != OMV.Quaternion.Identity) if (PositionDisplacement != OMV.Vector3.Zero)
{ {
// Correct for any rotation around the center-of-mass // The origional shape was offset from 'zero' by PositionDisplacement.
// TODO!!! // These physical location must be back converted to be centered around the displaced
// root shape.
OMV.Vector3 displacedPos = entprop.Position + (PositionDisplacement * entprop.Rotation); // Move the returned center-of-mass location to the root prim location.
DetailLog("{0},BSPrimDisplaced.ForcePosition,physPos={1},disp={2},newPos={3}", LocalID, entprop.Position, PositionDisplacement, displacedPos); OMV.Vector3 displacement = PositionDisplacement * entprop.Rotation;
OMV.Vector3 displacedPos = entprop.Position - displacement;
DetailLog("{0},BSPrimDisplaced.UpdateProperties,physPos={1},disp={2},simPos={3}",
LocalID, entprop.Position, displacement, displacedPos);
entprop.Position = displacedPos; entprop.Position = displacedPos;
// entprop.Rotation = something;
} }
base.UpdateProperties(entprop); base.UpdateProperties(entprop);

View File

@ -37,6 +37,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin
{ {
public class BSPrimLinkable : BSPrimDisplaced public class BSPrimLinkable : BSPrimDisplaced
{ {
// The purpose of this subclass is to add linkset functionality to the prim. This overrides
// operations necessary for keeping the linkset created and, additionally, this
// calls the linkset implementation for its creation and management.
// This adds the overrides for link() and delink() so the prim is linkable.
public BSLinkset Linkset { get; set; } public BSLinkset Linkset { get; set; }
// The index of this child prim. // The index of this child prim.
public int LinksetChildIndex { get; set; } public int LinksetChildIndex { get; set; }
@ -69,8 +75,8 @@ public class BSPrimLinkable : BSPrimDisplaced
BSPrimLinkable parent = obj as BSPrimLinkable; BSPrimLinkable parent = obj as BSPrimLinkable;
if (parent != null) if (parent != null)
{ {
BSPhysObject parentBefore = Linkset.LinksetRoot; BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG
int childrenBefore = Linkset.NumberOfChildren; int childrenBefore = Linkset.NumberOfChildren; // DEBUG
Linkset = parent.Linkset.AddMeToLinkset(this); Linkset = parent.Linkset.AddMeToLinkset(this);
@ -85,8 +91,8 @@ public class BSPrimLinkable : BSPrimDisplaced
// TODO: decide if this parent checking needs to happen at taint time // TODO: decide if this parent checking needs to happen at taint time
// Race condition here: if link() and delink() in same simulation tick, the delink will not happen // Race condition here: if link() and delink() in same simulation tick, the delink will not happen
BSPhysObject parentBefore = Linkset.LinksetRoot; BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG
int childrenBefore = Linkset.NumberOfChildren; int childrenBefore = Linkset.NumberOfChildren; // DEBUG
Linkset = Linkset.RemoveMeFromLinkset(this); Linkset = Linkset.RemoveMeFromLinkset(this);
@ -128,6 +134,17 @@ public class BSPrimLinkable : BSPrimDisplaced
get { return Linkset.LinksetMass; } get { return Linkset.LinksetMass; }
} }
public override OMV.Vector3 CenterOfMass
{
get { return Linkset.CenterOfMass; }
}
public override OMV.Vector3 GeometricCenter
{
get { return Linkset.GeometricCenter; }
}
// Refresh the linkset structure and parameters when the prim's physical parameters are changed.
public override void UpdatePhysicalParameters() public override void UpdatePhysicalParameters()
{ {
base.UpdatePhysicalParameters(); base.UpdatePhysicalParameters();
@ -139,14 +156,18 @@ public class BSPrimLinkable : BSPrimDisplaced
Linkset.Refresh(this); Linkset.Refresh(this);
} }
// When the prim is made dynamic or static, the linkset needs to change.
protected override void MakeDynamic(bool makeStatic) protected override void MakeDynamic(bool makeStatic)
{ {
base.MakeDynamic(makeStatic); base.MakeDynamic(makeStatic);
if (Linkset != null) // null can happen during initialization
{
if (makeStatic) if (makeStatic)
Linkset.MakeStatic(this); Linkset.MakeStatic(this);
else else
Linkset.MakeDynamic(this); Linkset.MakeDynamic(this);
} }
}
// Body is being taken apart. Remove physical dependencies and schedule a rebuild. // Body is being taken apart. Remove physical dependencies and schedule a rebuild.
protected override void RemoveDependencies() protected override void RemoveDependencies()
@ -155,6 +176,8 @@ public class BSPrimLinkable : BSPrimDisplaced
base.RemoveDependencies(); base.RemoveDependencies();
} }
// Called after a simulation step for the changes in physical object properties.
// Do any filtering/modification needed for linksets.
public override void UpdateProperties(EntityProperties entprop) public override void UpdateProperties(EntityProperties entprop)
{ {
if (Linkset.IsRoot(this)) if (Linkset.IsRoot(this))
@ -176,6 +199,7 @@ public class BSPrimLinkable : BSPrimDisplaced
Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
} }
// Called after a simulation step to post a collision with this object.
public override bool Collide(uint collidingWith, BSPhysObject collidee, public override bool Collide(uint collidingWith, BSPhysObject collidee,
OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
{ {

View File

@ -785,7 +785,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters
{ {
// The simulation of the time interval took less than realtime. // The simulation of the time interval took less than realtime.
// Do a sleep for the rest of realtime. // Do a sleep for the rest of realtime.
DetailLog("{0},BulletSPluginPhysicsThread,sleeping={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS);
Thread.Sleep(simulationTimeVsRealtimeDifferenceMS); Thread.Sleep(simulationTimeVsRealtimeDifferenceMS);
} }
else else

View File

@ -3,25 +3,21 @@ CURRENT PROBLEMS TO FIX AND/OR LOOK AT
Vehicle buoyancy. Computed correctly? Possibly creating very large effective mass. Vehicle buoyancy. Computed correctly? Possibly creating very large effective mass.
Interaction of llSetBuoyancy and vehicle buoyancy. Should be additive? Interaction of llSetBuoyancy and vehicle buoyancy. Should be additive?
Negative buoyancy computed correctly Negative buoyancy computed correctly
Center-of-gravity
Computation of mesh mass. How done? How should it be done? Computation of mesh mass. How done? How should it be done?
Script changing rotation of child prim while vehicle moving (eg turning wheel) causes
the wheel to appear to jump back. Looks like sending position from previous update.
Enable vehicle border crossings (at least as poorly as ODE) Enable vehicle border crossings (at least as poorly as ODE)
Terrain skirts Terrain skirts
Avatar created in previous region and not new region when crossing border Avatar created in previous region and not new region when crossing border
Vehicle recreated in new sim at small Z value (offset from root value?) (DONE) Vehicle recreated in new sim at small Z value (offset from root value?) (DONE)
User settable terrain mesh
Allow specifying as convex or concave and use different getHeight functions depending
Boats, when turning nose down into the water
Acts like rotation around Z is also effecting rotation around X and Y
Deleting a linkset while standing on the root will leave the physical shape of the root behind. Deleting a linkset while standing on the root will leave the physical shape of the root behind.
Not sure if it is because standing on it. Done with large prim linksets. Not sure if it is because standing on it. Done with large prim linksets.
Linkset child rotations. Linkset child rotations.
Nebadon spiral tube has middle sections which are rotated wrong. Nebadon spiral tube has middle sections which are rotated wrong.
Select linked spiral tube. Delink and note where the middle section ends up. Select linked spiral tube. Delink and note where the middle section ends up.
Refarb compound linkset creation to create a pseudo-root for center-of-mass
Let children change their shape to physical indendently and just add shapes to compound
Vehicle angular vertical attraction
vehicle angular banking
Center-of-gravity
Vehicle angular deflection
Preferred orientation angular correction fix
Teravus llMoveToTarget script debug Teravus llMoveToTarget script debug
Mixing of hover, buoyancy/gravity, moveToTarget, into one force Mixing of hover, buoyancy/gravity, moveToTarget, into one force
Setting hover height to zero disables hover even if hover flags are on (from SL wiki) Setting hover height to zero disables hover even if hover flags are on (from SL wiki)
@ -33,10 +29,16 @@ Vehicle script tuning/debugging
Avanti speed script Avanti speed script
Weapon shooter script Weapon shooter script
Move material definitions (friction, ...) into simulator. Move material definitions (friction, ...) into simulator.
osGetPhysicsEngineVerion() and create a version code for the C++ DLL
One sided meshes? Should terrain be built into a closed shape? One sided meshes? Should terrain be built into a closed shape?
When meshes get partially wedged into the terrain, they cannot push themselves out. When meshes get partially wedged into the terrain, they cannot push themselves out.
It is possible that Bullet processes collisions whether entering or leaving a mesh. It is possible that Bullet processes collisions whether entering or leaving a mesh.
Ref: http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4869 Ref: http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4869
Small physical objects do not interact correctly
Create chain of .5x.5x.1 torui and make all but top physical so to hang.
The chain will fall apart and pairs will dance around on ground
Chains of 1x1x.2 will stay connected but will dance.
Chains above 2x2x.4 are more stable and get stablier as torui get larger.
VEHICLES TODO LIST: VEHICLES TODO LIST:
================================================= =================================================
@ -45,14 +47,12 @@ LINEAR_MOTOR_DIRECTION values should be clamped to reasonable numbers.
Same for other velocity settings. Same for other velocity settings.
UBit improvements to remove rubber-banding of avatars sitting on vehicle child prims: UBit improvements to remove rubber-banding of avatars sitting on vehicle child prims:
https://github.com/UbitUmarov/Ubit-opensim https://github.com/UbitUmarov/Ubit-opensim
Vehicles (Move smoothly)
Some vehicles should not be able to turn if no speed or off ground. Some vehicles should not be able to turn if no speed or off ground.
Cannot edit/move a vehicle being ridden: it jumps back to the origional position. Cannot edit/move a vehicle being ridden: it jumps back to the origional position.
Neb car jiggling left and right Neb car jiggling left and right
Happens on terrain and any other mesh object. Flat cubes are much smoother. Happens on terrain and any other mesh object. Flat cubes are much smoother.
This has been reduced but not eliminated. This has been reduced but not eliminated.
Implement referenceFrame for all the motion routines. Implement referenceFrame for all the motion routines.
For limitMotorUp, use raycast down to find if vehicle is in the air.
Verify llGetVel() is returning a smooth and good value for vehicle movement. Verify llGetVel() is returning a smooth and good value for vehicle movement.
llGetVel() should return the root's velocity if requested in a child prim. llGetVel() should return the root's velocity if requested in a child prim.
Implement function efficiency for lineaar and angular motion. Implement function efficiency for lineaar and angular motion.
@ -93,29 +93,15 @@ Revisit CollisionMargin. Builders notice the 0.04 spacing between prims.
Duplicating a physical prim causes old prim to jump away Duplicating a physical prim causes old prim to jump away
Dup a phys prim and the original become unselected and thus interacts w/ selected prim. Dup a phys prim and the original become unselected and thus interacts w/ selected prim.
Scenes with hundred of thousands of static objects take a lot of physics CPU time. Scenes with hundred of thousands of static objects take a lot of physics CPU time.
BSPrim.Force should set a continious force on the prim. The force should be
applied each tick. Some limits?
Gun sending shooter flying. Gun sending shooter flying.
Collision margin (gap between physical objects lying on each other) Collision margin (gap between physical objects lying on each other)
Boundry checking (crashes related to crossing boundry) Boundry checking (crashes related to crossing boundry)
Add check for border edge position for avatars and objects. Add check for border edge position for avatars and objects.
Verify the events are created for border crossings. Verify the events are created for border crossings.
Avatar rotation (check out changes to ScenePresence for physical rotation)
Avatar running (what does phys engine need to do?)
Small physical objects do not interact correctly
Create chain of .5x.5x.1 torui and make all but top physical so to hang.
The chain will fall apart and pairs will dance around on ground
Chains of 1x1x.2 will stay connected but will dance.
Chains above 2x2x.4 are more stable and get stablier as torui get larger.
Add PID motor for avatar movement (slow to stop, ...)
setForce should set a constant force. Different than AddImpulse.
Implement raycast.
Implement ShapeCollection.Dispose() Implement ShapeCollection.Dispose()
Implement water as a plain so raycasting and collisions can happen with same. Implement water as a plain or mesh so raycasting and collisions can happen with same.
Add collision penetration return Add collision penetration return
Add field passed back by BulletSim.dll and fill with info in ManifoldConstact.GetDistance() Add field passed back by BulletSim.dll and fill with info in ManifoldConstact.GetDistance()
Add osGetPhysicsEngineName() so scripters can tell whether BulletSim or ODE
Also osGetPhysicsEngineVerion() maybe.
Linkset.Position and Linkset.Orientation requre rewrite to properly return Linkset.Position and Linkset.Orientation requre rewrite to properly return
child position. LinksetConstraint acts like it's at taint time!! child position. LinksetConstraint acts like it's at taint time!!
Implement LockAngularMotion -- implements llSetStatus(ROTATE_AXIS_*, T/F) Implement LockAngularMotion -- implements llSetStatus(ROTATE_AXIS_*, T/F)
@ -127,9 +113,6 @@ Selecting and deselecting physical objects causes CPU processing time to jump
Re-implement buoyancy as a separate force on the object rather than diddling gravity. Re-implement buoyancy as a separate force on the object rather than diddling gravity.
Register a pre-step event to add the force. Register a pre-step event to add the force.
More efficient memory usage when passing hull information from BSPrim to BulletSim More efficient memory usage when passing hull information from BSPrim to BulletSim
Avatar movement motor check for zero or small movement. Somehow suppress small movements
when avatar has stopped and is just standing. Simple test for near zero has
the problem of preventing starting up (increase from zero) especially when falling.
Physical and phantom will drop through the terrain Physical and phantom will drop through the terrain
@ -172,7 +155,6 @@ Do we need to do convex hulls all the time? Can complex meshes be left meshes?
There is some problem with meshes and collisions There is some problem with meshes and collisions
Hulls are not as detailed as meshes. Hulled vehicles insides are different shape. Hulls are not as detailed as meshes. Hulled vehicles insides are different shape.
Debounce avatar contact so legs don't keep folding up when standing. Debounce avatar contact so legs don't keep folding up when standing.
Implement LSL physics controls. Like STATUS_ROTATE_X.
Add border extensions to terrain to help region crossings and objects leaving region. Add border extensions to terrain to help region crossings and objects leaving region.
Use a different capsule shape for avatar when sitting Use a different capsule shape for avatar when sitting
LL uses a pyrimidal shape scaled by the avatar's bounding box LL uses a pyrimidal shape scaled by the avatar's bounding box
@ -205,8 +187,6 @@ Keep avatar scaling correct. http://pennycow.blogspot.fr/2011/07/matter-of-scale
INTERNAL IMPROVEMENT/CLEANUP INTERNAL IMPROVEMENT/CLEANUP
================================================= =================================================
Can the 'inTaintTime' flag be cleaned up and used? For instance, a call to
BSScene.TaintedObject() could immediately execute the callback if already in taint time.
Create the physical wrapper classes (BulletBody, BulletShape) by methods on Create the physical wrapper classes (BulletBody, BulletShape) by methods on
BSAPITemplate and make their actual implementation Bullet engine specific. BSAPITemplate and make their actual implementation Bullet engine specific.
For the short term, just call the existing functions in ShapeCollection. For the short term, just call the existing functions in ShapeCollection.
@ -365,4 +345,35 @@ After getting off a vehicle, the root prim is phantom (can be walked through)
Explore btGImpactMeshShape as alternative to convex hulls for simplified physical objects. Explore btGImpactMeshShape as alternative to convex hulls for simplified physical objects.
Regular triangle meshes don't do physical collisions. Regular triangle meshes don't do physical collisions.
(DONE: discovered GImpact is VERY CPU intensive) (DONE: discovered GImpact is VERY CPU intensive)
Script changing rotation of child prim while vehicle moving (eg turning wheel) causes
the wheel to appear to jump back. Looks like sending position from previous update.
(DONE: redo of compound linksets fixed problem)
Refarb compound linkset creation to create a pseudo-root for center-of-mass
Let children change their shape to physical indendently and just add shapes to compound
(DONE: redo of compound linkset fixed problem)
Vehicle angular vertical attraction (DONE: vegaslon code)
vehicle angular banking (DONE: vegaslon code)
Vehicle angular deflection (DONE: vegaslon code)
Preferred orientation angular correction fix
Vehicles (Move smoothly)
For limitMotorUp, use raycast down to find if vehicle is in the air.
(WILL NOT BE DONE: gravity does the job well enough)
BSPrim.Force should set a continious force on the prim. The force should be
applied each tick. Some limits?
(DONE: added physical actors. Implemented SetForce, SetTorque, ...)
Implement LSL physics controls. Like STATUS_ROTATE_X. (DONE)
Add osGetPhysicsEngineName() so scripters can tell whether BulletSim or ODE
Avatar rotation (check out changes to ScenePresence for physical rotation) (DONE)
Avatar running (what does phys engine need to do?) (DONE: multiplies run factor by walking force)
setForce should set a constant force. Different than AddImpulse. (DONE)
Add PID motor for avatar movement (slow to stop, ...) (WNBD: current works ok)
Avatar movement motor check for zero or small movement. Somehow suppress small movements
when avatar has stopped and is just standing. Simple test for near zero has
the problem of preventing starting up (increase from zero) especially when falling.
(DONE: avatar movement actor knows if standing on stationary object and zeros motion)
Can the 'inTaintTime' flag be cleaned up and used? For instance, a call to
BSScene.TaintedObject() could immediately execute the callback if already in taint time.
(DONE)

View File

@ -2382,6 +2382,32 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
return force; return force;
} }
public void llSetVelocity(LSL_Vector velocity, int local)
{
m_host.AddScriptLPS(1);
if (!m_host.ParentGroup.IsDeleted)
{
if (local != 0)
velocity *= llGetRot();
m_host.ParentGroup.RootPart.Velocity = velocity;
}
}
public void llSetAngularVelocity(LSL_Vector angularVelocity, int local)
{
m_host.AddScriptLPS(1);
if (!m_host.ParentGroup.IsDeleted)
{
if (local != 0)
angularVelocity *= llGetRot();
m_host.ParentGroup.RootPart.AngularVelocity = angularVelocity;
}
}
public LSL_Integer llTarget(LSL_Vector position, double range) public LSL_Integer llTarget(LSL_Vector position, double range)
{ {
m_host.AddScriptLPS(1); m_host.AddScriptLPS(1);

View File

@ -342,6 +342,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
void llSetDamage(double damage); void llSetDamage(double damage);
void llSetForce(LSL_Vector force, int local); void llSetForce(LSL_Vector force, int local);
void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local); void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local);
void llSetVelocity(LSL_Vector velocity, int local);
void llSetAngularVelocity(LSL_Vector angularVelocity, int local);
void llSetHoverHeight(double height, int water, double tau); void llSetHoverHeight(double height, int water, double tau);
void llSetInventoryPermMask(string item, int mask, int value); void llSetInventoryPermMask(string item, int mask, int value);
void llSetLinkAlpha(int linknumber, double alpha, int face); void llSetLinkAlpha(int linknumber, double alpha, int face);

View File

@ -1548,6 +1548,16 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
m_LSL_Functions.llSetForceAndTorque(force, torque, local); m_LSL_Functions.llSetForceAndTorque(force, torque, local);
} }
public void llSetVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetVelocity(force, local);
}
public void llSetAngularVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetAngularVelocity(force, local);
}
public void llSetHoverHeight(double height, int water, double tau) public void llSetHoverHeight(double height, int water, double tau)
{ {
m_LSL_Functions.llSetHoverHeight(height, water, tau); m_LSL_Functions.llSetHoverHeight(height, water, tau);

View File

@ -107,7 +107,7 @@ namespace OpenSim.Server.Handlers.Simulation
} }
else else
{ {
m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method); m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message (caller is {1})", method, Util.GetCallerIP(request));
responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
responsedata["str_response_string"] = "Method not allowed"; responsedata["str_response_string"] = "Method not allowed";

View File

@ -65,7 +65,7 @@ namespace OpenSim.Services.Connectors.SimianGrid
public void PostInitialise() { } public void PostInitialise() { }
public void Close() { } public void Close() { }
public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); } public SimianPresenceServiceConnector() { }
public string Name { get { return "SimianPresenceServiceConnector"; } } public string Name { get { return "SimianPresenceServiceConnector"; } }
public void AddRegion(Scene scene) public void AddRegion(Scene scene)
{ {
@ -121,6 +121,7 @@ namespace OpenSim.Services.Connectors.SimianGrid
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("=")) if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/'; serviceUrl = serviceUrl + '/';
m_serverUrl = serviceUrl; m_serverUrl = serviceUrl;
m_activityDetector = new SimianActivityDetector(this);
m_Enabled = true; m_Enabled = true;
} }
} }

View File

@ -156,7 +156,7 @@ namespace OpenSim.Services.UserAccountService
public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{ {
//m_log.DebugFormat("[Grid User Service]: SetLastPosition for {0}", userID); m_log.DebugFormat("[GRID USER SERVICE]: SetLastPosition for {0}", userID);
GridUserData d = m_Database.Get(userID); GridUserData d = m_Database.Get(userID);
if (d == null) if (d == null)
{ {

View File

@ -919,54 +919,72 @@
; ## Joint support ; ## Joint support
; ## ; ##
; if you would like physics joints to be enabled through a special naming convention in the client, set this to true. ; If you would like physics joints to be enabled through a special naming
; (see NINJA Physics documentation, http://opensimulator.org/wiki/NINJA_Physics) ; convention in the client, set this to true.
; default is false ; (See NINJA Physics documentation, http://opensimulator.org/wiki/NINJA_Physics)
; Default is false
;use_NINJA_physics_joints = true ;use_NINJA_physics_joints = true
; ## ; ##
; ## additional meshing options ; ## additional meshing options
; ## ; ##
; physical collision mesh proxies are normally created for complex prim shapes, and collisions for simple boxes and ; Physical collision mesh proxies are normally created for complex prim shapes,
; spheres are computed algorithmically. If you would rather have mesh proxies for simple prims, you can set this to ; and collisions for simple boxes and spheres are computed algorithmically.
; true. Note that this will increase memory usage and region startup time. Default is false. ; If you would rather have mesh proxies for simple prims, you can set this to
; true. Note that this will increase memory usage and region startup time.
; Default is false.
;force_simple_prim_meshing = true ;force_simple_prim_meshing = true
[BulletSim] [BulletSim]
; All the BulletSim parameters can be displayed with the console command "physics get all" ; All the BulletSim parameters can be displayed with the console command
; and all are defined in the source file OpenSim/Regions/Physics/BulletSPlugin/BSParam.cs. ; "physics get all" and all are defined in the source file
; OpenSim/Regions/Physics/BulletSPlugin/BSParam.cs.
; There are two bullet physics libraries, bulletunmanaged is the default and is a native c++ dll ; There are two bullet physics libraries, bulletunmanaged is the default and is a
; bulletxna is a managed C# dll. They have comparible functionality but the c++ one is much faster. ; native c++ dll bulletxna is a managed C# dll. They have comparible functionality
; but the c++ one is much faster.
BulletEngine = "bulletunmanaged" BulletEngine = "bulletunmanaged"
; BulletEngine = "bulletxna" ; BulletEngine = "bulletxna"
; Terrain Implementation ; BulletSim can run on its own thread independent of the simulator's heartbeat
TerrainImplementation = 1 ; 0=Heightfield, 1=mesh ; thread. Enabling this will nto let the physics engine slow down avatar movement, etc.
; For mesh terrain, the detail of the created mesh. '1' gives 256x256 (heightfield resolution). '2' UseSeparatePhysicsThread = false
; gives 512x512. Etc. Cannot be larger than '4'. Higher magnification uses lots of memory.
; Terrain implementation can use either Bullet's heightField or BulletSim can build
; a mesh. 0=heightField, 1=mesh
TerrainImplementation = 1
; For mesh terrain, the detail of the created mesh. '1' gives 256x256 (heightfield
; resolution). '2' gives 512x512. Etc. Cannot be larger than '4'. Higher
; magnification uses lots of memory.
TerrainMeshMagnification = 2 TerrainMeshMagnification = 2
; Avatar physics height adjustments. http://opensimulator.org/wiki/BulletSim#Adjusting_Avatar_Height ; Avatar physics height adjustments.
; http://opensimulator.org/wiki/BulletSim#Adjusting_Avatar_Height
AvatarHeightLowFudge = -0.2 ; Adjustment at low end of height range AvatarHeightLowFudge = -0.2 ; Adjustment at low end of height range
AvatarHeightMidFudge = 0.1 ; Adjustment at mid point of avatar height range AvatarHeightMidFudge = 0.1 ; Adjustment at mid point of avatar height range
AvatarHeightHighFudge = 0.1 ; Adjustment at high end of height range AvatarHeightHighFudge = 0.1 ; Adjustment at high end of height range
; Default linkset implmentation ; Default linkset implmentation
; 'Constraint' uses physics constraints to hold linkset together. 'Compound' builds a compound ; 'Constraint' uses physics constraints to hold linkset together. 'Compound'
; shape from the children shapes to create a single physical shape. 'Compound' uses a lot less CPU time. ; builds a compound shape from the children shapes to create a single physical
; shape. 'Compound' uses a lot less CPU time.
LinkImplementation = 1 ; 0=constraint, 1=compound LinkImplementation = 1 ; 0=constraint, 1=compound
; If 'true', offset a linkset's origin based on mass of linkset parts.
LinksetOffsetCenterOfMass = false
; If 'true', turn scuplties into meshes ; If 'true', turn scuplties into meshes
MeshSculptedPrim = true MeshSculptedPrim = true
; If 'true', force simple prims (box and sphere) to be meshed ; If 'true', force simple prims (box and sphere) to be meshed
; If 'false', the Bullet native special case shape is used for square rectangles and even dimensioned spheres ; If 'false', the Bullet native special case shape is used for square rectangles
; and even dimensioned spheres.
ForceSimplePrimMeshing = false ForceSimplePrimMeshing = false
; If 'true', when creating meshes, remove all triangles that have two equal vertexes. ; If 'true', when creating meshes, remove all triangles that have two equal vertexes.
; Happens often in sculpties. If turned off, there will be some doorways that cannot be walked through. ; Happens often in sculpties. If turned off, there will be some doorways
; that cannot be walked through.
ShouldRemoveZeroWidthTriangles = true ShouldRemoveZeroWidthTriangles = true
; If 'true', use convex hull definition in mesh asset if present. ; If 'true', use convex hull definition in mesh asset if present.